コード例 #1
0
void IE_Imp_WordPerfect::openEndnote(const WPXPropertyList & /*propList*/)
{
	if (m_bHdrFtrOpenCount) return; // HACK
	const gchar** propsArray = NULL;
	
	UT_String endnoteId;
	UT_String_sprintf(endnoteId,"%i",UT_rand());	
	
	propsArray = static_cast<const gchar **>(UT_calloc(7, sizeof(gchar *)));
	propsArray [0] = "type";
	propsArray [1] = "endnote_ref";
	propsArray [2] = "endnote-id";
	propsArray [3] = endnoteId.c_str();
	propsArray [4] = NULL;
	propsArray [5] = NULL;
	propsArray [6] = NULL;
	X_CheckDocumentError(appendObject(PTO_Field, propsArray));

	const gchar * attribs[3] ={"endnote-id", endnoteId.c_str(), NULL};
	X_CheckDocumentError(appendStrux(PTX_SectionEndnote,attribs));
	
	X_CheckDocumentError(appendStrux(PTX_Block,NULL));
	m_bRequireBlock = false;

	propsArray = static_cast<const gchar **>(UT_calloc(7, sizeof(gchar *)));
	propsArray [0] = "type";
	propsArray [1] = "endnote_anchor";
	propsArray [2] = "endnote-id";
	propsArray [3] = endnoteId.c_str();
	propsArray [4] = NULL;
	propsArray [5] = NULL;
	propsArray [6] = NULL;
	X_CheckDocumentError(appendObject(PTO_Field, propsArray));
}
コード例 #2
0
ファイル: xap_Dictionary.cpp プロジェクト: Distrotech/abiword
bool XAP_Dictionary::addWord(const UT_UCSChar * pWord, UT_uint32 len)
{
	char * key = static_cast<char *>(UT_calloc(len+1, sizeof(char)));
	UT_UCSChar * copy = static_cast<UT_UCSChar *>(UT_calloc(len+1, sizeof(UT_UCSChar)));
    if (!key || !copy)
	{
		UT_DEBUGMSG(("mem failure adding word to dictionary\n"));
		FREEP(key);
		FREEP(copy);
		return false;
	}
	UT_uint32 i = 0;
	for (i = 0; i < len; i++)
	{
		UT_UCSChar currentChar;
		currentChar = pWord[i];
		// map smart quote apostrophe to ASCII right single quote
		if (currentChar == UCS_RQUOTE) currentChar = '\'';
		key[i] = static_cast<char>(static_cast<unsigned char>(pWord[i]));
		copy[i] = currentChar;
		xxx_UT_DEBUGMSG(("addWord: key[%d] = %c %d \n",i,key[i],key[i]));
		if(key[i] == 0)
		{
			break;
		}
	}
	key[i] = 0;
//
// Get exactly the same length.
//
	char * key2 = g_strdup(key);
	copy[i] = 0;
#if 0
//
// Useful debugging code
//
	char * ucs_dup = static_cast<char *>(UT_calloc(2*len+1, sizeof(char)));
	UT_UCS4_strcpy_to_char( ucs_dup, copy);
	UT_DEBUGMSG(("Inserting word %s with key %s into hash \n",ucs_dup,key));
	FREEP(ucs_dup);

#endif
	if(!m_hashWords.insert(key2,copy))
		FREEP(copy);
	
	FREEP(key);
	FREEP(key2);

	// TODO: is this right?
	m_bDirty = true;
	return true;
}
コード例 #3
0
/*
	Does a stringSet exist on disk?
*/
bool	AP_Win32App::doesStringSetExist(const char* pLocale)
{
	FILE* in;
	const char * szDirectory = NULL;	

	UT_return_val_if_fail(pLocale, false);
	
	getPrefsValueDirectory(true,AP_PREF_KEY_StringSetDirectory,&szDirectory);
	UT_return_val_if_fail(((szDirectory) && (*szDirectory)), false);

	char * szPathname = (char *)UT_calloc(sizeof(char),strlen(szDirectory)+strlen(pLocale)+100);
	UT_return_val_if_fail(szPathname, false);
				
	sprintf(szPathname,"%s%s%s.strings",
				szDirectory,
				((szDirectory[strlen(szDirectory)-1]=='\\') ? "" : "\\"),
				pLocale);				
	
	in =  fopen(szPathname, "r");	
	g_free (szPathname);
	
	if (in)
	{
		fclose(in);		
		return true;
	}			
	
	return false;
}
コード例 #4
0
int RX_bin_search(rx_srch_mt search_mode, int par_a, int par_b, rx_tree_t *tree, ip_prefix_t *prefix, GList **datleaves, int max_count) {
    rx_nodcpy_t stack[128];
    rx_dataleaf_t *leafptr;
    int stkcnt, resnum = 0;
    GList *nodlist = NULL, *nitem, *iitem;
    rx_node_t *curnode;
    rx_nodcpy_t *curcpy;
    rx_datref_t *datref;
    rx_stk_mt dmode;

    /* more specific node search may start from a glue node, */
    /* for all others the stack should not contain glues. */

    dmode = (search_mode == RX_SRCH_MORE || search_mode == RX_SRCH_DBLS || search_mode == RX_SRCH_RANG) ? RX_STK_QUERY_ALLNOD : RX_STK_QUERY_NOGLUE;

    rx_build_stack(stack, &stkcnt, tree, prefix, dmode);

#ifdef DEBUG_RADIX
    char DEBUGbuf[256];
    int DEBUGi;
    IP_pref_b2a(prefix, DEBUGbuf, 256);
    fprintf(stderr, ">>> RX_bin_search(%d, %d, %d, %s) = %d results after rx_build_stack:\n", search_mode, par_a, par_b, DEBUGbuf, stkcnt);
    for (DEBUGi = 0; DEBUGi < stkcnt; DEBUGi++) {
        rx_nod_print(&stack[DEBUGi].cpy, DEBUGbuf, 256);
        fprintf(stderr, ">>> %s\n", DEBUGbuf);
    }
#endif

    rx_nod_search(search_mode, par_a, par_b, tree, prefix, stack, stkcnt, &nodlist, 1000);

//    LG_log(rx_context, LG_DEBUG, "RX_bin_search: processing nodes");

    for (nitem = g_list_first(nodlist); nitem != NULL; nitem = g_list_next(nitem)) {

        resnum++;
        curcpy = nitem->data;
        curnode = curcpy->srcptr;

        /* iterate through dataleafs attached to this node */
        for (iitem = g_list_first(curnode->leaves_ptr); iitem != NULL; iitem = g_list_next(iitem)) {
            leafptr = (rx_dataleaf_t *) iitem->data;

            /* XXX never add composed inetnum for exact prefix search
               (but do for exact range search...) - must be solved in upper layer. */
            datref = (rx_datref_t *) UT_calloc(1, sizeof(rx_datref_t));
            datref->leafptr = leafptr;

            *datleaves = g_list_prepend(*datleaves, datref);
        }
    }

    wr_clear_list(&nodlist);

//    LG_log(rx_context, LG_DEBUG, "RX_bin_search: found %d nodes", resnum);

    /* the LL of answers (*datleaves) contains pointers to answer structs,
     that SHOULD BE NORMALIZED HERE (==with no redundant entries) */

    return RX_OK;
}
コード例 #5
0
EV_Toolbar_ActionSet::EV_Toolbar_ActionSet(XAP_Toolbar_Id first, XAP_Toolbar_Id last)
{
	// TODO tis bad to call g_try_malloc/UT_calloc from a constructor, since we cannot report failure.
	// TODO move this allocation to somewhere else.
	m_actionTable = static_cast<EV_Toolbar_Action **>(UT_calloc((last-first+1),sizeof(EV_Toolbar_Action *)));
	m_first = first;
	m_last = last;
}
コード例 #6
0
char * AP_Dialog_MarkRevisions::getComment1()
{
	_initRevision();

	if(!m_pRev || m_bForceNew)
		return NULL;

	bool bFree = false;

	const UT_UCS4Char * pC = m_pRev->getDescription();

	if(!pC)
		return NULL;

	// now we run this string through fribidi
	if(XAP_App::getApp()->theOSHasBidiSupport() == XAP_App::BIDI_SUPPORT_NONE)
	{
		UT_UCS4Char *pStr2 = 0;
		UT_uint32 iLen = UT_UCS4_strlen(pC);

		pStr2  = (UT_UCS4Char *)UT_calloc( iLen + 1, sizeof(UT_UCS4Char));
		UT_return_val_if_fail(pStr2,NULL);
		bFree = true;

		UT_BidiCharType iDomDir = UT_bidiGetCharType(pC[0]);

		UT_bidiReorderString(pC, iLen, iDomDir, pStr2);
		pC = pStr2;

	}

	char * pComment = (char *)UT_calloc(UT_UCS4_strlen(pC) + 1, sizeof(char));
	UT_return_val_if_fail(pComment,NULL);

	UT_UCS4_strcpy_to_char(pComment,pC);

	if(bFree)
	{
		FREEP(pC);
	}

	return pComment;
}
コード例 #7
0
ファイル: ud_misc.c プロジェクト: agoston/whoisserver-legacy
/************************************************************
* Transaction_t *transaction_new()                          *
*                                                           *
* Creates a transaction                                     *
*                                                           *
************************************************************/
Transaction_t *
transaction_new (SQ_connection_t *sql_connection, C_Type_t class_type, LG_context_t *src_ctx) 
{
  Transaction_t *tr = (Transaction_t *)UT_calloc(1, sizeof(Transaction_t));

  tr->sql_connection = sql_connection;
  tr->class_type = class_type;
  tr->thread_upd=TR_UPDATE;
  tr->thread_ins=TR_INSERT;
  tr->succeeded = 1;
  tr->error_script = g_string_sized_new(STR_XL);
  tr->K = g_string_sized_new(STR_L);
  tr->sequence_id=1; /* we start from 1*/
  tr->packptr=UT_calloc(1, sizeof(rp_upd_pack_t));
  tr->query = g_string_sized_new(STR_XL);
  tr->src_ctx = src_ctx;
  
  return tr;
} /* transaction_new() */
コード例 #8
0
ファイル: xap_Dictionary.cpp プロジェクト: Distrotech/abiword
bool XAP_Dictionary::addWord(const char * word)
{
	UT_sint32 len = strlen(word);
	if(len <=0)
	{
		return false;
	}
	UT_UCSChar * ucs_dup = static_cast<UT_UCSChar *>(UT_calloc(len+1, sizeof(UT_UCSChar)));
	UT_UCS4_strcpy_char(ucs_dup, word);
	addWord(ucs_dup,len);
	FREEP(ucs_dup);
	return true;
}
コード例 #9
0
char * AP_Dialog_MarkRevisions::getRadio1Label()
{
	_initRevision();

	if(!m_pRev || m_bForceNew)
		return NULL;

	UT_return_val_if_fail(m_pSS,NULL);
	const char * pLabel = m_pSS->getValue(AP_STRING_ID_DLG_MarkRevisions_Check1Label);

	UT_return_val_if_fail(pLabel,NULL);
	char * pBuff = (char*)UT_calloc(strlen(pLabel) + 35, sizeof(char));

	
	sprintf(pBuff, pLabel, m_pRev->getId());

	return pBuff;
}
コード例 #10
0
ファイル: xap_Dictionary.cpp プロジェクト: Distrotech/abiword
/*!
 * Returns true if the word given is found in the users custom dictionary.
\param const UT_UCSChar * pWord the word to look for suggestion for
\param UT_uint32 len the length of the word
\returns UT_Vector * pVecSuggestions this a vector of suggestions.
The returner is responsible for deleting these words. 
*/
void XAP_Dictionary::suggestWord(UT_GenericVector<UT_UCSChar *> * pVecSuggestions, const UT_UCSChar * pWord, UT_uint32 len)
{
  //
  // Get the words in the local dictionary
  //
  UT_GenericVector<UT_UCSChar *> * pVec = m_hashWords.enumerate();
  UT_ASSERT(pVec);
  UT_uint32 i=0;
  UT_uint32 count = pVec->getItemCount();
  //
  // Turn our word into a NULL teminated string
  //
  UT_UCSChar * pszWord = static_cast<UT_UCSChar*>(UT_calloc(len+1, sizeof(UT_UCSChar)));
  for(i=0; i< len; i++)
  {
    pszWord[i] = pWord[i];
  }
  pszWord[len] = 0;
  //
  // Loop over all the words in our custom doctionary and add them to the 
  //the suggestions if they're possibilities.
  //
  for(i=0; i< count; i++)
  {
    UT_UCSChar * pszDict = pVec->getNthItem(i);
    UT_UCSChar * pszReturn = NULL;
    float lenDict = static_cast<float>(UT_UCS4_strlen(pszDict));
    UT_uint32 wordInDict = countCommonChars(pszDict,pszWord);
    UT_uint32 dictInWord = countCommonChars(pszWord,pszDict);
    float flen = static_cast<float>(len);
    float frac1 = (static_cast<float>(wordInDict)) / flen;
    float frac2 = (static_cast<float>(dictInWord)) / lenDict;

    if((frac1 > 0.8) && (frac2 > 0.8))
    {
	  UT_UCS4_cloneString(&pszReturn, pszDict);
	  pVecSuggestions->addItem(pszReturn);
    }
  }
  FREEP(pszWord);
  DELETEP(pVec);
}
コード例 #11
0
ファイル: ut_growbuf.cpp プロジェクト: Distrotech/abiword
bool UT_GrowBuf::_growBuf(UT_uint32 spaceNeeded)
{
	// expand the buffer if necessary to accomidate the requested space.
	// round up to the next multiple of the chunk size.
	
	UT_uint32 newSize = ((m_iSize+spaceNeeded+m_iChunk-1)/m_iChunk)*m_iChunk;
	UT_GrowBufElement * pNew = static_cast<UT_GrowBufElement *>(UT_calloc(newSize,sizeof(*m_pBuf))); // Why not use g_try_realloc ? - fjf
	if (!pNew)
		return false;
	
	if (m_pBuf)
	{
		memmove(pNew,m_pBuf,m_iSize*sizeof(*m_pBuf));
		g_free(m_pBuf);
	}

	m_pBuf = pNew;
	m_iSpace = newSize;

	return true;
}
コード例 #12
0
ファイル: ap_Win32App.cpp プロジェクト: lokeshguddu/AbiWord
/*
	Does a stringSet exist on disk?
*/
bool	AP_Win32App::doesStringSetExist(const char* pLocale)
{
	HANDLE in;
	const char * szDirectory = NULL;

	UT_return_val_if_fail(pLocale, false);
	
	getPrefsValueDirectory(true,AP_PREF_KEY_StringSetDirectory,&szDirectory);
	UT_return_val_if_fail(((szDirectory) && (*szDirectory)), false);

	char *szPathname = (char*) UT_calloc(sizeof(char),strlen(szDirectory)+strlen(pLocale)+100);
	UT_return_val_if_fail(szPathname, false);
	
	char *szDest = szPathname;
	strcpy(szDest, szDirectory);
	szDest += strlen(szDest);
	if ((szDest > szPathname) && (szDest[-1]!='\\'))
		*szDest++='\\';
	lstrcpyA(szDest,pLocale);
	lstrcatA(szDest,".strings");

	UT_Win32LocaleString wsFilename;
	wsFilename.fromUTF8(szPathname);

	in = CreateFileW(wsFilename.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,
		OPEN_EXISTING,0,NULL);
	g_free (szPathname);
	
	if (in!=INVALID_HANDLE_VALUE)
	{
		CloseHandle(in);
		return true;
	}			
	
	return false;
}
コード例 #13
0
ファイル: xap_Dictionary.cpp プロジェクト: Distrotech/abiword
bool XAP_Dictionary::isWord(const UT_UCSChar * pWord, UT_uint32 len) const
{
	char * key = static_cast<char*>(UT_calloc(len+1, sizeof(char)));
	if (!key)
	{
		UT_DEBUGMSG(("mem failure looking up word in dictionary\n"));
		FREEP(key);
		return false;
	}
	UT_uint32 i =0;
	for (i = 0; i < len; i++)
	{
		key[i] = static_cast<char>(static_cast<unsigned char>( pWord[i] ));
		xxx_UT_DEBUGMSG(("isword key[%d] = %c %d \n",i,key[i],key[i]));
		if(key[i] == 0)
			break;
	}
	key[i] = 0;
	char * key2 = g_strdup(key);
	bool contains = m_hashWords.contains (key2, NULL);
	FREEP(key);
	FREEP(key2);
	return contains;
}
コード例 #14
0
ファイル: ut_Win32OS.cpp プロジェクト: lokeshguddu/AbiWord
wchar_t * UT_GetDefaultPrinterName()
{
	UT_uint32 iBufferSize = 128; // will become 2x bigger immediately in the loop
	wchar_t * pPrinterName = NULL; 
	DWORD rc;
	
	do
	{
		iBufferSize *= 2;

		if(pPrinterName)
			g_free(pPrinterName);
		
		pPrinterName = (wchar_t *) UT_calloc(sizeof(wchar_t),iBufferSize);
		UT_return_val_if_fail( pPrinterName, NULL );
		
		// the method of obtaining the name is version specific ...
		OSVERSIONINFOW osvi;
		DWORD iNeeded, iReturned, iBuffSize;
		LPPRINTER_INFO_5W pPrinterInfo;
		wchar_t* p;

		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
		GetVersionExW(&osvi);

		if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
		{
			// get size of the buffer needed to call enum printers
			if (!EnumPrintersW(PRINTER_ENUM_DEFAULT,NULL,5,NULL,0,&iNeeded,&iReturned))
			{
				if ((rc = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
				{
					return NULL;
				}
			}

			// allocate the buffer
			if ((pPrinterInfo = (LPPRINTER_INFO_5W)LocalAlloc(LPTR,iNeeded)) == NULL)
			{
				rc = GetLastError();
			}
			else
			{
				// now get the default printer
				if (!EnumPrintersW(PRINTER_ENUM_DEFAULT,NULL,5,
								  (LPBYTE) pPrinterInfo,iNeeded,&iNeeded,&iReturned))
				{
					rc = GetLastError();
				}
				else
				{
					if (iReturned > 0)
					{
						// here we copy the name to our own buffer
						if ((DWORD) wcslen(pPrinterInfo->pPrinterName) > iBufferSize-1)
						{
							rc = ERROR_INSUFFICIENT_BUFFER;
						}
						else
						{
							wcscpy(pPrinterName,pPrinterInfo->pPrinterName);
							rc = ERROR_SUCCESS;
						}
					}
					else
					{
						*pPrinterName = '0';
						rc = ERROR_SUCCESS;
					}
				}

				LocalFree(pPrinterInfo);
			}
		}
		else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
		{
			if (osvi.dwMajorVersion >= 5) /* Windows 2000 or later */
			{
				iBuffSize = iBufferSize;

				HMODULE hWinSpool = LoadLibraryW(L"winspool.drv");
				if (!hWinSpool)
					return NULL;

				HRESULT (WINAPI * fnGetDefaultPrinter)(LPWSTR, LPDWORD) =
					(HRESULT (WINAPI * )(LPWSTR, LPDWORD)) GetProcAddress(hWinSpool, GETDEFAULTPRINTER);
				
				if (!fnGetDefaultPrinter)
				{
					FreeLibrary(hWinSpool);
					return NULL;
				}

                bool i =false;
				if (!fnGetDefaultPrinter(pPrinterName,&iBuffSize))
                        i = true;
                         
                if(i)
					rc = GetLastError();
				else
					rc = ERROR_SUCCESS;

				FreeLibrary(hWinSpool);
			}
			else /* Windows NT 4.0 or earlier */
			{
				if (GetProfileStringW(L"windows",L"device",L"",pPrinterName,iBufferSize) == iBufferSize-1)
				{
					rc = ERROR_INSUFFICIENT_BUFFER;
				}
				else
				{
					p = pPrinterName;
					while (*p != '0' && *p !=L',')
						++p;
					*p = '0';

					rc = ERROR_SUCCESS;
				}
			}
		}
	}
	while (rc == ERROR_INSUFFICIENT_BUFFER);
	
	return pPrinterName;
}
コード例 #15
0
void AP_Win32Dialog_New::_doChoose()
{

	XAP_Dialog_Id id = XAP_DIALOG_ID_FILE_OPEN;

	XAP_DialogFactory * pDialogFactory
		= (XAP_DialogFactory *) m_pFrame->getDialogFactory();

	XAP_Dialog_FileOpenSaveAs * pDialog
		= (XAP_Dialog_FileOpenSaveAs *)(pDialogFactory->requestDialog(id));
	UT_return_if_fail (pDialog);

	pDialog->setCurrentPathname(0);
	pDialog->setSuggestFilename(false);

	UT_uint32 filterCount = IE_Imp::getImporterCount();
	const char ** szDescList = (const char **) UT_calloc(filterCount + 1,
													  sizeof(char *));
	UT_return_if_fail(szDescList);
	const char ** szSuffixList = (const char **) UT_calloc(filterCount + 1,
														sizeof(char *));
	if(!szSuffixList)
	{
		UT_ASSERT_HARMLESS(szSuffixList);
		FREEP(szDescList);
		return;
	}
	IEFileType * nTypeList = (IEFileType *) UT_calloc(filterCount + 1,
												   sizeof(IEFileType));
	if(!nTypeList)
	{
		UT_ASSERT_HARMLESS(nTypeList);
		FREEP(szDescList);
		FREEP(szSuffixList);
		return;
	}
	UT_uint32 k = 0;

	while (IE_Imp::enumerateDlgLabels(k, &szDescList[k], 
									  &szSuffixList[k], &nTypeList[k]))
			k++;

	pDialog->setFileTypeList(szDescList, szSuffixList, 
							 (const UT_sint32 *) nTypeList);

	pDialog->setDefaultFileType(IE_Imp::fileTypeForSuffix(".abw"));

	pDialog->runModal(m_pFrame);

	XAP_Dialog_FileOpenSaveAs::tAnswer ans = pDialog->getAnswer();
	bool bOK = (ans == XAP_Dialog_FileOpenSaveAs::a_OK);

	if (bOK)
	{
		const char * szResultPathname = pDialog->getPathname();
		if (szResultPathname && *szResultPathname)
		{
			// update the entry box
			_win32Dialog.setControlText( AP_RID_DIALOG_NEW_EBX_EXISTING, 
			                             szResultPathname);
			setFileName (szResultPathname);
		}
	}
}
コード例 #16
0
bool pt_PieceTable::_realChangeSpanFmt(PTChangeFmt ptc,
									   PT_DocPosition dpos1,
									   PT_DocPosition dpos2,
									   const gchar ** attributes,
									   const gchar ** properties,
									   bool bRevisionDelete)
{
	// apply a span-level formatting change to the given region.

	UT_return_val_if_fail (m_pts==PTS_Editing,false);
    _tweakFieldSpan(dpos1,dpos2);
//
// Deal with case of exactly selecting the endOfFootnote
//
	pf_Frag * pfEndDum = m_fragments.findFirstFragBeforePos(dpos2);
	if(isEndFootnote(pfEndDum))
	{
		if(dpos2 > dpos1)
		{
			dpos2--;
		}
	}
//
// Deal with addStyle
//
	bool bApplyStyle = (PTC_AddStyle == ptc);
	const gchar ** sProps = NULL;
	const gchar ** lProps = properties;
	if(bApplyStyle)
	{
//
// OK for styles we expand out all defined properties including BasedOn styles
// Then we use these to eliminate any specfic properties in the current strux
// Then properties in the current strux will resolve to those defined in the
// style (they exist there) to specifc values in strux (if not overridden by
// the style) then finally to default value.
//
		const gchar * szStyle = UT_getAttribute(PT_STYLE_ATTRIBUTE_NAME,attributes);
		PD_Style * pStyle = NULL;
		UT_return_val_if_fail (szStyle,false);
		getDocument()->getStyle(szStyle,&pStyle);
		UT_return_val_if_fail (pStyle,false);
		UT_Vector vProps;
//
// Get the vector of properties
//
		pStyle->getAllProperties(&vProps,0);
//
// Finally make the const gchar * array of properties
//
		UT_uint32 countp = vProps.getItemCount() + 1;
		sProps = (const gchar **) UT_calloc(countp, sizeof(gchar *));
		countp--;
		UT_uint32 i;
		for(i=0; i<countp; i++)
		{
			sProps[i] = (const gchar *) vProps.getNthItem(i);
		}
		sProps[i] = NULL;
		lProps = sProps;
	}
	if (dpos1 == dpos2) 		// if length of change is zero, then we have a toggle format.
	{
		UT_uint32 startUndoPos = m_history.getUndoPos();
		bool bRes = _insertFmtMarkFragWithNotify(ptc,dpos1,attributes,lProps);
		UT_uint32 endUndoPos = m_history.getUndoPos();
		// Won't be a persistant change if it's just a toggle
		PX_ChangeRecord *pcr=0;
		m_history.getUndo(&pcr,true);
		if (pcr && (startUndoPos != endUndoPos) )
		{
			UT_DEBUGMSG(("Setting persistance of change to false\n"));
			pcr->setPersistance(false);
			m_history.setSavePosition(m_history.getSavePosition()+1);
		}
		if(bApplyStyle)
		{
			FREEP(sProps);
		}
		return bRes;
	}

	UT_return_val_if_fail (dpos1 < dpos2,false);
	bool bHaveAttributes, bHaveProperties;
	bHaveAttributes = (attributes && *attributes);
	bHaveProperties = (lProps && *lProps);

	pf_Frag * pf_First;
	pf_Frag * pf_End;
	PT_BlockOffset fragOffset_First;
	PT_BlockOffset fragOffset_End;

	bool bFound;
	bFound = getFragsFromPositions(dpos1,dpos2,&pf_First,&fragOffset_First,&pf_End,&fragOffset_End);
	UT_return_val_if_fail (bFound, false);

#if 0
	{
		pf_Frag * pf1, * pf2;
		PT_BlockOffset fo1, fo2;

		bool bFound1 = getFragFromPosition(dpos1,&pf1,&fo1);
		bool bFound2 = getFragFromPosition(dpos2,&pf2,&fo2);
		UT_return_val_if_fail (bFound1 && bFound2, false);
		UT_return_val_if_fail ((pf1==pf_First) && (fragOffset_First==fo1), false);
		UT_return_val_if_fail ((pf2==pf_End) && (fragOffset_End==fo2), false);
	}
#endif

	// see if the amount of text to be changed is completely
	// contained within a single fragment.  if so, we have a
	// simple change.  otherwise, we need to set up a multi-step
	// change -- it may not actually take more than one step,
	// but it is too complicated to tell at this point, so we
	// assume it will and don't worry about it.
	//
	// we are in a simple change if the beginning and end are
	// within the same fragment.

	// NOTE: if we call beginMultiStepGlob() we ***MUST*** call
	// NOTE: endMultiStepGlob() before we return -- otherwise,
	// NOTE: the undo/redo won't be properly bracketed.

	bool bSimple = (pf_First == pf_End);
	if (!bSimple)
		beginMultiStepGlob();

	pf_Frag_Strux * pfsContainer = NULL;
	pf_Frag * pfNewEnd;
	UT_uint32 fragOffsetNewEnd;

	UT_uint32 length = dpos2 - dpos1;
	while (length != 0)
	{
		// FIXME: Special check to support a FmtMark at the end of the
		// document. This is necessary because FmtMarks don't have a
		// length...  See bug 452.
		if (0 == length
			&& (!pf_First || pf_Frag::PFT_FmtMark != pf_First->getType()))
			break;

		UT_return_val_if_fail (dpos1+length==dpos2, false);

		UT_uint32 lengthInFrag = pf_First->getLength() - fragOffset_First;
		UT_uint32 lengthThisStep = UT_MIN(lengthInFrag, length);

		switch (pf_First->getType())
		{
		case pf_Frag::PFT_EndOfDoc:
		default:
			UT_DEBUGMSG(("fragment type: %d\n",pf_First->getType()));
			UT_ASSERT_HARMLESS(0);
			if(bApplyStyle)
			{
				FREEP(sProps);
			}
			return false;

		case pf_Frag::PFT_Strux:
			{
				// we are only applying span-level changes, so we ignore strux.
				// but we still need to update our loop indices.

				pfNewEnd = pf_First->getNext();
				fragOffsetNewEnd = 0;
				pfsContainer = static_cast<pf_Frag_Strux *> (pf_First);
				bool bFoundStrux = false;
				if(isEndFootnote(pfsContainer))
				{
					bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux, false);
				}
			}
			break;

		case pf_Frag::PFT_Text:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}
				}

				bool bResult;
				bResult	= _fmtChangeSpanWithNotify(ptc,static_cast<pf_Frag_Text *>(pf_First),
											   fragOffset_First,dpos1,lengthThisStep,
											   attributes,lProps,
											   pfsContainer,&pfNewEnd,&fragOffsetNewEnd,bRevisionDelete);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		case pf_Frag::PFT_Object:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}
				}

				bool bResult;
				bResult	= _fmtChangeObjectWithNotify(ptc,static_cast<pf_Frag_Object *>(pf_First),
												 fragOffset_First,dpos1,lengthThisStep,
												 attributes,lProps,
												 pfsContainer,&pfNewEnd,&fragOffsetNewEnd,false);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		case pf_Frag::PFT_FmtMark:
			{
				if (!pfsContainer)
				{
					bool bFoundStrux;
					bFoundStrux = _getStruxFromPosition(dpos1,&pfsContainer);
					UT_return_val_if_fail (bFoundStrux,false);
					if(isEndFootnote(pfsContainer))
					{
						bFoundStrux = _getStruxFromFragSkip(pfsContainer,&pfsContainer);
						UT_return_val_if_fail (bFoundStrux,false);
					}

				}

				bool bResult;
				bResult = _fmtChangeFmtMarkWithNotify(ptc,static_cast<pf_Frag_FmtMark *>(pf_First),
												  dpos1, attributes,lProps,
												  pfsContainer,&pfNewEnd,&fragOffsetNewEnd);
				UT_return_val_if_fail (bResult,false);
			}
			break;

		}

		dpos1 += lengthThisStep;
		length -= lengthThisStep;

		// since _fmtChange{Span,FmtMark,...}WithNotify(), can delete pf_First, mess with the
		// fragment list, and does some aggressive coalescing of
		// fragments, we cannot just do a pf_First->getNext() here.
		// to advance to the next fragment, we use the *NewEnd variables
		// that each of the cases routines gave us.

		pf_First = pfNewEnd;
		if (!pf_First)
			length = 0;
		fragOffset_First = fragOffsetNewEnd;
	}
	if(bApplyStyle)
	{
		FREEP(sProps);
	}

	if (!bSimple)
		endMultiStepGlob();

	return true;
}
コード例 #17
0
XAP_Args::XAP_Args(const char * szCmdLine)
{
    // build an argc,argv for this command line

    m_argc = 0;
    m_argv = NULL;
    m_szBuf = NULL;

    if (!szCmdLine || !*szCmdLine)
        return;

    // copy command line into work buffer
    // and put pointers to the tokens in m_argv
    //
    // we support (with apologies to Flex & Bison):
    //
    //    WHITE [ \t]+
    //    DQUOTE '"'
    //    SQUOTE '\''
    //    OTHER [^ \t'"]
    //
    //    T1 := OTHER*
    //    T2 := DQUOTE [^DQUOTE]* DQUOTE
    //    T3 := SQUOTE [^SQUOTE]* SQUOTE
    //
    //    WHITE ({T1|T2|T3}WHITE)* [WHITE]

    m_szBuf = g_strdup(szCmdLine);
    UT_ASSERT(m_szBuf);

    int count = 10;	// start with 10 and g_try_realloc if necessary
    int k = 0;
    char ** argv = (char **)UT_calloc(count,sizeof(char *));

    enum _state { S_START, S_INTOKEN, S_INDQUOTE, S_INSQUOTE } state;
    state = S_START;

#define GrowArrayIfNecessary()								\
	do	{	if (k==count)									\
			{	int newsize = (count+10)*sizeof(char *);	\
				argv = (char **)g_try_realloc(argv,newsize);	\
				count += 10;								\
		}} while (0)

    char * p = m_szBuf;
    while (*p)
    {
        switch (state)
        {
        case S_START:
            if ( (*p==' ') || (*p=='\t') )
            {
                p++;
                break;
            }

            if (*p=='\'')
            {
                state=S_INSQUOTE;
                *p++=0;					// don't include starting quote in token
            }
            else if (*p=='"')
            {
                state=S_INDQUOTE;
                *p++=0;					// don't include starting quote in token
            }
            else
                state=S_INTOKEN;

            GrowArrayIfNecessary();
            argv[k++] = p++;
            break;

        case S_INTOKEN:
            if ( (*p==' ') || (*p=='\t') )
            {
                state=S_START;
                *p++=0;
                break;
            }

            p++;
            break;

        case S_INDQUOTE:
            if ( (*p=='"') )
            {
                state=S_START;
                *p++=0;
                break;
            }

            p++;
            break;

        case S_INSQUOTE:
            if ( (*p=='\'') )
            {
                state=S_START;
                *p++=0;
                break;
            }

            p++;
            break;
        }
    }

    if (k==0)
    {
        FREEP(m_szBuf);
        return;
    }

    m_argv = argv;
    m_argc = k;

#ifdef DEBUG
    for (int kk=0; kk<m_argc; kk++)
        UT_DEBUGMSG(("ParsedCommandLine: argv[%d][%s]\n",kk,m_argv[kk]));
#endif

    return;
}
コード例 #18
0
ファイル: xap_Dlg_Print.cpp プロジェクト: Distrotech/abiword
bool XAP_Dialog_Print::_getPrintToFilePathname(XAP_Frame * pFrame,
												 const char * szSuggestedName)
{
	UT_return_val_if_fail(pFrame,false);
	UT_ASSERT(szSuggestedName && *szSuggestedName);

	XAP_Dialog_Id id = XAP_DIALOG_ID_PRINTTOFILE;
	
	XAP_DialogFactory * pDialogFactory
		= (XAP_DialogFactory *)(pFrame->getDialogFactory());

	XAP_Dialog_FileOpenSaveAs * pDialog
		= (XAP_Dialog_FileOpenSaveAs *)(pDialogFactory->requestDialog(id));
	UT_return_val_if_fail(pDialog,false);

	pDialog->setCurrentPathname(szSuggestedName);
	pDialog->setSuggestFilename(true);

	const char ** szDescList = NULL;
	const char ** szSuffixList = NULL;
	UT_sint32 * nTypeList = NULL;
	{
		// TODO : FIX THIS!  Make this pull dynamic types from the export
		// TODO : filter list (creat that while you're at it).

		// TODO : Right now we can just feed the dialog some static filters
		// TODO : that will be ignored by Windows but will be required
		// TODO : by Unix.

		UT_uint32 filterCount = 1;

		szDescList = (const char **) UT_calloc(filterCount + 1,
														  sizeof(char *));
		szSuffixList = (const char **) UT_calloc(filterCount + 1,
															sizeof(char *));
		// HACK : this should be IEFileType
		nTypeList = (UT_sint32 *) UT_calloc(filterCount + 1,
													 sizeof(UT_sint32));

		szDescList[0] = "PostScript 2.0";
		szSuffixList[0] = "ps";
		nTypeList[0] = 0;

		pDialog->setFileTypeList(szDescList, szSuffixList, (const UT_sint32 *) nTypeList);
	}

	pDialog->runModal(pFrame);

	XAP_Dialog_FileOpenSaveAs::tAnswer ans = pDialog->getAnswer();
	bool bOK = (ans == XAP_Dialog_FileOpenSaveAs::a_OK);

	if (bOK)
		m_szPrintToFilePathname = g_strdup(pDialog->getPathname());       

	FREEP(szDescList);
	FREEP(szSuffixList);
	FREEP(nTypeList);

	pDialogFactory->releaseDialog(pDialog);
	
	return bOK;
}
bool XAP_UnixDialog_FileOpenSaveAs::_run_gtk_main(XAP_Frame * pFrame,
        GtkWidget * filetypes_pulldown)
{
    /*
      Run the dialog in a loop to catch bad filenames.
      The location of this check being in this dialog loop
      could be considered temporary.  Doing this matches the Windows
      common control behavior (where the dialog checks everything
      for the programmer), but lacks flexibility for different
      uses of this dialog (file export, print export, directory
      (not file) selection).

      This check might need to be moved into the ap code which calls
      this dialog, and certain interfaces exposed so that the
      dialog is displayed throughout the verification.

      For right now you can signal this check on and off with
      bCheckWritePermission.
    */

    char * szDialogFilename = NULL;		// this is the file name returned from the dialog
    char * szFinalPathname = NULL;		// this is the file name after suffix addition, if any
    char * szFinalPathnameCopy = NULL;	// one to mangle when looking for dirs, etc.

    char * pLastSlash;

    // if m_bSave is not set, we're looking to OPEN a file.
    // otherwise we are looking to SAVE a file.
    if (!m_bSave)
    {
        while (1)
        {
            gtk_main();
            if (m_answer == a_CANCEL)			// The easy way out
                return false;

            m_szFinalPathnameCandidate = gtk_file_chooser_get_uri(m_FC);
            UT_ASSERT(m_szFinalPathnameCandidate);
            return (m_answer == a_OK);
        }
    }
    else
    {
        while(1)
        {
            gtk_main();
            if (m_answer == a_CANCEL)			// The easy way out
                return false;

            // Give us a filename we can mangle

            szDialogFilename = gtk_file_chooser_get_uri(m_FC);
            if (!szDialogFilename)
                continue;

            // We append the suffix of the default type, so the user doesn't
            // have to.  This is adapted from the Windows front-end code
            // (xap_Win32Dlg_FileOpenSaveAs.cpp), since it should act the same.
            // If, however, the user doesn't want suffixes, they don't have to have them.
            {
                //UT_uint32 end = g_strv_length(m_szSuffixes);
                UT_sint32 nFileType = XAP_comboBoxGetActiveInt(GTK_COMBO_BOX(filetypes_pulldown));

                // set to first item, which should probably be auto detect
                // TODO : "probably" isn't very good.
                UT_uint32 nIndex = 0;

                // the index in the types table will match the index in the suffix
                // table.  nFileType is the data we are searching for.
                if(m_nTypeList != NULL)
                {
                    for (UT_uint32 i = 0; m_nTypeList[i]; i++)
                    {
                        if (m_nTypeList[i] == nFileType)
                        {
                            nIndex = i;
                            break;
                        }
                    }
                }

                bool wantSuffix = true;
                XAP_Prefs *pPrefs= XAP_App::getApp()->getPrefs();
                pPrefs->getPrefsValueBool(static_cast<const gchar *>(XAP_PREF_KEY_UseSuffix), &wantSuffix);
                UT_DEBUGMSG(("UseSuffix: %d\n", wantSuffix));

                if (nFileType > 0 && getDialogId() != XAP_DIALOG_ID_FILE_SAVE_IMAGE) // 0 means autodetect
                {
                    if (!UT_pathSuffix(szDialogFilename).empty())
                    {
                        // warn if we have a suffix that doesn't match the selected file type
                        IE_ExpSniffer* pSniffer = IE_Exp::snifferForFileType(m_nTypeList[nIndex]);
                        if (pSniffer && !pSniffer->recognizeSuffix(UT_pathSuffix(szDialogFilename).c_str()))
                        {
                            UT_UTF8String msg;
                            const XAP_StringSet * pSS = m_pApp->getStringSet();
                            pSS->getValueUTF8(XAP_STRING_ID_DLG_FOSA_ExtensionDoesNotMatch, msg);
                            if (pFrame->showMessageBox(msg.utf8_str(), XAP_Dialog_MessageBox::b_YN, XAP_Dialog_MessageBox::a_NO) != XAP_Dialog_MessageBox::a_YES)
                                goto ContinueLoop;
                        }
                        szFinalPathname = g_strdup(szDialogFilename);
                    }
                    else if (wantSuffix)
                    {
                        // if the file doesn't have a suffix already, and the file type
                        // is normal (special types are negative, like auto detect),
                        // and the user wants extensions, slap a suffix on it.
                        // add suffix based on selected file type
                        UT_UTF8String suffix (IE_Exp::preferredSuffixForFileType(m_nTypeList[nIndex]));
                        UT_uint32 length = strlen(szDialogFilename) + suffix.size() + 1;

                        szFinalPathname = static_cast<char *>(UT_calloc(length,sizeof(char)));

                        if (szFinalPathname)
                        {
                            char * p = szFinalPathname;
                            strcpy(p,szDialogFilename);
                            strcat(p,suffix.utf8_str());
                        }
                    }
                    else
                        szFinalPathname = g_strdup(szDialogFilename);
                }
                else
                {
                    // the file type is special (auto detect)
                    // set to plain name, and let the auto detector in the
                    // exporter figure it out
                    szFinalPathname = g_strdup(szDialogFilename);
                }

                // g_free szDialogFilename since it's been put into szFinalPathname (with
                // or without changes) and it's invalid (missing an extension which
                // might have been appended)

                FREEP(szDialogFilename);
            }

            szFinalPathnameCopy = g_strdup(szFinalPathname);

            if (UT_go_file_exists(szFinalPathnameCopy))
            {
                // we have an existing file, ask to overwrite
                if (_askOverwrite_YesNo(pFrame, szFinalPathname))
                {
                    m_szFinalPathnameCandidate = g_strdup(szFinalPathname);
                    goto ReturnTrue;
                }

                goto ContinueLoop;
            }

            // We have a string that may contain a path, and may have a file
            // at the end.  First, strip off a file (if it exists), and test
            // for a matching directory.  We can then proceed with the file
            // if another stat of that dir passes.

            if (szFinalPathnameCopy && strlen(szFinalPathnameCopy))
                pLastSlash = strrchr(szFinalPathnameCopy,'/');
            else
                pLastSlash = NULL;

            if (!pLastSlash)
            {
                _notifyError_OKOnly(pFrame,XAP_STRING_ID_DLG_InvalidPathname);
                goto ContinueLoop;
            }

            m_szFinalPathnameCandidate = g_strdup(szFinalPathname);
            goto ReturnTrue;

            // complain about write permission on the directory.
            // lop off ugly trailing slash only if we don't have
            // the root dir ('/') for a path

            if (pLastSlash > szFinalPathnameCopy)
                *pLastSlash = 0;

            _notifyError_OKOnly(pFrame,XAP_STRING_ID_DLG_NoSaveFile_DirNotWriteable,
                                szFinalPathname);
ContinueLoop:
            FREEP(szFinalPathnameCopy);
        }
    } /* if m_bSave */

    /*NOTREACHED*/

ReturnTrue:
    FREEP(szFinalPathnameCopy);
    FREEP(szFinalPathname);
    return true;
}
コード例 #20
0
void XAP_Win32Slurp::processCommand(HDDEDATA hData)
{
	DWORD bufSize = DdeGetData(hData,NULL,0,0);

	char * pBuf = (char *)UT_calloc(sizeof(char),bufSize+100);
	if (!pBuf)
	{
		UT_DEBUGMSG(("No memory to allocate DDE buffer [size %d]\n",bufSize));
		return;
	}
	
	DdeGetData(hData,(LPBYTE)pBuf,bufSize+99,0);
	UT_Win32LocaleString wstr;
	UT_UTF8String astr;
	wstr.fromLocale((LPCWSTR)pBuf);
	astr=wstr.utf8_str();
	UT_DEBUGMSG(("DDEML received command '%s'\n",astr.utf8_str()));
	
	// we expect something of the form:
	//     [Open("<pathname>")]
	// if anything more complicated is needed, it may be a
	// good idea to use a regex library
	// TODO failures just goto Finished. Some error reporting
	// TODO would be nice

	// pointer to work through the incoming string
	const char * next = astr.utf8_str();
	
	// pointer used to copy into command and pathname
	char * dest = 0;
	
	// chomp the [
	if ( *next++ != '[' ) goto Finished;
	
	// find the next sequence of non ( characters
	// this will be the dde command
	char command[1024];
	dest = command;
	for ( ; *next != '('; ++next )
	{
		*dest++ = *next;
	}
	*dest = 0;

	// chomp the ( and the "
	if ( *next++ != '(' ) goto Finished;
	if ( *next++ != '"' ) goto Finished;
	// go until the next " to get the parameter
	// " are not allowed in filenames, so we should be safe here
	char pathname[4096];
	dest = pathname;
	for ( ; *next != '"'; ++next )	
	{
		*dest++ = *next;
	}
	*dest = 0;
	
	// chomp the ", ), and ]
	if ( *next++ != '"' ) goto Finished;
	if ( *next++ != ')' ) goto Finished;
	if ( *next++ != ']' ) goto Finished;
	
	// now do something useful with the command and its parameter
	if (g_ascii_strcasecmp(command,"open") == 0)
		{
			if (!pathname || !*pathname)
			{
				UT_DEBUGMSG(("No pathname given in DDE Open command.\n"));
				goto Finished;
			}

			// ask the application to load this document into a window....

			// let's create uri for comparison with filenames from command line
			// TODO: That method does not always work. Some proper method should
			//       be designed.
			char *uri = UT_go_filename_to_uri(pathname);
			XAP_Win32App *p_app = (XAP_Win32App *)XAP_App::getApp();
			UT_sint32 ndx = p_app->findFrame(uri);
			UT_Error error;
			if ((ndx < 0) || p_app->getFrame(ndx)->isDirty()) {
				error = p_app->fileOpen(p_app->getLastFocussedFrame(), uri);
			}

			if(error != UT_OK)
			{
				UT_DEBUGMSG(("Could not load document given in DDE Open command [%s].\n",uri));
			}

			FREEP(uri);

			goto Finished;
		}

Finished:
	FREEP(pBuf);
	DdeFreeDataHandle(hData);
}
コード例 #21
0
ファイル: AbiGOComponent.cpp プロジェクト: hfiguiere/abiword
static bool s_AskForGOComponentPathname(XAP_Frame * pFrame,
					   char ** ppPathname,
					   IEGraphicFileType * iegft)
{
	// raise the file-open dialog for inserting a component.
	// return a_OK or a_CANCEL depending on which button
	// the user hits.
	// return a pointer a g_strdup()'d string containing the
	// pathname the user entered -- ownership of this goes
	// to the caller (so free it when you're done with it).

	UT_DEBUGMSG(("s_AskForGOComponentPathname: frame %p\n",
				 pFrame));

	UT_return_val_if_fail (ppPathname, false);
	*ppPathname = NULL;

	pFrame->raise();

	XAP_DialogFactory * pDialogFactory
		= static_cast<XAP_DialogFactory *>(pFrame->getDialogFactory());

	XAP_Dialog_FileOpenSaveAs * pDialog
		= static_cast<XAP_Dialog_FileOpenSaveAs *>(pDialogFactory->requestDialog(XAP_DIALOG_ID_INSERTOBJECT));
	UT_return_val_if_fail (pDialog, false);

	pDialog->setCurrentPathname("");
	pDialog->setSuggestFilename(false);

	// to fill the file types popup list, we need to convert AP-level
	// ImpGraphic descriptions, suffixes, and types into strings.

	UT_uint32 filterCount = IE_ImpGraphic::getImporterCount();

	const char ** szDescList = static_cast<const char **>(UT_calloc(filterCount + 1, sizeof(char *)));
	const char ** szSuffixList = static_cast<const char **>(UT_calloc(filterCount + 1, sizeof(char *)));
	IEGraphicFileType * nTypeList = (IEGraphicFileType *)
		 UT_calloc(filterCount + 1,	sizeof(IEGraphicFileType));
	UT_uint32 k = 0;

	while (IE_ImpGraphic::enumerateDlgLabels(k, &szDescList[k], &szSuffixList[k], &nTypeList[k]))
		k++;

	pDialog->setFileTypeList(szDescList, szSuffixList, static_cast<const UT_sint32 *>(nTypeList));
	if (iegft != NULL)
	  pDialog->setDefaultFileType(*iegft);
	pDialog->runModal(pFrame);

	XAP_Dialog_FileOpenSaveAs::tAnswer ans = pDialog->getAnswer();
	bool bOK = (ans == XAP_Dialog_FileOpenSaveAs::a_OK);

	if (bOK)
	{
		const std::string & resultPathname = pDialog->getPathname();
		UT_DEBUGMSG(("OBJECT Path Name selected = %s \n", resultPathname.c_str()));
		if (!resultPathname.empty()) {
			*ppPathname = g_strdup(resultPathname.c_str());
		}

		UT_sint32 type = pDialog->getFileType();

		// If the number is negative, it's a special type.
		// Some operating systems which depend solely on filename
		// suffixes to identify type (like Windows) will always
		// want auto-detection.
		if (type < 0)
			switch (type)
			{
			case XAP_DIALOG_FILEOPENSAVEAS_FILE_TYPE_AUTO:
				// do some automagical detecting
				*iegft = IEGFT_Unknown;
				break;
			default:
				// it returned a type we don't know how to handle
				UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
			}
		else
			*iegft = static_cast<IEGraphicFileType>(pDialog->getFileType());
	}

	FREEP(szDescList);
	FREEP(szSuffixList);
	FREEP(nTypeList);

	pDialogFactory->releaseDialog(pDialog);

	return bOK;
}
コード例 #22
0
ファイル: ap_Win32App.cpp プロジェクト: lokeshguddu/AbiWord
bool AP_Win32App::initialize(void)
{
	bool bSuccess = true;
	const char * szUserPrivateDirectory = getUserPrivateDirectory();
	bool bVerified = s_createDirectoryIfNecessary(szUserPrivateDirectory);

	UT_return_val_if_fail (bVerified, false);

	// create templates directory
	UT_String sTemplates = szUserPrivateDirectory;
	sTemplates += "/templates";
	s_createDirectoryIfNecessary(sTemplates.c_str());

	// load the preferences.
	
	m_prefs = new AP_Win32Prefs();
	UT_return_val_if_fail (m_prefs, false);
	
	m_prefs->fullInit();
		   
	// now that preferences are established, let the xap init

	m_pClipboard = new AP_Win32Clipboard();
	UT_return_val_if_fail (m_pClipboard, false);
	   
	m_pEMC = AP_GetEditMethods();
	UT_return_val_if_fail (m_pEMC, false);

	m_pBindingSet = new AP_BindingSet(m_pEMC);
	UT_return_val_if_fail (m_pBindingSet, false);
	
	m_pMenuActionSet = AP_CreateMenuActionSet();
	UT_return_val_if_fail (m_pMenuActionSet,false);

	m_pToolbarActionSet = AP_CreateToolbarActionSet();
	UT_return_val_if_fail (m_pToolbarActionSet,false);

	//////////////////////////////////////////////////////////////////
	// load the dialog and message box strings
	//////////////////////////////////////////////////////////////////
	
	{
		// assume we will be using the builtin set (either as the main
		// set or as the fallback set).
		
		AP_BuiltinStringSet * pBuiltinStringSet = new AP_BuiltinStringSet(this,AP_PREF_DEFAULT_StringSet);
		UT_return_val_if_fail (pBuiltinStringSet, false);
		m_pStringSet = pBuiltinStringSet;

		// see if we should load an alternate set from the disk
		
		const char * szDirectory = NULL;
		const char * szStringSet = NULL;

		if (   (getPrefsValue(AP_PREF_KEY_StringSet,&szStringSet))
			&& (szStringSet)
			&& (*szStringSet)
			&& (g_ascii_strcasecmp(szStringSet,AP_PREF_DEFAULT_StringSet) != 0))
		{
			getPrefsValueDirectory(true,AP_PREF_KEY_StringSetDirectory,&szDirectory);
			UT_return_val_if_fail ((szDirectory) && (*szDirectory), false);

			char * szPathname = (char *)UT_calloc(sizeof(char),strlen(szDirectory)+strlen(szStringSet)+100);
			UT_return_val_if_fail (szPathname, false);

			sprintf(szPathname,"%s%s%s.strings",
					szDirectory,
					((szDirectory[strlen(szDirectory)-1]=='\\') ? "" : "\\"),
					szStringSet);

			AP_DiskStringSet * pDiskStringSet = new AP_DiskStringSet(this);
			UT_return_val_if_fail (pDiskStringSet, false);

			if (pDiskStringSet->loadStringsFromDisk(szPathname))
			{
				pDiskStringSet->setFallbackStringSet(m_pStringSet);
				m_pStringSet = pDiskStringSet;
				UT_Language_updateLanguageNames();
				UT_DEBUGMSG(("Using StringSet [%s]\n",szPathname));
			}
			else
			{
				UT_DEBUGMSG(("Unable to load StringSet [%s] -- using builtin strings instead.\n",szPathname));				
				DELETEP(pDiskStringSet);
			}
				
			g_free(szPathname);
		}
	}

	// AP_App::initilize() calls for us XAP_Win32App::initialize()
	if (! AP_App::initialize())
		return false;

	
	// let various window types register themselves

	if (!AP_Win32Frame::RegisterClass(this))
	{
		UT_DEBUGMSG(("couldn't register class\n"));
		return false;
	}

	//////////////////////////////////////////////////////////////////
	// Initialize the importers/exporters
	//////////////////////////////////////////////////////////////////
	IE_ImpExp_RegisterXP ();

	//////////////////////////////////////////////////////////////////
	// initializes the spell checker.
	//////////////////////////////////////////////////////////////////
	
	{
#if ENABLE_SPELL
		SpellManager::instance();
#endif
	}
	
	
	// Now we have the strings loaded we can populate the field names correctly
	int i;
	
	for (i = 0; fp_FieldTypes[i].m_Type != FPFIELDTYPE_END; i++)
	{
	    (&fp_FieldTypes[i])->m_Desc = m_pStringSet->getValue(fp_FieldTypes[i].m_DescId);
	    UT_DEBUGMSG(("Setting field type desc for type %d, desc=%s\n", fp_FieldTypes[i].m_Type, fp_FieldTypes[i].m_Desc));
	}

	for (i = 0; fp_FieldFmts[i].m_Tag != NULL; i++)
	{
	    (&fp_FieldFmts[i])->m_Desc = m_pStringSet->getValue(fp_FieldFmts[i].m_DescId);
	    UT_DEBUGMSG(("Setting field desc for field %s, desc=%s\n", fp_FieldFmts[i].m_Tag, fp_FieldFmts[i].m_Desc));
	}

    ///////////////////////////////////////////////////////////////////////
    /// Build a labelset so the plugins can add themselves to something ///
    ///////////////////////////////////////////////////////////////////////

	const char * szMenuLabelSetName = NULL;
	if (getPrefsValue( AP_PREF_KEY_StringSet, (const gchar**)&szMenuLabelSetName)
		&& (szMenuLabelSetName) && (*szMenuLabelSetName))
	{
		;
	}
	else
		szMenuLabelSetName = AP_PREF_DEFAULT_StringSet;

	getMenuFactory()->buildMenuLabelSet(szMenuLabelSetName);	
	
	//////////////////////////////////////////////////////////////////
	// Check for necessary DLLs now that we can do localized error messages
	//////////////////////////////////////////////////////////////////

	// Ensure that common control DLL is loaded
	HINSTANCE hinstCC = LoadLibraryW(L"comctl32.dll");
	UT_return_val_if_fail (hinstCC, false);
	InitCommonControlsEx_fn  pInitCommonControlsEx = NULL;
	if( hinstCC != NULL )
		pInitCommonControlsEx = (InitCommonControlsEx_fn)GetProcAddress( hinstCC, "InitCommonControlsEx");
	if( pInitCommonControlsEx != NULL )
	{
		INITCOMMONCONTROLSEX icex;
		icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
		icex.dwICC = ICC_COOL_CLASSES | ICC_BAR_CLASSES 	// load the rebar and toolbar
					| ICC_TAB_CLASSES | ICC_UPDOWN_CLASS	// and tab and spin controls
					| ICC_STANDARD_CLASSES;
		pInitCommonControlsEx(&icex);
	}
	else
	{
		InitCommonControls();

		UT_Win32LocaleString err;
		err.fromUTF8 (m_pStringSet->getValue(AP_STRING_ID_WINDOWS_COMCTL_WARNING));		
		MessageBoxW(NULL, err.c_str(), NULL, MB_OK);
	}

	//////////////////////////////////////////////////////////////////
	// load the all Plugins from the correct directory
	//////////////////////////////////////////////////////////////////

#ifndef DISABLE_BUILTIN_PLUGINS
	abi_register_builtin_plugins();
#endif

	bool bLoadPlugins = true;
	bool bFound = getPrefsValueBool(XAP_PREF_KEY_AutoLoadPlugins,&bLoadPlugins);

	if(bLoadPlugins || !bFound)
	{
		WCHAR szPath[PATH_MAX];
		WCHAR szPlugin[PATH_MAX];
		_getExeDir( szPath, PATH_MAX);
#ifdef _MSC_VER
		lstrcatW(szPath, L"..\\plugins\\*.dll");
#else
#define ABI_WIDE_STRING(t) L ## t
		lstrcatW(szPath, ABI_WIDE_STRING("..\\lib\\" PACKAGE L"-" ABIWORD_SERIES L"\\plugins\\*.dll"));
#endif

		WIN32_FIND_DATAW cfile;
		HANDLE findtag = FindFirstFileW( szPath, &cfile );
		if( findtag != INVALID_HANDLE_VALUE )
		{
			do
			{	
				_getExeDir( szPlugin, PATH_MAX );
#ifdef _MSC_VER
				lstrcatW( szPlugin, L"..\\plugins\\" );
#else
				lstrcatW( szPlugin, ABI_WIDE_STRING("..\\lib\\" PACKAGE L"-" ABIWORD_SERIES L"\\plugins\\" ));
#endif
				lstrcatW( szPlugin, cfile.cFileName );
				XAP_ModuleManager::instance().loadModule( getUTF8String(szPlugin) );
			} while( FindNextFileW ( findtag, &cfile ) );
			FindClose( findtag );
		}

		UT_String pluginName( getUserPrivateDirectory() ); 
		UT_String pluginDir( getUserPrivateDirectory() );
		pluginDir += "\\AbiWord\\plugins\\*.dll";
		UT_Win32LocaleString str;
		str.fromUTF8(pluginDir.c_str());
		findtag = FindFirstFileW( str.c_str(), &cfile );
		if( findtag != INVALID_HANDLE_VALUE )
		{
			do
			{	
				pluginName = getUserPrivateDirectory();
				pluginName += "\\AbiWord\\plugins\\";
				pluginName += getUTF8String(cfile.cFileName);
				XAP_ModuleManager::instance().loadModule( pluginName.c_str() );
			} while( FindNextFileW( findtag, &cfile ) );
			FindClose( findtag );
		}
	}
	return bSuccess;
}
コード例 #23
0
ファイル: ut_Xpm2Bmp.cpp プロジェクト: Distrotech/abiword
bool UT_Xpm2Bmp(UT_uint32 maxWidth,
				   UT_uint32 maxHeight,
				   const char ** pIconData,
				   UT_uint32 sizeofData,
				   HDC hdc,
				   UT_RGBColor * pBackgroundColor,
				   HBITMAP * pBitmap)
{
	// convert an XPM into a BMP using a DIB.
	// return true if successful.

	UT_ASSERT(pIconData && *pIconData);
	UT_ASSERT(sizeofData > 0);
	UT_ASSERT(pBackgroundColor);
	UT_ASSERT(pBitmap);

	// first row contains: width height, number of colors, chars per pixel

	UT_uint32 width, height, xpm_width, xpm_height, nrColors, charsPerPixel;
	UT_uint32 cut_left, cut_top;
	UT_uint32 n = sscanf(pIconData[0],"%ld %ld %ld %ld",
						 &xpm_width,&xpm_height,&nrColors,&charsPerPixel);
	UT_ASSERT(n == 4);
	UT_ASSERT(xpm_width > 0);
	UT_ASSERT(xpm_height > 0);

	UT_ASSERT(charsPerPixel > 0);

	width = xpm_width < maxWidth ? xpm_width : maxWidth;
	cut_left = xpm_width - width;
	cut_left -= cut_left / 2;
	height = xpm_height < maxHeight ? xpm_height : maxHeight;
	cut_top = xpm_height - height;
	cut_top -= cut_top / 2;
	
	UT_uint32 sizeofColorData = nrColors * sizeof(RGBQUAD);
	UT_uint32 widthRoundedUp = _RoundUp(width,sizeof(LONG));
	UT_uint32 rowPadding = widthRoundedUp - width;
	UT_uint32 sizeofPixelData = widthRoundedUp * height;
	UT_uint32 sizeofStructure = sizeof(BITMAPINFOHEADER) + sizeofColorData + sizeofPixelData;

	UT_Byte * pInfo = (UT_Byte *)UT_calloc(1,sizeofStructure);
	if (!pInfo)
		return false;

	BITMAPINFO * pbmi = (BITMAPINFO *)pInfo;
	BITMAPINFOHEADER * pbmih = &pbmi->bmiHeader;
	RGBQUAD * pRGB = (RGBQUAD *)(pInfo + sizeof(BITMAPINFOHEADER));
	UT_Byte * pPixel = (UT_Byte *)(pInfo + sizeof(BITMAPINFOHEADER) + sizeofColorData);

	pbmih->biSize			= sizeof(BITMAPINFOHEADER);
	pbmih->biWidth			= width;
	pbmih->biHeight			= -(LONG)height;	// minus height gives us a top-down bitmap
	pbmih->biPlanes			= 1;
	pbmih->biBitCount		= 8;
	pbmih->biCompression	= BI_RGB;
	pbmih->biSizeImage		= 0;
	pbmih->biXPelsPerMeter	= 0;
	pbmih->biYPelsPerMeter	= 0;
	pbmih->biClrUsed		= nrColors;	// should we verify that they are all actually used ??
	pbmih->biClrImportant	= 0;

	UT_StringPtrMap hash(256);
	UT_RGBColor color(0,0,0);
	
	// walk thru the palette

	// use a local UT_String, else every call to hash.insert and hash.pick
	// creates and destroys its own UT_String
	UT_String sTmp;

	const char ** pIconDataPalette = &pIconData[1];
	for (UT_uint32 k=0; (k < nrColors); k++)
	{
		char bufSymbol[10] = { 0 };
		char bufKey[10];
		char bufColorValue[100];

		// we expect something of the form: ".. c #000000"
		// or we can accpet ".. g #000000" for gray scale
		// but we allow a space as a character in the symbol, so we
		// get the first field the hard way.

		for (UT_uint32 kPx=0; (kPx < charsPerPixel); kPx++)
			bufSymbol[kPx] = pIconDataPalette[k][kPx];
		UT_ASSERT(strlen(bufSymbol) == charsPerPixel);
		
		UT_uint32 nf = sscanf(&pIconDataPalette[k][charsPerPixel+1]," %s %s",&bufKey,&bufColorValue);
		UT_ASSERT(nf == 2);
		UT_ASSERT(bufKey[0] == 'c' || bufKey[0] == 'g');

		// make the ".." a hash key and store our color index as the data.
		// we add k+1 because the hash code does not like null pointers...
		sTmp = bufSymbol;
		hash.insert(sTmp, (void *)(k+1));

		// store the actual color value in the rgb quad array with our color index.

		if (g_ascii_strcasecmp(bufColorValue,"None")==0)
		{
			pRGB[k].rgbRed		= pBackgroundColor->m_red;
			pRGB[k].rgbGreen	= pBackgroundColor->m_grn;
			pRGB[k].rgbBlue		= pBackgroundColor->m_blu;
			pRGB[k].rgbReserved	= 0;
		}
		else
		{
			// TODO fix this to also handle #ffffeeeedddd type color references
			
			UT_ASSERT((bufColorValue[0] == '#') && strlen(bufColorValue)==7);
			UT_parseColor(bufColorValue, color);
			pRGB[k].rgbRed		= color.m_red;
			pRGB[k].rgbGreen	= color.m_grn;
			pRGB[k].rgbBlue		= color.m_blu;
			pRGB[k].rgbReserved	= 0;
		}
	}

	// walk thru the image data

	const char ** pIconDataImage = &pIconDataPalette[nrColors];
	for (UT_uint32 kRow=0; (kRow < height); kRow++)
	{
		const char * p = pIconDataImage[kRow+cut_top];
		
		p += cut_left * charsPerPixel;
		for (UT_uint32 kCol=0; (kCol < width); kCol++)
		{
			char bufPixel[10] = { 0 };
			for (UT_uint32 kPx=0; (kPx < charsPerPixel); kPx++)
				bufPixel[kPx] = *p++;

			sTmp = bufPixel;
			guint32 pEntry = (guint32) hash.pick(sTmp);
			*pPixel++ = ((UT_Byte)(pEntry)) - 1;
		}

		pPixel += rowPadding;
	}

	UT_ASSERT(pPixel == (pInfo + sizeofStructure));
	pPixel = (UT_Byte *)(pInfo + sizeof(BITMAPINFOHEADER) + sizeofColorData);
	
	HBITMAP hBitmap = CreateDIBitmap(hdc,pbmih,CBM_INIT,pPixel,pbmi,DIB_RGB_COLORS);
	*pBitmap = hBitmap;

	g_free(pInfo);
	
	return (hBitmap != 0);
}
コード例 #24
0
bool AP_Dialog_Paragraph::getDialogData(const gchar **& pProps)
{
	UT_Vector v;

	struct propPair
	{
		gchar * prop;
		gchar * val;
	};

	propPair * p;

	// only do this if the control has a proper value
	if (_wasChanged(id_MENU_ALIGNMENT)  && _getMenuItemValue(id_MENU_ALIGNMENT))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("text-align");

		switch (_getMenuItemValue(id_MENU_ALIGNMENT))
		{
			case align_LEFT:
				p->val = g_strdup("left");
				break;
			case align_CENTERED:
				p->val = g_strdup("center");
				break;
			case align_RIGHT:
				p->val = g_strdup("right");
				break;
			case align_JUSTIFIED:
				p->val = g_strdup("justify");
				break;
			default:
				UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
		}
		v.addItem(p);
	}


	if (_wasChanged(id_CHECK_DOMDIRECTION))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("dom-dir");

		if (_getCheckItemValue(id_CHECK_DOMDIRECTION) == check_TRUE)
			p->val = g_strdup("rtl");
		else
			p->val = g_strdup("ltr");

		v.addItem(p);

	}


	if (_wasChanged(id_SPIN_LEFT_INDENT))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("margin-left");
		p->val = g_strdup(_getSpinItemValue(id_SPIN_LEFT_INDENT));

		v.addItem(p);
	}

	if (_wasChanged(id_SPIN_RIGHT_INDENT))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("margin-right");
		p->val = g_strdup(_getSpinItemValue(id_SPIN_RIGHT_INDENT));

		v.addItem(p);
	}

	// TODO : The logic here might not be bulletproof.  If the user triggers
	// TODO : a change in the TYPE of special indent (hanging, first line,
	// TODO : none), we will always save what's in the box as a property.
	// TODO : One could make it smarter with a stronger contract with
	// TODO : the platform interfaces.

	if (_getMenuItemValue(id_MENU_SPECIAL_INDENT) &&
		(_wasChanged(id_MENU_SPECIAL_INDENT) || _wasChanged(id_SPIN_SPECIAL_INDENT)))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("text-indent");

		tIndentState i = (tIndentState) _getMenuItemValue(id_MENU_SPECIAL_INDENT);

		if (i == indent_NONE)
			p->val = g_strdup(UT_convertInchesToDimensionString(m_dim, 0));
		else if (i == indent_FIRSTLINE)
			p->val = g_strdup(_getSpinItemValue(id_SPIN_SPECIAL_INDENT));
		else if (i == indent_HANGING)
		{
			// we have to flip the sign for "hanging" indents to a negative quantity for
			// storage in the document as a text-indent

			// get with no dimension
			UT_Dimension dim = UT_determineDimension(_getSpinItemValue(id_SPIN_SPECIAL_INDENT));
			double val = UT_convertDimensionless(_getSpinItemValue(id_SPIN_SPECIAL_INDENT));
			// Convert to inches
			val = UT_convertDimToInches(val, dim);

			// flip sign
			val = val * (double) -1;

			// store the reconstructed
			p->val = g_strdup(UT_convertInchesToDimensionString(dim, val));
		}

		v.addItem(p);
	}

	if (_wasChanged(id_SPIN_BEFORE_SPACING))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("margin-top");
		p->val = g_strdup(_getSpinItemValue(id_SPIN_BEFORE_SPACING));

		v.addItem(p);
	}

	if (_wasChanged(id_SPIN_AFTER_SPACING))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("margin-bottom");
		p->val = g_strdup(_getSpinItemValue(id_SPIN_AFTER_SPACING));

		v.addItem(p);
	}

	// TODO : The logic here might not be bulletproof.  If the user triggers
	// TODO : a change in the TYPE of special indent (single, double, etc.)
	// TODO : we will always save what's in the box as a property.
	// TODO : One could make it smarter with a stronger contract with
	// TODO : the platform interfaces.

	if(_getMenuItemValue(id_MENU_SPECIAL_SPACING) &&
		 (_wasChanged(id_MENU_SPECIAL_SPACING) || _wasChanged(id_SPIN_SPECIAL_SPACING)))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("line-height");

		// normal spacings (single, 1.5, double) are just simple numbers.
		// "at least" needs a "+" at the end of the number (no units).
		// "exactly" simply has units.
		// "multiple" has no units.

		gchar * pTmp = NULL;
		const gchar * pString = _getSpinItemValue(id_SPIN_SPECIAL_SPACING);
		UT_uint32 nSize = 0;

		switch(_getMenuItemValue(id_MENU_SPECIAL_SPACING))
		{
		case spacing_SINGLE:
			p->val = g_strdup("1.0");
			break;
		case spacing_ONEANDHALF:
			p->val = g_strdup("1.5");
			break;
		case spacing_DOUBLE:
			p->val = g_strdup("2.0");
			break;
		case spacing_ATLEAST:
			nSize = strlen(pString);
			pTmp = (gchar *) UT_calloc(nSize + 2, sizeof(gchar));
			UT_return_val_if_fail (pTmp, false);

			strncpy(pTmp, pString, nSize);
			// stick a '+' at the end
			pTmp[nSize] = '+';
			p->val = g_strdup(pTmp);
			FREEP(pTmp);
			break;

		case spacing_EXACTLY:
			// fallthrough
		case spacing_MULTIPLE:
			// both these cases either do or don't have units associated with them.
			// the platform dialog code takes care of that.
			p->val = g_strdup(pString);
			break;
		default:
			UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
		}
		v.addItem(p);
	}

	// NOTE : "orphans" and "widows" hold a number specifying the number
	// NOTE : of lines to consider an orphaned or widowed piece of text.
	// NOTE : If they're both 0 they're off.  If either is greater than
	// NOTE : 0, then some form of control is in effect.  If the property
	// NOTE : is not set, they're indeterminate.

	if (_wasChanged(id_CHECK_WIDOW_ORPHAN))
	{
		// TODO : fix this!  we stomp on both properties (setting them
		// TODO : to "2"s or "0"s) if the one check box was ever
		// TODO : changed

		{
			ALLOC_PROP_PAIR(p);
			p->prop = g_strdup("orphans");

			if (_getCheckItemValue(id_CHECK_WIDOW_ORPHAN) == check_TRUE)
				p->val = g_strdup("2");
			else
				p->val = g_strdup("0");

			v.addItem(p);
		}

		{
			ALLOC_PROP_PAIR(p);
			p->prop = g_strdup("widows");

			if (_getCheckItemValue(id_CHECK_WIDOW_ORPHAN) == check_TRUE)
				p->val = g_strdup("2");
			else
				p->val = g_strdup("0");

			v.addItem(p);
		}
	}

	if (_wasChanged(id_CHECK_KEEP_LINES))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("keep-together");

		if (_getCheckItemValue(id_CHECK_KEEP_LINES) == check_TRUE)
			p->val = g_strdup("yes");
		else
			p->val = g_strdup("no");

		v.addItem(p);
	}

	if (_wasChanged(id_CHECK_KEEP_NEXT))
	{
		ALLOC_PROP_PAIR(p);
		p->prop = g_strdup("keep-with-next");

		if (_getCheckItemValue(id_CHECK_KEEP_NEXT) == check_TRUE)
			p->val = g_strdup("yes");
		else
			p->val = g_strdup("no");

		v.addItem(p);
	}

	// TODO : add these to PP_Property (pp_Property.cpp) !!!
	/*
	  m_pageBreakBefore;
	  m_suppressLineNumbers;
	  m_noHyphenate;
	*/

	// export everything in the array
	UT_uint32 count = v.getItemCount()*2 + 1;

	const gchar ** newprops = (const gchar **) UT_calloc(count, sizeof(gchar *));
	if (!newprops)
		return false;

	const gchar ** newitem = newprops;

	UT_uint32 i = v.getItemCount();

	while (i > 0)
	{
		p = (propPair *) v.getNthItem(i-1);
		i--;

		newitem[0] = p->prop;
		newitem[1] = p->val;
		newitem += 2;
	}

	// DO purge the vector's CONTENTS, which are just propPair structs
	UT_VECTOR_FREEALL(propPair *, v);

	// DO NOT purge the propPair's CONTENTS, because they will be pointed to
	// by the pointers we just copied into memory typed (gchar **)

	pProps = newprops;

	return true;
}
コード例 #25
0
/*!
 * Import graphic for cell background.
 */
void AP_Dialog_FormatFrame::askForGraphicPathName(void)
{
	UT_return_if_fail(m_pApp);
	XAP_Frame * pFrame = m_pApp->getLastFocussedFrame();

	UT_return_if_fail(pFrame);
	XAP_DialogFactory * pDialogFactory
		= static_cast<XAP_DialogFactory *>(pFrame->getDialogFactory());

	UT_return_if_fail(pDialogFactory);
	XAP_Dialog_FileOpenSaveAs * pDialog
		= static_cast<XAP_Dialog_FileOpenSaveAs *>(pDialogFactory->requestDialog(XAP_DIALOG_ID_INSERT_PICTURE));
	UT_return_if_fail (pDialog);

	pDialog->setCurrentPathname(NULL);
	pDialog->setSuggestFilename(false);

	// to fill the file types popup list, we need to convert AP-level
	// ImpGraphic descriptions, suffixes, and types into strings.

	UT_uint32 filterCount = IE_ImpGraphic::getImporterCount();

	const char ** szDescList = static_cast<const char **>(UT_calloc(filterCount + 1, sizeof(char *)));
	const char ** szSuffixList = static_cast<const char **>(UT_calloc(filterCount + 1, sizeof(char *)));
	IEGraphicFileType * nTypeList = (IEGraphicFileType *)
		 UT_calloc(filterCount + 1,	sizeof(IEGraphicFileType));
	UT_uint32 k = 0;

	while (IE_ImpGraphic::enumerateDlgLabels(k, &szDescList[k], &szSuffixList[k], &nTypeList[k]))
		k++;

	pDialog->setFileTypeList(szDescList, szSuffixList, static_cast<const UT_sint32 *>(nTypeList));
	pDialog->runModal(pFrame);

	XAP_Dialog_FileOpenSaveAs::tAnswer ans = pDialog->getAnswer();
	bool bOK = (ans == XAP_Dialog_FileOpenSaveAs::a_OK);

	if (bOK)
	{
		m_sImagePath = pDialog->getPathname();
		UT_sint32 type = pDialog->getFileType();

		// If the number is negative, it's a special type.
		// Some operating systems which depend solely on filename
		// suffixes to identify type (like Windows) will always
		// want auto-detection.
		if (type < 0)
			switch (type)
			{
			case XAP_DIALOG_FILEOPENSAVEAS_FILE_TYPE_AUTO:
				// do some automagical detecting
				m_iGraphicType = IEGFT_Unknown;
				break;
			default:
				// it returned a type we don't know how to handle
				UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
			}
		else
			m_iGraphicType = static_cast<IEGraphicFileType>(pDialog->getFileType());
	}

	FREEP(szDescList);
	FREEP(szSuffixList);
	FREEP(nTypeList);

	pDialogFactory->releaseDialog(pDialog);
	if(m_sImagePath.size() == 0)
	{
		return;
	}

	FG_Graphic* pFG = NULL;

	UT_Error errorCode;

	errorCode = IE_ImpGraphic::loadGraphic(m_sImagePath.c_str(), m_iGraphicType, &pFG);
	if(errorCode != UT_OK || !pFG)
	{
		ShowErrorBox(m_sImagePath, errorCode);
		return;
	}

	DELETEP(m_pGraphic);
	DELETEP(m_pImage);
	m_pGraphic = pFG->clone();
	GR_Graphics * pG = m_pFormatFramePreview->getGraphics();

	FV_View * pView = static_cast<FV_View *>(pFrame->getCurrentView());
	UT_return_if_fail(pView && pView->getDocument());

	UT_uint32 uid = pView->getDocument()->getUID(UT_UniqueId::Image); //see Bug 10851
	m_sImagePath.clear();
	m_sImagePath = UT_std_string_sprintf("%d",uid);

    m_pImage = _makeImageForRaster(m_sImagePath, pG, m_pGraphic);

	// draw the preview with the changed properties
	if(m_pFormatFramePreview)
		m_pFormatFramePreview->draw();

}
コード例 #26
0
/*!
 * Massage the byte buffer into an array of strings that can be loaded by 
 * gdk-pixbuf
 */
GdkPixbuf * IE_ImpGraphic_GdkPixbuf::_loadXPM(UT_ByteBuf * pBB)
{
	GdkPixbuf * pixbuf = NULL;
	const char * pBC = reinterpret_cast<const char *>(pBB->getPointer(0));

	UT_GenericVector<char*> vecStr;
	UT_sint32 k =0;
	UT_sint32 iBase =0;

	//
	// Find dimension line to start with.
	//
	UT_sint32 length = static_cast<UT_sint32>(pBB->getLength());
	for(k =0; (*(pBC+k) != '"') &&( k < length); k++)
		;

	if(k >= length)
	{
		return NULL;
	}

	k++;
	iBase = k;
	for(; (*(pBC+k) != '"') && (k < length); k++)
		;
	if(k >= length)
	{
		return NULL;
	}

	char * sz = NULL;
	UT_sint32 kLen = k-iBase+1;
	sz = static_cast<char *>(UT_calloc(kLen,sizeof(char)));
	UT_sint32 i =0;

	for(i=0; i< (kLen -1); i++)
	{
		*(sz+i) = *(pBC+iBase+i);
	}
	*(sz+i) = 0;
	vecStr.addItem(sz);

	//
	// Now loop through all the lines until we get to "}" outside the
	// '"'
	while((*(pBC+k) != '}')  && (k < length) )
	{
		k++;

		//
		// Load a single string of data into our vector.
		// 
		if(*(pBC+k) =='"')
		{
			//
			// Start of a line
			//
			k++;
			iBase = k;
			for(; (*(pBC+k) != '"') && (k < length); k++) 
			{
			}
			if(k >= length)
			{
				return NULL;
			}
			sz = NULL;
			kLen = k-iBase+1;
			sz = static_cast<char *>(UT_calloc(kLen,sizeof(char)));
			for(i=0; i<(kLen -1); i++)
			{
				*(sz+i) = *(pBC+iBase+i);
			}
			*(sz +i) = 0;
			vecStr.addItem(sz);
		}
	}

	if(k >= length)
	{
		for(i=0; i< vecStr.getItemCount(); i++)
		{
			char * psz = vecStr.getNthItem(i);
			FREEP(psz);
		}
		return NULL;
	}

	const char ** pszStr = static_cast<const char **>(UT_calloc(vecStr.getItemCount(),sizeof(char *)));
	for(i=0; i< vecStr.getItemCount(); i++)
		pszStr[i] = vecStr.getNthItem(i);
	pixbuf = gdk_pixbuf_new_from_xpm_data(pszStr);
	DELETEP(pszStr);
	return pixbuf;
}
コード例 #27
0
void XAP_Win32Dialog_PluginManager::event_Load()
{
	
	const XAP_StringSet * pSS = m_pApp->getStringSet();

	XAP_DialogFactory * pDialogFactory
		= (XAP_DialogFactory *) getApp()->findValidFrame()->getDialogFactory();
	
	XAP_Dialog_FileOpenSaveAs * pDialog
		= (XAP_Dialog_FileOpenSaveAs *)(pDialogFactory->requestDialog(XAP_DIALOG_ID_FILE_OPEN));
	UT_return_if_fail(pDialog);
	
	// set the intial plugin directory to the user-local plugin directory
	// could also set to: XAP_App::getApp()->getUserPrivateDirectory()\plugins
	// could also set to: XAP_App::getApp()->getAbiSuiteLibDir()\plugins
	UT_String pluginDir (XAP_App::getApp()->getAbiSuiteAppDir());
	pluginDir += "\\plugins";
	pDialog->setCurrentPathname (pluginDir.c_str());
	pDialog->setSuggestFilename(false);
	
	UT_uint32 filterCount = 1;
	const char ** szDescList = (const char **) UT_calloc(filterCount + 1,
													  sizeof(char *));
	UT_return_if_fail(szDescList);
	const char ** szSuffixList = (const char **) UT_calloc(filterCount + 1,
														sizeof(char *));
	if(!szSuffixList)
	{
		UT_ASSERT_HARMLESS(szSuffixList);
		FREEP(szDescList);
		return;
	}
	IEFileType * nTypeList = (IEFileType *) UT_calloc(filterCount + 1,
												   sizeof(IEFileType));
	if(!nTypeList)
	{
		UT_ASSERT_HARMLESS(nTypeList);
		FREEP(szDescList);
		FREEP(szSuffixList);
		return;
	}
	// we probably shouldn't hardcode this
	// HP-UX uses .sl, for instance
	szDescList[0] = "AbiWord Plugin (.dll)";
	szSuffixList[0] = "*.dll";
	nTypeList[0] = (IEFileType)1;
	
	pDialog->setFileTypeList(szDescList, szSuffixList, 
							 (const UT_sint32 *) nTypeList);
	
	pDialog->setDefaultFileType((IEFileType)1);

	// todo: cd to the proper plugin directory
	
	pDialog->runModal(getApp()->findValidFrame());
	
	XAP_Dialog_FileOpenSaveAs::tAnswer ans = pDialog->getAnswer();
	bool bOK = (ans == XAP_Dialog_FileOpenSaveAs::a_OK);
	
	if (bOK)
	{
		const char * szResultPathname = pDialog->getPathname();
		if (szResultPathname && *szResultPathname)
		{
			if( activatePlugin(szResultPathname) )
			{
				// worked!
				refreshPluginList();
			}
			else
			{
				// error message
				getApp()->findValidFrame()->showMessageBox( pSS->getValue(XAP_STRING_ID_DLG_PLUGIN_MANAGER_COULDNT_LOAD),
                                          XAP_Dialog_MessageBox::b_O,
                                          XAP_Dialog_MessageBox::a_OK );
			}
		}
	}
	
	FREEP(szDescList);
	FREEP(szSuffixList);
	FREEP(nTypeList);
	
	pDialogFactory->releaseDialog(pDialog);
}