Пример #1
0
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;
}
void OXMLi_ListenerState_Table::startElement (OXMLi_StartElementRequest * rqst)
{
	if (nameMatches(rqst->pName, NS_W_KEY, "tbl"))
	{
		OXML_Element_Table* pTable = new OXML_Element_Table("");
		m_tableStack.push(pTable);
		OXML_SharedElement table(pTable);
		rqst->stck->push(table);
		rqst->handled = true;
		pTable->setCurrentRowNumber(-1);
		pTable->setCurrentColNumber(-1);
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tr"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();
		OXML_Element_Row* pRow = new OXML_Element_Row("", table);
		m_rowStack.push(pRow);
		OXML_SharedElement row(pRow);
		rqst->stck->push(row);
		rqst->handled = true;
		table->incrementCurrentRowNumber();
		table->setCurrentColNumber(0);
		pRow->setRowNumber(table->getCurrentRowNumber());
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tc"))
	{
		if(m_tableStack.empty() || m_rowStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		OXML_Element_Row* row = m_rowStack.top();				
		OXML_Element_Cell* pCell = new OXML_Element_Cell("", table, row, 
								table->getCurrentColNumber(), table->getCurrentColNumber()+1, //left right
								table->getCurrentRowNumber(), table->getCurrentRowNumber()+1); //top,bottom
		m_cellStack.push(pCell);
		OXML_SharedElement cell(pCell);
		rqst->stck->push(cell);
		rqst->handled = true;
		table->incrementCurrentColNumber();
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "gridSpan"))
	{
		if(m_tableStack.empty() || m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val)
		{
			int span = atoi(val);
			int left = table->getCurrentColNumber()-1;
			int right = left + span;
			//change current cell's right index
			OXML_Element_Cell* cell = m_cellStack.top();
			cell->setRight(right);
			//update column index of current table			
			table->setCurrentColNumber(right);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "vMerge"))
	{
		if(m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Cell* cell = m_cellStack.top();				
		cell->setVerticalMergeStart(false); //default to continue if the attribute is missing
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && !strcmp(val, "restart")) 
		{
			cell->setVerticalMergeStart(true);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "hMerge"))
	{
		if(m_cellStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Cell* cell = m_cellStack.top();				
		cell->setHorizontalMergeStart(false); //default to continue if the attribute is missing
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && !strcmp(val, "restart")) 
		{
			cell->setHorizontalMergeStart(true);
		}
		rqst->handled = true;
	}

	//Table Properties
	else if(nameMatches(rqst->pName, NS_W_KEY, "gridCol") && 
			contextMatches(rqst->context->back(), NS_W_KEY, "tblGrid"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* w = attrMatches(NS_W_KEY, "w", rqst->ppAtts);
		if(w) 
		{
			//append this width to table-column-props property
			const gchar* tableColumnProps = NULL;
			UT_Error ret = table->getProperty("table-column-props", tableColumnProps);
			if((ret != UT_OK) || !tableColumnProps)
				tableColumnProps = "";				
			std::string cols(tableColumnProps);
			cols += _TwipsToPoints(w);
			cols += "pt/";
			ret = table->setProperty("table-column-props", cols);
			if(ret != UT_OK)
			{	
				UT_DEBUGMSG(("FRT:OpenXML importer can't set table-column-props:%s\n", cols.c_str()));
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "trHeight") && 
			contextMatches(rqst->context->back(), NS_W_KEY, "trPr"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val) 
		{
			const gchar* tableRowHeights = NULL;
			UT_Error ret = table->getProperty("table-row-heights", tableRowHeights);
			if((ret != UT_OK) || !tableRowHeights)
				tableRowHeights = "";				
			std::string rowHeights(tableRowHeights);
			rowHeights += _TwipsToPoints(val);
			rowHeights += "pt/";
			ret = table->setProperty("table-row-heights", rowHeights);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set table-row-heights:%s\n", rowHeights.c_str()));
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "left") ||
			nameMatches(rqst->pName, NS_W_KEY, "right") ||
			nameMatches(rqst->pName, NS_W_KEY, "top") ||
			nameMatches(rqst->pName, NS_W_KEY, "bottom"))
	{
		rqst->handled = true;
		const gchar* color = attrMatches(NS_W_KEY, "color", rqst->ppAtts);
		const gchar* sz = attrMatches(NS_W_KEY, "sz", rqst->ppAtts);
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);

		UT_Error ret = UT_OK;

		std::string borderName(rqst->pName);
		borderName = borderName.substr(strlen(NS_W_KEY)+1);
		if(!borderName.compare("bottom"))
			borderName = "bot";

		std::string borderStyle = borderName + "-style";
		std::string borderColor = borderName + "-color";
		std::string borderThickness = borderName + "-thickness";

		OXML_Element* element = NULL;

		if(rqst->context->empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(contextMatches(rqst->context->back(), NS_W_KEY, "tcBorders"))
			element = m_cellStack.empty() ? NULL : m_cellStack.top();
		else if(contextMatches(rqst->context->back(), NS_W_KEY, "tblBorders"))
			element = m_tableStack.empty() ? NULL : m_tableStack.top();

		if(!element)
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(color && strcmp(color, "auto")) 
		{
			ret = element->setProperty(borderColor, color);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:%s\n", borderColor.c_str(), color));
			}
		}
		if(sz) 
		{
			std::string szVal(_EighthPointsToPoints(sz));
			szVal += "pt";
			ret = element->setProperty(borderThickness, szVal);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:%s\n", borderThickness.c_str(), color));
			}
		}

		std::string styleValue = "1"; //single line border by default
		if(val)
		{
			if(!strcmp(val, "dashed"))
				styleValue = "0"; 
		}

		ret = element->setProperty(borderStyle, styleValue);
		if(ret != UT_OK)
		{
			UT_DEBUGMSG(("FRT:OpenXML importer can't set %s:0\n", borderStyle.c_str()));
		}
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "shd"))
	{
		const gchar* fill = attrMatches(NS_W_KEY, "fill", rqst->ppAtts);

		UT_Error ret = UT_OK;
		OXML_Element* element = NULL;

		if(rqst->context->empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(contextMatches(rqst->context->back(), NS_W_KEY, "tcPr"))
			element = m_cellStack.empty() ? NULL : m_cellStack.top();
		else if(contextMatches(rqst->context->back(), NS_W_KEY, "tblPr"))
			element = m_tableStack.empty() ? NULL : m_tableStack.top();

		if(!element)
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		if(fill && strcmp(fill, "auto")) 
		{
			ret = element->setProperty("background-color", fill);
			if(ret != UT_OK)
			{
				UT_DEBUGMSG(("FRT:OpenXML importer can't set background-color:%s\n", fill));	
			}
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tblStyle"))
	{
		if(m_tableStack.empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_Element_Table* table = m_tableStack.top();				
		const gchar* val = attrMatches(NS_W_KEY, "val", rqst->ppAtts);
		if(val && table) 
		{
			std::string styleName(val);
			OXML_Document* doc = OXML_Document::getInstance();
			if(doc)
				table->applyStyle(doc->getStyleById(styleName));
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tblPr"))
	{
		if(m_tableStack.empty())
		{
			//we must be in tblStyle in styles, so let's push the table instance to m_tableStack
			OXML_Element_Table* tbl = static_cast<OXML_Element_Table*>(get_pointer(rqst->stck->top()));
			m_tableStack.push(tbl);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "trPr"))
	{
		if(m_rowStack.empty())
		{
			//we must be in styles, so let's push the row instance to m_rowStack
			OXML_Element_Row* row = static_cast<OXML_Element_Row*>(get_pointer(rqst->stck->top()));
			m_rowStack.push(row);
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tcPr"))
	{
		if(m_cellStack.empty())
		{
			//we must be in styles, so let's push the cell instance to m_cellStack
			OXML_Element_Cell* cell = static_cast<OXML_Element_Cell*>(get_pointer(rqst->stck->top()));
			m_cellStack.push(cell);
		}
		rqst->handled = true;
	}
	//TODO: more coming here
}
Пример #3
0
int AP_UnixApp::main(const char * szAppName, int argc, char ** argv)
{
    // This is a static function.	
	
	if (!g_thread_supported ())
		g_thread_init (NULL);	
    
    // initialize our application.
	int exit_status = 0;
	AP_UnixApp * pMyUnixApp = new AP_UnixApp(szAppName);

#ifdef WITH_CHAMPLAIN
    gtk_clutter_init (&argc, &argv);
#endif
    
	/* this brace is here to ensure that our local variables on the stack
	 * do not outlive the application object by giving them a lower scope
	 */
	{
		XAP_Args XArgs = XAP_Args(argc, argv);
		AP_Args Args = AP_Args(&XArgs, szAppName, pMyUnixApp);
#ifdef LOGFILE
		UT_String sLogFile = pMyUnixApp->getUserPrivateDirectory();
		sLogFile += "abiLogFile";
		logfile = fopen(sLogFile.c_str(),"a+");
		fprintf(logfile,"About to do gtk_set_locale \n");
		fprintf(logfile,"New logfile \n");
#endif
		// Step 1: Initialize GTK and create the APP.
		// hack needed to intialize gtk before ::initialize
		setlocale(LC_ALL, "");
		gboolean have_display = gtk_init_check(&argc, &argv);
#ifdef LOGFILE
		fprintf(logfile,"Got display %d \n",have_display);
		fprintf(logfile,"Really display %d \n",have_display);
#endif
		if (have_display > 0) {
			Args.addOptions(gtk_get_option_group(TRUE));
			Args.parseOptions();
		}
		else {
			// no display, but we still need to at least parse our own arguments, damnit, for --to, --to-png, and --print
			Args.addOptions(gtk_get_option_group(FALSE));
			Args.parseOptions();
		}

		// if the initialize fails, we don't have icons, fonts, etc.
		if (!pMyUnixApp->initialize(have_display))
		{
			delete pMyUnixApp;
			return -1;	// make this something standard?
		}
	
		// Setup signal handlers, primarily for segfault
		// If we segfaulted before here, we *really* blew it
		struct sigaction sa;
		sa.sa_handler = signalWrapper;
    
		sigfillset(&sa.sa_mask);  // We don't want to hear about other signals
		sigdelset(&sa.sa_mask, SIGABRT); // But we will call abort(), so we can't ignore that
#if defined (SA_NODEFER) && defined (SA_RESETHAND)
		sa.sa_flags = SA_NODEFER | SA_RESETHAND; // Don't handle nested signals
#else
		sa.sa_flags = 0;
#endif
    
		sigaction(SIGSEGV, &sa, NULL);
		sigaction(SIGBUS, &sa, NULL);
		sigaction(SIGILL, &sa, NULL);
		sigaction(SIGQUIT, &sa, NULL);
		sigaction(SIGFPE, &sa, NULL);

		// TODO: handle SIGABRT
	
		// Step 2: Handle all non-window args.
    
		bool windowlessArgsWereSuccessful = true;
		if (!Args.doWindowlessArgs(windowlessArgsWereSuccessful )) {
			delete pMyUnixApp;
			return (windowlessArgsWereSuccessful ? 0 : -1);
		}

		if (have_display) {

			// Step 3: Create windows as appropriate.
			// if some args are botched, it returns false and we should
			// continue out the door.
			// We used to check for bShowApp here.  It shouldn't be needed
			// anymore, because doWindowlessArgs was supposed to bail already. -PL

			if (pMyUnixApp->openCmdLineFiles(&Args))
			{
#if defined(EMBEDDED_TARGET) && EMBEDDED_TARGET == EMBEDDED_TARGET_HILDON
				s_bInitDone = true;
				pMyUnixApp->processStartupQueue();
#endif
				// turn over control to gtk
				gtk_main();
			}
			else
			{
				UT_DEBUGMSG(("DOM: not parsing command line or showing app\n"));
			}
		}
		else {
			fprintf(stderr, "No DISPLAY: this may not be what you want.\n");
			exit_status = 1;
		}
		// unload all loaded plugins (remove some of the memory leaks shown at shutdown :-)
		XAP_ModuleManager::instance().unloadAllPlugins();

		// Step 4: Destroy the App.  It should take care of deleting all frames.
		pMyUnixApp->shutdown();
	}
	
	delete pMyUnixApp;
	
	return exit_status;
}
Пример #4
0
TCPAccountHandler::~TCPAccountHandler()
{
	UT_DEBUGMSG(("~TCPAccountHandler()\n"));
	if (m_bConnected)
		disconnect();
}
Пример #5
0
ConnectResult TCPAccountHandler::connect()
{
	UT_DEBUGMSG(("TCPAccountHandler::connect()\n"));

	AbiCollabSessionManager* pManager = AbiCollabSessionManager::getManager();
	UT_return_val_if_fail(pManager, CONNECT_INTERNAL_ERROR);

	UT_return_val_if_fail(!m_pDelegator, CONNECT_INTERNAL_ERROR);
	UT_return_val_if_fail(!m_bConnected, CONNECT_ALREADY_CONNECTED);
	UT_return_val_if_fail(!m_thread, CONNECT_INTERNAL_ERROR);
	m_io_service.reset();
	m_thread = new asio::thread(boost::bind(&asio::io_service::run, &m_io_service));

	// set up the connection
	if (getProperty("server") == "")
	{
		UT_sint32 port = _getPort(getProperties());
		UT_DEBUGMSG(("Start accepting connections on port %d...\n", port));

		try
		{
			IOServerHandler* pDelegator = new IOServerHandler(port, 
						boost::bind(&TCPAccountHandler::_handleAccept, this, _1, _2),
						boost::bind(&TCPAccountHandler::handleEvent, this, _1), m_io_service);
			m_pDelegator = pDelegator;
			m_bConnected = true; // todo: ask it to the acceptor
			pDelegator->run();
		}
		catch (asio::system_error se)
		{
			UT_DEBUGMSG(("Failed to start accepting connections: %s\n", se.what()));
			_teardownAndDestroyHandler();
			return CONNECT_FAILED;
		}
		catch (...)
		{
			UT_DEBUGMSG(("Caught unhandled server exception!\n"));
			_teardownAndDestroyHandler();
			return CONNECT_FAILED;
		}
	}
	else
	{
		UT_DEBUGMSG(("Connecting to server %s on port %d...\n", getProperty("server").c_str(), _getPort(getProperties())));

		try
		{
			asio::ip::tcp::resolver resolver(m_io_service);
			asio::ip::tcp::resolver::query query(getProperty("server"), getProperty("port"));
			asio::ip::tcp::resolver::iterator iterator(resolver.resolve(query));

			bool connected = false;
			boost::shared_ptr<Session> session_ptr(new Session(m_io_service, boost::bind(&TCPAccountHandler::handleEvent, this, _1)));
			while (iterator != tcp::resolver::iterator())
			{
				try
				{
					UT_DEBUGMSG(("Attempting to connect...\n"));
					session_ptr->connect(iterator);
					UT_DEBUGMSG(("Connected!\n"));
					connected = true;
					break;
				}
				catch (asio::system_error se)
				{
					UT_DEBUGMSG(("Connection attempt failed: %s\n", se.what()));
					// make sure we close the socket after a failed attempt, as it
					// may have been opened by the connect() call.
					try { session_ptr->getSocket().close(); } catch(...) {}
				}
				iterator++;
			}

			if (!connected)
			{
				UT_DEBUGMSG(("Giving up to connecting to server!\n"));
				_teardownAndDestroyHandler();
				return CONNECT_FAILED;
			}

			session_ptr->asyncReadHeader();
			m_bConnected = true; // todo: ask it to the socket
			// Add a buddy
			TCPBuddyPtr pBuddy = boost::shared_ptr<TCPBuddy>(new TCPBuddy(this, 
						session_ptr->getRemoteAddress(),
						boost::lexical_cast<std::string>(session_ptr->getRemotePort())));
			addBuddy(pBuddy);
			m_clients.insert(std::pair<TCPBuddyPtr, boost::shared_ptr<Session> >(pBuddy, session_ptr));
		}
		catch (asio::system_error se)
		{
			UT_DEBUGMSG(("Failed to resolve %s:%d: %s\n", getProperty("server").c_str(), _getPort(getProperties()), se.what()));
			_teardownAndDestroyHandler();
			return CONNECT_FAILED;
		}
	}
	
	if (!m_bConnected)
		return CONNECT_FAILED;

	// we are connected now, time to start sending out messages (such as events)
	pManager->registerEventListener(this);
	// signal all listeners we are logged in
	AccountOnlineEvent event;
	// TODO: fill the event
	AbiCollabSessionManager::getManager()->signal(event);

	return CONNECT_SUCCESS;
}
Пример #6
0
UT_Error IE_ImpGraphic_WMF::convertGraphic(UT_ByteBuf* pBBwmf,
					   UT_ByteBuf** ppBBpng)
{
	UT_ByteBuf * pBBpng = 0;

	wmf_error_t err;

	wmf_gd_t * ddata = 0;

	wmfAPI * API = 0;
	wmfAPI_Options api_options;

	wmfD_Rect bbox;

	unsigned long flags;

#if 0 // the code that uses these two variables is in an if 0 block below
	unsigned int max_width  = 500;
	unsigned int max_height = 500;
#endif

	unsigned int width, height;

	bbuf_read_info  read_info;
	bbuf_write_info write_info;

   	if (!pBBwmf) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Bad Arg (1)\n"));
		return UT_ERROR;
	}
   	if (!ppBBpng) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Bad Arg (2)\n"));
		return UT_ERROR;
	}

	*ppBBpng = 0;

	flags = WMF_OPT_IGNORE_NONFATAL | WMF_OPT_FUNCTION;

	api_options.function = wmf_gd_function;

	err = wmf_api_create(&API,flags,&api_options);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic No API\n"));
		return UT_ERROR;
	}

	ddata = WMF_GD_GetData(API);
	if ((ddata->flags & WMF_GD_SUPPORTS_PNG) == 0) { // Impossible, but...
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic No PNG\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

	read_info.pByteBuf = pBBwmf;

	read_info.len = pBBwmf->getLength();
	read_info.pos = 0;

	err = wmf_bbuf_input (API,AbiWord_WMF_read,AbiWord_WMF_seek,AbiWord_WMF_tell,(void *) &read_info);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Bad input set\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

	err = wmf_scan (API,0,&bbox);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Scan failed\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

	/* TODO: be smarter about getting the resolution from screen 
	 */
	double resolution_x, resolution_y;
	resolution_x = resolution_y = 72.0;

	err = wmf_display_size (API, &width, &height, resolution_x, resolution_y);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Get size failed\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

	ddata->width  = (unsigned int) width;
	ddata->height = (unsigned int) height;

	if ((ddata->width == 0) || (ddata->height == 0)) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Size error (1)\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

#if 0
	// not sure if this branch is needed any more after the recent changes
	// done by FJF and myself inside of libWMF for better size detection - DAL

	if ((ddata->width >= max_width) || (ddata->height >= max_height)) {
		float ratio_wmf = height / width;
		float ratio_bounds = (float) max_height / (float) max_width;

		if (ratio_wmf > ratio_bounds) {
			ddata->height = max_height;
			ddata->width  = (unsigned int) ((float) ddata->height / ratio_wmf);
		}
		else {
			ddata->width  = max_width;
			ddata->height = (unsigned int) ((float) ddata->width  * ratio_wmf);
		}
	}
#endif

	if ((ddata->width == 0) || (ddata->height == 0)) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Size error (1)\n"));
		wmf_api_destroy(API);
		return UT_ERROR;
	}

	ddata->bbox = bbox;

	ddata->type = wmf_gd_png;

	pBBpng = new UT_ByteBuf;
	if (pBBpng == 0) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Ins. Mem.\n"));
		wmf_api_destroy(API);
		return UT_IE_NOMEMORY;
	}

	write_info.pByteBuf = pBBpng;

	ddata->flags |= WMF_GD_OUTPUT_MEMORY | WMF_GD_OWN_BUFFER;

	ddata->sink.context = (void *) &write_info;
	ddata->sink.function = AbiWord_WMF_function;

	err = wmf_play(API,0,&bbox);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Play failed\n"));
	}

	err = wmf_api_destroy(API);

	if (err == wmf_E_None) {
		*ppBBpng = pBBpng;
		return UT_OK;
	}

	UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Err. on destroy\n"));

	DELETEP(pBBpng);

	return UT_ERROR;
}
Пример #7
0
UT_Error IE_Exp_WordPerfect::_writeHeader()
{
	int i = 0;
	UT_DEBUGMSG(("WordPerfect Exporter::_writeHeader\n"));
	
	m_buffer = new UT_String();
	
	*m_buffer += (char)0xFF;						// -1
	*m_buffer += "WPC";								// WPC
	_UT_String_add(*m_buffer, (int)0x00000000);		// pointer to document area; THIS IS A DUMMY VALUE!
	*m_buffer += (char)0x01;						// program that created the file, WordPerfect itself = 1, we choose also 1 :-)
	*m_buffer += (char)0x0A;						// file type, WordPerfect document had type 0x0A
	*m_buffer += (char)0x02;						// major version of file, WP 8.0 = 2
	*m_buffer += (char)0x01;						// minor version of file, WP 8.0 = 1
	_UT_String_add(*m_buffer, (short)0x0000);		// encryption key; 0 means no encryption is used
	_UT_String_add(*m_buffer, (short)0x0200);		// offset to the index header = 0x200
	*m_buffer += char(0x05);						// reserved; beginning of extended file header, fixed entry count = 5
	*m_buffer += (char)0x00;						// reserved; completeness indicator
	_UT_String_add(*m_buffer, (short)0x0000);		// reserved; offset to proprietary data
	_UT_String_add(*m_buffer, (int)0x00000000);		// file size, not including pad charachters at EOF; THIS IS A DUMMY VALUE!

	for (i=0; i<488; i++) { *m_buffer += (char)0x00; } // extended header, 488 bytes
		
	// Index and Packet Data Areas follow
	
	*m_buffer += (char)0x02;						// index header; flags = 2
	*m_buffer += (char)0x00;						// index header; reserved = 0
	_UT_String_add(*m_buffer, (short)0x0005);		// index header; number of indexes in index block, we write 5 packets
	for (i=0; i<10; i++) { *m_buffer += (char)0x00; } // index header; reserved = 0 x 10
	
		
	// FIXME: clean me up
	m_ptrDesiredFontUseCount = m_buffer->length() + 2;

	// This is a piece of the index header which I can't figure out yet
	// When I do figure out what it all means, I'll replace it with some nice header-writing functions
	char magic[192] = 
	{
		// Desired Font
		(char)0x00, (char)0x55, 
		(char)0x01, (char)0x00, (char)0x00, (char)0x00, (char)0x4E, (char)0x00, (char)0x00, (char)0x00, (char)0x46, (char)0x02, (char)0x00, (char)0x00, 
		
		// Initial Font
		(char)0x09, (char)0x25, (char)0x01, (char)0x00, 
		(char)0x00, (char)0x00, (char)0x06, (char)0x00, (char)0x00, (char)0x00, (char)0x94, (char)0x02, (char)0x00, (char)0x00, 
		
		// Style Data
		(char)0x0B, (char)0x30, (char)0x02, (char)0x00, (char)0x00, (char)0x00, 
		(char)0x28, (char)0x00, (char)0x00, (char)0x00, (char)0x9A, (char)0x02, (char)0x00, (char)0x00, 
		
		// Prefix Time Stamp
		(char)0x08, (char)0x5E, (char)0x01, (char)0x00, (char)0x00, (char)0x00, (char)0x0C, (char)0x00, 
		(char)0x00, (char)0x00, (char)0xC2, (char)0x02, 
		
		// Extra Desired Font Information
		(char)0x00, (char)0x00,
		(char)0x28, (char)0x00, (char)0xD6, (char)0x1E, (char)0xC3, (char)0x0f, (char)0x39, (char)0x08, (char)0x00, (char)0x00, 
		(char)0x11, (char)0x09, (char)0x00, (char)0x00, (char)0x00, (char)0x5A, (char)0x00, (char)0x1B, (char)0x01, (char)0x00, (char)0x8B, (char)0x14, (char)0x36, (char)0x00, (char)0x54, (char)0x00, 
		(char)0x69, (char)0x00, (char)0x6D, (char)0x00, (char)0x65, (char)0x00, (char)0x73, (char)0x00, (char)0x20, (char)0x00, (char)0x4E, (char)0x00, (char)0x65, (char)0x00, (char)0x77, (char)0x00, 
		(char)0x20, (char)0x00, (char)0x52, (char)0x00, (char)0x6F, (char)0x00, (char)0x6D, (char)0x00, (char)0x61, (char)0x00, (char)0x6E, (char)0x00, (char)0x20, (char)0x00, (char)0x52, (char)0x00, 
		(char)0x65, (char)0x00, (char)0x67, (char)0x00, (char)0x75, (char)0x00, (char)0x6C, (char)0x00, (char)0x61, (char)0x00, (char)0x72, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, 
		(char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x01, (char)0x00, (char)0x01, (char)0x00, (char)0x58, (char)0x02, (char)0x01, (char)0x00, (char)0x00, (char)0x00, (char)0x04, (char)0x00, 
		(char)0x28, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, 
		(char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x01, (char)0x12, (char)0x02, (char)0x00, (char)0x24, (char)0x00, (char)0xA1, (char)0x00, (char)0x00, (char)0x00, (char)0xA1, (char)0x00, 
		(char)0x00, (char)0x00, (char)0x50, (char)0xA5, (char)0x4E, (char)0x25, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x00, (char)0x08, (char)0x00, 
	};
		
	// add the magic index contents to get a nice and working header
	_UT_String_add_chars(*m_buffer, magic, 192);

	// we're done writing the header, save this position as the start of document		
	m_ptrToDocument = m_buffer->length();
	
	// write some global document properties now
	_handleGlobalOn();
	_handleGlobalOff();
	
	return UT_OK;
}
Пример #8
0
/*!
 * Sets given attribute in this PP_AttrProp bundle.
 * Deals correctly with setting the PT_PROPS_ATTRIBUTE_NAME property:
 * intercepts this call and appends properties instead.
 *
 * Because all mutations of attributes go through here, it is always the
 * case that the props attribute is correctly handled.
 */
bool	PP_AttrProp::setAttribute(const gchar * szName, const gchar * szValue)
{
	// TODO when this assert fails, switch this file to use UT_XML_ version of str*() functions.
	UT_return_val_if_fail (sizeof(char)==sizeof(gchar), false);

	if (0 == strcmp(szName, PT_PROPS_ATTRIBUTE_NAME) && *szValue)	// PROPS -- cut value up into properties
	{
		char * pOrig = NULL;
		
		if (!(pOrig = g_strdup(szValue)))
		{
			UT_DEBUGMSG(("setAttribute: g_strdup() failed on [%s]\n",szValue));
			return false;
		}

		// This function parses out CSS properties, separated by semicolons.

		char *z = pOrig;
		int bDone = 0;
		while (!bDone)
		{
			// p will point to the property name.  q will be the property value.
			char *p = z;
			char *q = p;
			// skip the whitespace before the property name
			while (isspace(*p))
				p++;

			// skip to the colon to find the value
			while (*q && (*q != ':'))
				q++;

			// if there was no colon, this is invalid
			if (!*q)
			{
				g_free(pOrig);
				UT_DEBUGMSG(("props: %s\n", szValue));
				return false;
			}

			// zero-out the colon, thus separating into two strings.
			*q = 0;
			q++;

			// now, search ahead for the next semicolon, and separate this property from the next
			z = q;
			while (*z && (*z != ';'))
				z++;

			if (*z == ';')
			{
				*z = 0;
				z++;
			}
			else
			{
				bDone = 1;
			}

			// skip the whitespace before the property value
			while ((*q > 0) && isspace(*q))
				q++;

			setProperty(p, q);
		}

		g_free(pOrig);
		return true;
	}
	else if (0 == strcmp(szName, PT_XID_ATTRIBUTE_NAME) && *szValue)
	{
		// XID is a unique id for the xml element / PT frag. Its function is to facilitate
		// comparing/merging documents and we do not want it in the AP
		return true;
	}
	else // not "PROPS" -- add to attribute list
	{
		UT_UTF8String url;
		if (szValue && *szValue && (0 == strcmp(szName, "xlink:href") || 0 == strcmp(szName, "href")))
		{
			url = szValue;
			url.decodeURL();
			szValue = url.utf8_str();
		}
		
		if (!m_pAttributes)
		{
			m_pAttributes = new UT_GenericStringMap<gchar*>(5);
			if (!m_pAttributes)
			{
				UT_DEBUGMSG(("setAttribute: could not allocate hash table.\n"));
				return false;
			}
		}

		// make sure we store attribute names in lowercase
		UT_ASSERT_HARMLESS(sizeof(char) == sizeof(gchar));

		char * copy = g_ascii_strdown(szName, -1);
		char * szDupValue = szValue ? g_strdup(szValue) : NULL;

		// get rid of any illegal chars we might have been given
		if(!UT_isValidXML(copy))
			UT_validXML(copy);
		if(!UT_isValidXML(szDupValue))
			UT_validXML(szDupValue);

		const char * pEntry = m_pAttributes->pick(copy);

		if(pEntry)
		{
			// attribute exists, replace it
			FREEP(pEntry);
			m_pAttributes->set(copy, szDupValue);
		}
		else
		{
			bool bRet = m_pAttributes->insert(copy, szDupValue);
			UT_ASSERT_HARMLESS( bRet );
			if(!bRet)
			{
				FREEP(szDupValue);
			}
		}
		
		FREEP(copy);

		return true;
	}
}
Пример #9
0
/*! This method inserts a new pair of property name and value into [this] APs set of
	 properties, creating "props" if it does not already exist and overwriting the value
	 of any property of the same name with the newly passed value.
	 (?)It appears as though we replace the entire pair, rather than only the value.
		 (?)Is there a reason for this?
	 \return Whether or not the operation succeeded.
*/
bool	PP_AttrProp::setProperty(const gchar * szName, const gchar * szValue)
{
	UT_return_val_if_fail( szName, false );
	
	if (!m_pProperties)
	{
		m_pProperties = new UT_GenericStringMap<PropertyPair*>(5);
		if (!m_pProperties)
		{
			UT_DEBUGMSG(("setProperty: could not allocate hash table.\n"));
			return false;
		}
	}

	// if szValue == NULL or *szValue == 0, indicates absent property.
	// We have to set it empty, otherwise the code that changes
	// properties has no way of knowing that this property is not to
	// be present
	// 
	//bool bRemove = (!szValue || !*szValue);

	// get rid of any chars invalid in xml
	char * szName2 = NULL;
	if(!UT_isValidXML(szName))
	{
		szName2 = g_strdup(szName);

		// get rid of any illegal chars we were passed
		UT_validXML(szName2);

		szName = szName2;
	}
	
	char * szValue2 = szValue ? g_strdup(szValue) : NULL;
	UT_return_val_if_fail( szName && (szValue2 || !szValue), false);

	// get rid of any illegal chars we might have been given in the value
	if(!UT_isValidXML(szValue2))
		UT_validXML(szValue2);
	
	const PropertyPair * pEntry = m_pProperties->pick(szName);
	if (pEntry)
	{
		const PropertyPair* p = pEntry;

		// hack. don't do it.
		gchar* tmp = (gchar*)p->first;
		UT_return_val_if_fail (!m_bIsReadOnly, false);
		if(strcmp(szName,"line-height") == 0)
		{
			UT_DEBUGMSG(("Found line-height, Old value %s new value is %s \n",tmp,szValue));
		}

		FREEP(tmp);
		if (p->second) 
		{
			delete p->second;
		}
		delete p;
		m_pProperties->set(szName, 
				   new PropertyPair(szValue2, 
						    (const PP_PropertyType*)NULL));
	}
	else
	{
		m_pProperties->insert(szName, 
				      new PropertyPair(szValue2, 
						       (const PP_PropertyType*)NULL));
	}

	// g_free the name duplicate if necessary
	FREEP(szName2);
	
	return true;
}
Пример #10
0
UT_Error UT_XML::parse (const char * szFilename)
{
	UT_ASSERT (m_pListener || m_pExpertListener);
	UT_ASSERT (szFilename);
	
	if ((szFilename == 0) || ((m_pListener == 0) && (m_pExpertListener == 0))) return UT_ERROR;
	if (!reset_all ()) return UT_OUTOFMEM;
	
	UT_Error ret = UT_OK;
	
	DefaultReader defaultReader;
	Reader * reader = &defaultReader;
	if (m_pReader)
		reader = m_pReader;
	
	if (!reader->openFile (szFilename))
    {
		UT_DEBUGMSG (("Could not open file %s\n", szFilename));
		return UT_errnoToUTError ();
    }
	
	char buffer[2048];
	
	m_bStopped = false;
	
	xmlSAXHandler hdl;
	xmlParserCtxtPtr ctxt = 0;
	
	memset(&hdl, 0, sizeof(hdl));
	
	hdl.getEntity    = _getEntity;
	hdl.startElement = _startElement;
	hdl.endElement   = _endElement;
	hdl.characters   = _charData;
	hdl.error        = _errorSAXFunc;
	hdl.fatalError   = _fatalErrorSAXFunc;
	hdl.processingInstruction = _processingInstruction;
	hdl.comment      = _comment;
	hdl.cdataBlock   = _cdata;

	size_t length = reader->readBytes (buffer, sizeof (buffer));
	int done = (length < sizeof (buffer));
	
	if (length != 0)
    {
		ctxt = xmlCreatePushParserCtxt (&hdl, static_cast<void *>(this), buffer, static_cast<int>(length), szFilename);
		if (ctxt == NULL)
		{
			UT_DEBUGMSG (("Unable to create libxml2 push-parser context!\n"));
			reader->closeFile ();
			return UT_ERROR;
		}
		xmlSubstituteEntitiesDefault (1);
		UT_sint32 chucks = -1;
		while (!done && !m_bStopped)
		{
			chucks++;
			length = reader->readBytes (buffer, sizeof (buffer));
			UT_DEBUGMSG(("Done chunk %d length %zd \n",chucks,length));
			done = (length < sizeof (buffer));
			
			if (xmlParseChunk (ctxt, buffer, static_cast<int>(length), 0))
			{
			  if(getNumMinorErrors() > getNumRecoveredErrors())
			    {
				UT_DEBUGMSG (("Error - 1 parsing '%s' (Line: %d, Column: %d)\n", szFilename, xmlSAX2GetLineNumber(ctxt), xmlSAX2GetColumnNumber(ctxt)));
				ret = UT_IE_IMPORTERROR;
				break;
			    }
			}
		}
		if (ret == UT_OK)
		  if (!m_bStopped && (getNumMinorErrors() == 0))
			{
				if (xmlParseChunk (ctxt, "", 0, 1))
				{
					UT_DEBUGMSG (("Error -2 parsing '%s' (Line: %d, Column: %d)\n", szFilename, xmlSAX2GetLineNumber(ctxt), xmlSAX2GetColumnNumber(ctxt)));
					ret = UT_IE_IMPORTERROR;
				}
			}
		if (ret == UT_OK && (getNumMinorErrors() == 0))
			if (!ctxt->wellFormed && !m_bStopped) ret = UT_IE_IMPORTERROR; // How does stopping mid-file affect wellFormed?

		xmlDocPtr myXmlDoc = ctxt->myDoc;
		xmlFreeParserCtxt (ctxt);
		xmlFreeDoc(myXmlDoc);
    }
	else
    {
		UT_DEBUGMSG(("Empty file to parse - not sure how to proceed\n"));
    }
	
	reader->closeFile ();
	
	return ret;
}
/*!
 * Fill the GUI tree with the styles as defined in the XP tree.
 */
void  AP_UnixDialog_Stylist::_fillTree(void)
{
	Stylist_tree * pStyleTree = getStyleTree();
	if(pStyleTree == NULL)
	{
		updateDialog();
		pStyleTree = getStyleTree();
	}
	if(pStyleTree->getNumRows() == 0)
	{
		updateDialog();
		pStyleTree = getStyleTree();
	}
	UT_DEBUGMSG(("Number of rows of styles in document %d \n",pStyleTree->getNumRows()));
	if(m_wRenderer)
	{
//		g_object_unref (G_OBJECT (m_wRenderer));
		gtk_widget_destroy (m_wStyleList);
	}

	GtkTreeIter iter;
	GtkTreeIter child_iter;
	GtkTreeSelection *sel;
	UT_sint32 row,col, page;

	m_wModel = gtk_tree_store_new (3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);

	page = 0;
	UT_UTF8String sTmp(""); 
	for(row= 0; row < pStyleTree->getNumRows();row++)
	{
		gtk_tree_store_append (m_wModel, &iter, NULL);
		if(!pStyleTree->getNameOfRow(sTmp,row))
		{
			UT_ASSERT(UT_SHOULD_NOT_HAPPEN);
			break;
		}
		if(pStyleTree->getNumCols(row) > 0)
		{
			xxx_UT_DEBUGMSG(("Adding Heading %s at row %d \n",sTmp.utf8_str(),row));

			gtk_tree_store_set (m_wModel, &iter, 0, sTmp.utf8_str(), 1, row,2,0, -1);
			for(col =0 ; col < pStyleTree->getNumCols(row); col++)
			{
				gtk_tree_store_append (m_wModel, &child_iter, &iter);
				if(!pStyleTree->getStyleAtRowCol(sTmp,row,col))
				{
					UT_ASSERT(UT_SHOULD_NOT_HAPPEN);
					break;
				}
				gtk_tree_store_set (m_wModel, &child_iter, 0, sTmp.utf8_str(), 1, row,2,col+1, -1);
				xxx_UT_DEBUGMSG(("Adding style %s at row %d col %d \n",sTmp.utf8_str(),row,col+1));
				page++;
			}
		}
		else
		{
			xxx_UT_DEBUGMSG(("Adding style %s at row %d \n",sTmp.utf8_str(),row));
			gtk_tree_store_set (m_wModel, &iter, 0, sTmp.utf8_str(), 1,row,2,0,-1);
			page++;
		}
	}

	// create a new treeview
	m_wStyleList = gtk_tree_view_new_with_model (GTK_TREE_MODEL (m_wModel));
	g_object_unref (G_OBJECT (m_wModel));
	gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (m_wStyleList), true);

	// get the current selection
	sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (m_wStyleList));
	gtk_tree_selection_set_mode (sel, GTK_SELECTION_BROWSE);
	gtk_tree_selection_set_select_function (sel, tree_select_filter,
														 NULL, NULL);
	
	const XAP_StringSet * pSS = m_pApp->getStringSet ();
	m_wRenderer = gtk_cell_renderer_text_new ();
	UT_UTF8String s;
	pSS->getValueUTF8(AP_STRING_ID_DLG_Stylist_Styles,s);
	gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (m_wStyleList),
												 -1, s.utf8_str(),
												 m_wRenderer, "text", 0, NULL); 	

	gtk_tree_view_collapse_all (GTK_TREE_VIEW (m_wStyleList));
	gtk_container_add (GTK_CONTAINER (m_wStyleListContainer), m_wStyleList);

	g_signal_connect_after(G_OBJECT(m_wStyleList),
						   "cursor-changed",
						   G_CALLBACK(s_types_clicked),
						   static_cast<gpointer>(this));

	g_signal_connect_after(G_OBJECT(m_wStyleList),
						   "row-activated",
						   G_CALLBACK(s_types_dblclicked),
						   static_cast<gpointer>(this));
	gtk_widget_show_all(m_wStyleList);
	setStyleTreeChanged(false);
}
void AP_UnixDialog_Lists::loadXPDataIntoLocal(void)
{
	//
	// This function reads the various memeber variables and loads them into
	// into the dialog variables.
	//

  //
  // Block all signals while setting these things
  //
	XAP_GtkSignalBlocker b1(  G_OBJECT(m_oAlignList_adj), m_iAlignListSpinID);
	XAP_GtkSignalBlocker b2(  G_OBJECT(m_oIndentAlign_adj), m_iIndentAlignSpinID);

	XAP_GtkSignalBlocker b3(  G_OBJECT(m_wDecimalEntry), m_iDecimalEntryID);
	XAP_GtkSignalBlocker b4(  G_OBJECT(m_wDelimEntry), m_iDelimEntryID );
	//
	// HACK to effectively block an update during this method
	//
	m_bDontUpdate = true;

	UT_DEBUGMSG(("loadXP newListType = %d \n",getNewListType()));
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(m_wAlignListSpin),getfAlign());
	float indent = getfAlign() + getfIndent();
	gtk_spin_button_set_value(GTK_SPIN_BUTTON( m_wIndentAlignSpin),indent);
	if( (getfIndent() + getfAlign()) < 0.0)
	{
		setfIndent( - getfAlign());
		gtk_spin_button_set_value(GTK_SPIN_BUTTON( m_wIndentAlignSpin), 0.0);

	}
	//
	// Code to work out which is active Font
	//
	if(getFont() == "NULL")
	{
		gtk_combo_box_set_active(m_wFontOptions, 0 );
	}
	else
	{
        size_t i = 0;
		for(std::vector<std::string>::const_iterator iter = m_glFonts.begin();
            iter != m_glFonts.end(); ++iter, ++i)
		{
			if(*iter == getFont())
				break;
		}
        if(i < m_glFonts.size())
		{
			gtk_combo_box_set_active(m_wFontOptions, i + 1 );
		}
		else
		{
			gtk_combo_box_set_active(m_wFontOptions, 0 );
		}
	}
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(m_wStartSpin),static_cast<float>(getiStartValue()));

    gtk_entry_set_text( GTK_ENTRY(m_wDecimalEntry), getDecimal().c_str());
	gtk_entry_set_text( GTK_ENTRY(m_wDelimEntry), getDelim().c_str());

	//
	// Now set the list type and style
	FL_ListType save = getNewListType();
	if(getNewListType() == NOT_A_LIST)
	{
		styleChanged(0);
		setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 0);
		gtk_combo_box_set_active(m_wListStyleBox, 0);
	}
	else if(IS_BULLETED_LIST_TYPE(getNewListType()) )
	{
		styleChanged(1);
		setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 1);
		gtk_combo_box_set_active(m_wListStyleBox, (gint) (getNewListType() - BULLETED_LIST));
	}
	else
	{
		styleChanged(2);
	    setNewListType(save);
		gtk_combo_box_set_active(m_wListTypeBox, 2);
		if(getNewListType() < OTHER_NUMBERED_LISTS)
		{
			gtk_combo_box_set_active(m_wListStyleBox, getNewListType());
		}
		else
		{
		    gint iMenu = static_cast<gint>(getNewListType()) - OTHER_NUMBERED_LISTS + BULLETED_LIST -1 ;
			gtk_combo_box_set_active(m_wListStyleBox,iMenu);
		}
	}

	//
	// HACK to allow an update during this method
	//
	m_bDontUpdate = false;
}
Пример #13
0
bool AP_Win32App::_pasteFormatFromClipboard(PD_DocumentRange * pDocRange, const char * szFormat,
											const char * szType, bool bWide)
{
	HANDLE	hData;
	bool 	bSuccess = false;	
  
	if (!(hData = m_pClipboard->getHandleInFormat(szFormat)))
		return bSuccess;		
 		
 	// It's a bitmap
 	if (g_ascii_strcasecmp(szFormat, AP_CLIPBOARD_BMP)==0)
	{			
 		HBITMAP					hBitmap;
 		PBITMAPINFO 			bi;
 		HWND		 			hWnd;
 		HDC 					hdc;
 		IE_ImpGraphic*			pIEG = NULL;
 		FG_Graphic* 			pFG = NULL;	
 		UT_Error 				errorCode;		
 		UT_ByteBuf 				byteBuf;				
 		IEGraphicFileType		iegft = IEGFT_BMP;	
 		XAP_Frame* 				pFrame;						
 		AP_FrameData* 			pFrameData;		
 		FL_DocLayout*			pDocLy;	
 		FV_View* 				pView;						
		UT_ByteBuf*				bBufBMP = new UT_ByteBuf;
 		
 		hBitmap = (HBITMAP)hData;					
 		hWnd =  GetDesktopWindow();
 		hdc = GetDC(hWnd);		
 		
 		// Create a BMP file from a BITMAP
 		bi =  CreateBitmapInfoStruct(hBitmap);						
 		CreateBMP(hWnd, *bBufBMP, bi, hBitmap,hdc);                  										
 		
 		// Since we are providing the file type, there is not need to pass the bytebuff filled up
 		errorCode = IE_ImpGraphic::constructImporter(*bBufBMP, iegft, &pIEG);				 				
		 				
 		if(errorCode != UT_OK)		
			return false;				  	
		 				 			
 		errorCode = pIEG->importGraphic(bBufBMP, &pFG); 		
 		
 		if(errorCode != UT_OK || !pFG)
		{
			DELETEP(bBufBMP);
			DELETEP(pIEG);
 			return false;
		}
		// sunk in importGraphic
		bBufBMP = NULL;
 		 
 		// Insert graphic in the view
 		pFrame = getLastFocussedFrame(); 						
 		pFrameData = (AP_FrameData*) pFrame->getFrameData();		
 		pDocLy =	pFrameData->m_pDocLayout;	
 		pView =  pDocLy->getView();		
 				
 		errorCode = pView->cmdInsertGraphic(pFG);	  		  		
 	
		DELETEP(pIEG);
 		//DELETEP(pFG);		
 		
 		bSuccess = true;
 	}
 	else	
	{
		unsigned char * pData = static_cast<unsigned char *>(GlobalLock(hData));
		UT_DEBUGMSG(("Paste: [fmt %s %s][hdata 0x%08lx][pData 0x%08lx]\n",
					 szFormat, szType,  hData, pData));
		UT_uint32 iSize = GlobalSize(hData);
		UT_uint32 iStrLen = bWide
			? wcslen(reinterpret_cast<const wchar_t *>(pData)) * 2
			: strlen(reinterpret_cast<const char *>(pData));
		UT_uint32 iLen = UT_MIN(iSize,iStrLen);

		
		IE_Imp * pImp = 0;
		IE_Imp::constructImporter(pDocRange->m_pDoc, IE_Imp::fileTypeForSuffix(szType), &pImp, 0);
		if (pImp)
		{
			const char * szEncoding = 0;
			if (bWide)
				szEncoding = XAP_EncodingManager::get_instance()->getUCS2LEName();
			else
				; // TODO Get code page using CF_LOCALE
			pImp->pasteFromBuffer(pDocRange,pData,iLen,szEncoding);
			delete pImp;
		}

		GlobalUnlock(hData);
		bSuccess = true;
	}
	return bSuccess;
}
Пример #14
0
/*!
    copy data in required format to the clipboard
*/
bool AP_Win32App::_copyFmtToClipboard(PD_DocumentRange * pDocRange, const char * pszFmt)
{
	UT_return_val_if_fail(m_pClipboard && pszFmt, false);
	
	UT_ByteBuf buf;
	UT_Error status;;
	UT_Byte b = 0;

	if(0 == strcmp(AP_CLIPBOARD_TEXTPLAIN_8BIT, pszFmt))
	{
		IE_Exp_Text * pExpText = new IE_Exp_Text(pDocRange->m_pDoc);
		if (pExpText)
		{
			status = pExpText->copyToBuffer(pDocRange,&buf);

			if(status != UT_OK)
				return false;
			
			buf.append(&b,1);			// NULL terminate the string
			m_pClipboard->addData(AP_CLIPBOARD_TEXTPLAIN_8BIT,
								  (UT_Byte *)buf.getPointer(0),buf.getLength());
			DELETEP(pExpText);
			UT_DEBUGMSG(("CopyToClipboard: copying %d bytes in TEXTPLAIN format.\n",
						 buf.getLength()));
		}
		else
		{
			return false;
		}
		
	}
	else if(0 == strcmp(AP_CLIPBOARD_TEXTPLAIN_UCS2, pszFmt))
	{
		const char *szEnc = XAP_EncodingManager::get_instance()->getNativeUnicodeEncodingName(); 
		IE_Exp_Text * pExpUnicodeText = new IE_Exp_Text(pDocRange->m_pDoc,szEnc);
		if (pExpUnicodeText)
		{
			status = pExpUnicodeText->copyToBuffer(pDocRange,&buf);

			if(status != UT_OK)
				return false;
			
			UT_Byte b[2] = {0,0};
			buf.append(b,2);			// NULL terminate the string
			m_pClipboard->addData(AP_CLIPBOARD_TEXTPLAIN_UCS2,
								  (UT_Byte *)buf.getPointer(0),buf.getLength());
			DELETEP(pExpUnicodeText);
			UT_DEBUGMSG(("CopyToClipboard: copying %d bytes in TEXTPLAIN UNICODE format.\n",
						 buf.getLength()*2));
		}
		else
		{
			return false;
		}
	}
	else if(0 == strcmp(AP_CLIPBOARD_RTF, pszFmt))
	{
		IE_Exp_RTF * pExpRtf = new IE_Exp_RTF(pDocRange->m_pDoc);
		if (pExpRtf)
		{
			status = pExpRtf->copyToBuffer(pDocRange,&buf);

			if(status != UT_OK)
				return false;
			
			buf.append(&b,1);			// NULL terminate the string
			m_pClipboard->addData(AP_CLIPBOARD_RTF,(UT_Byte *)buf.getPointer(0),buf.getLength());
			DELETEP(pExpRtf);
			UT_DEBUGMSG(("CopyFmtToClipboard: copying %d bytes in RTF format.\n",
						 buf.getLength()));
		}
		else
		{
			return false;
		}
	}

	return true;
}
Пример #15
0
// This creates our FG_Graphic object for a PNG
UT_Error IE_ImpGraphic_WMF::importGraphic(UT_ByteBuf* pBBwmf, 
					  FG_Graphic ** ppfg)
{
	UT_Error err = UT_OK;

	*ppfg = 0;
	UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Begin -\n"));

	bool importAsPNG = true;

#ifdef TOOLKIT_GTK
	importAsPNG = false;
#endif

	if (importAsPNG) {

		UT_ByteBuf * pBBpng = 0;

		FG_GraphicRaster * pFGR = 0;

		err = convertGraphic(pBBwmf,&pBBpng);
		if (err != UT_OK) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Conversion failed...\n"));
			return err;
		}

		pFGR = new FG_GraphicRaster();
		if(pFGR == 0) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Ins. Mem.\n"));
			err = UT_IE_NOMEMORY;
		}
		else if(!pFGR->setRaster_PNG(pBBpng)) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Fake type?\n"));
			DELETEP(pFGR);
			err = UT_IE_FAKETYPE;
		}
		else {
			*ppfg = (FG_Graphic *) pFGR;
		}
	} else {
		UT_ByteBuf *svg = 0;
		err = convertGraphicToSVG(pBBwmf, &svg);
		if (err != UT_OK) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Conversion failed...\n"));
			return err;
		}

		FG_GraphicVector * pFGR = 0;
		pFGR = new FG_GraphicVector();
		if(pFGR == 0) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Ins. Mem.\n"));
			err = UT_IE_NOMEMORY;
		}
		else if(!pFGR->setVector_SVG(svg)) {
			UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic Fake type?\n"));
			DELETEP(pFGR);
			err = UT_IE_FAKETYPE;
		}
		else {
			*ppfg = (FG_Graphic *) pFGR;
		}
	}

	UT_DEBUGMSG(("IE_ImpGraphic_WMF::importGraphic - End\n"));

	return err;
}
Пример #16
0
/*!
 * Set all pagesize parameters via const gchar attributes
 */
bool fp_PageSize::Set(const gchar ** attributes)
{
	const gchar * szPageSize=NULL, * szOrientation=NULL, * szWidth=NULL, * szHeight=NULL, * szUnits=NULL, * szPageScale=NULL;
	double width=0.0;
	double height=0.0;
	double scale =1.0;
	UT_Dimension u = DIM_IN;

	for (const gchar ** a = attributes; (*a); a++)
	{
	  UT_DEBUGMSG(("PageSize  -prop %s value %s \n",a[0],a[1]));
		if (strcmp(a[0],"pagetype") == 0)
		        szPageSize = a[1];
		else if (strcmp(a[0], "orientation") == 0)
			szOrientation = a[1];
		else if (strcmp(a[0], "width") == 0)
			szWidth = a[1];
		else if (strcmp(a[0], "height") == 0)
			szHeight = a[1];
		else if (strcmp(a[0], "units") == 0)
			szUnits = a[1];
		else if (strcmp(a[0], "page-scale") == 0)
			szPageScale = a[1];
		a++;
	}
	if(!szPageSize)
		return false;
	if(!szOrientation)
		return false;
	Set(static_cast<const char *>(szPageSize));

	if( szWidth && szHeight && szUnits && szPageScale)
	  {
		if(g_ascii_strcasecmp(szPageSize,"Custom") == 0)
		  {
		    width = UT_convertDimensionless(szWidth);
		    height = UT_convertDimensionless(szHeight);
		    if(strcmp(szUnits,"cm") == 0)
		      u = DIM_CM;
		    else if(strcmp(szUnits,"mm") == 0)
		      u = DIM_MM;
		    else if(strcmp(szUnits,"inch") == 0)
		      u = DIM_IN;
		    Set(width,height,u);
		  }

		scale =  UT_convertDimensionless(szPageScale);
		setScale(scale);
	  }

	// set portrait by default
	setPortrait();
	if( g_ascii_strcasecmp(szOrientation,"landscape") == 0 )
	{
		// Note: setting landscape causes the width and height to be swapped
		if (szWidth && szHeight && szUnits) // just setting a custom width or height should be allowed imo, but I'm lazy - MARCM
		{
			width = UT_convertDimensionless(szWidth);
			height = UT_convertDimensionless(szHeight);
			if(strcmp(szUnits,"cm") == 0)
				u = DIM_CM;
			else if(strcmp(szUnits,"mm") == 0)
				u = DIM_MM;
			else if(strcmp(szUnits,"inch") == 0)
				u = DIM_IN;
			setLandscape();
			Set(height,width,u);
		}
		else  
		{
			Set(m_iHeight, m_iWidth, FUND);
		}
	}
	UT_DEBUGMSG(("PageSize - Height %lf Width %lf \n",m_iHeight,m_iWidth));
	return true;
}
Пример #17
0
UT_Error IE_ImpGraphic_WMF::convertGraphicToSVG(UT_ByteBuf* pBBwmf, UT_ByteBuf** ppBB)
{
	int status = 0;

	unsigned int disp_width  = 0;
	unsigned int disp_height = 0;

	float wmf_width;
	float wmf_height;
	float ratio_wmf;
	float ratio_bounds;

	unsigned long flags;

	unsigned int max_width  = 768;
	unsigned int max_height = 512;
	unsigned long max_flags = 0;

	static const char* Default_Description = "wmf2svg";

	wmf_error_t err;

	wmf_svg_t* ddata = 0;

	wmfAPI* API = 0;
	wmfD_Rect bbox;

	wmfAPI_Options api_options;

	bbuf_read_info  read_info;

	char *stream = NULL;
	unsigned long stream_len = 0;

	*ppBB = 0;

	flags = 0;

	flags = WMF_OPT_IGNORE_NONFATAL | WMF_OPT_FUNCTION;
	api_options.function = wmf_svg_function;

	err = wmf_api_create (&API,flags,&api_options);
	status = explicit_wmf_error ("wmf_api_create",err);

	if (status)
	{	
		if (API) 
			wmf_api_destroy (API);
		return (UT_ERROR);
	}

	read_info.pByteBuf = pBBwmf;

	read_info.len = pBBwmf->getLength();
	read_info.pos = 0;

	err = wmf_bbuf_input (API,AbiWord_WMF_read,AbiWord_WMF_seek,AbiWord_WMF_tell,(void *) &read_info);
	if (err != wmf_E_None) {
		UT_DEBUGMSG(("IE_ImpGraphic_WMF::convertGraphic Bad input set\n"));
		goto ErrorHandler;
	}

	err = wmf_scan (API,0,&(bbox));
	status = explicit_wmf_error ("wmf_scan",err);

	if (status)
	{	
		goto ErrorHandler;
	}

/* Okay, got this far, everything seems cool.
 */
	ddata = WMF_SVG_GetData (API);

	ddata->out = wmf_stream_create(API, NULL);

	ddata->Description = (char *)Default_Description;

	ddata->bbox = bbox;

	wmf_display_size (API,&disp_width,&disp_height,72,72);

	wmf_width  = (float) disp_width;
	wmf_height = (float) disp_height;

	if ((wmf_width <= 0) || (wmf_height <= 0))
	{	fputs ("Bad image size - but this error shouldn't occur...\n",stderr);
		status = 1;
		wmf_api_destroy (API);
		return UT_ERROR;
	}

	if ((wmf_width  > (float) max_width )
	 || (wmf_height > (float) max_height))
	{	if (max_flags == 0) max_flags = WMF2SVG_MAXPECT;
	}

	if (max_flags == WMF2SVG_MAXPECT) /* scale the image */
	{	ratio_wmf = wmf_height / wmf_width;
		ratio_bounds = (float) max_height / (float) max_width;

		if (ratio_wmf > ratio_bounds)
		{	ddata->height = max_height;
			ddata->width  = (unsigned int) ((float) ddata->height / ratio_wmf);
		}
		else
		{	ddata->width  = max_width;
			ddata->height = (unsigned int) ((float) ddata->width  * ratio_wmf);
		}
	}
	else if (max_flags == WMF2SVG_MAXSIZE) /* bizarre option, really */
	{	ddata->width  = max_width;
		ddata->height = max_height;
	}
	else
	{	ddata->width  = (unsigned int) ceil ((double) wmf_width );
		ddata->height = (unsigned int) ceil ((double) wmf_height);
	}

	ddata->flags |= WMF_SVG_INLINE_IMAGES;

	ddata->flags |= WMF_GD_OUTPUT_MEMORY | WMF_GD_OWN_BUFFER;

	if (status == 0)
	{	err = wmf_play (API,0,&(bbox));
		status = explicit_wmf_error ("wmf_play",err);
	}

	wmf_stream_destroy(API, ddata->out, &stream, &stream_len);

	if (status == 0) 
	{
		UT_ByteBuf* pBB = new UT_ByteBuf;
		pBB->append((const UT_Byte*)stream, (UT_uint32)stream_len);
		*ppBB = pBB;
		DELETEP(pBBwmf);
		wmf_free(API, stream);
		wmf_api_destroy (API);
		return UT_OK;
	}

ErrorHandler:
	DELETEP(pBBwmf);
	if(API) 
	{
		if(stream) 
		{
			wmf_free(API, stream);
		}
		wmf_api_destroy (API);
	}
	return UT_ERROR;
}
Пример #18
0
/*!
 * This method copies the selection defined by pDocRange to ODT format
 * placed in the ByteBuf bufODT
 */
UT_Error IE_Exp_OpenDocument::copyToBuffer(PD_DocumentRange * pDocRange,UT_ByteBuf *  bufODT)
{
    //
    // First export selected range to a tempory document
    //
    PD_Document * outDoc = new PD_Document();
    outDoc->createRawDocument();
    IE_Exp_DocRangeListener * pRangeListener = new IE_Exp_DocRangeListener(pDocRange,outDoc);
    UT_DEBUGMSG(("DocumentRange low %d High %d \n",pDocRange->m_pos1,pDocRange->m_pos2));
    PL_ListenerCoupleCloser* pCloser = new PL_ListenerCoupleCloser();
    pDocRange->m_pDoc->tellListenerSubset(pRangeListener,pDocRange,pCloser);
    if( pCloser)
        delete pCloser;
    
    //
    // Grab the RDF triples while we are copying...
    //
    if( PD_DocumentRDFHandle outrdf = outDoc->getDocumentRDF() )
    {

        std::set< std::string > xmlids;
        PD_DocumentRDFHandle inrdf = pDocRange->m_pDoc->getDocumentRDF();
        inrdf->addRelevantIDsForRange( xmlids, pDocRange );

        if( !xmlids.empty() )
        {
            UT_DEBUGMSG(("MIQ: ODF export creating restricted RDF model xmlids.sz:%ld \n",(long)xmlids.size()));
            PD_RDFModelHandle subm = inrdf->createRestrictedModelForXMLIDs( xmlids );
            PD_DocumentRDFMutationHandle m = outrdf->createMutation();
            m->add( subm );
            m->commit();
            subm->dumpModel("copied rdf triples subm");
            outrdf->dumpModel("copied rdf triples result");
        }
        
        // PD_DocumentRDFMutationHandle m = outrdf->createMutation();
        // m->add( PD_URI("http://www.example.com/foo"),
        //         PD_URI("http://www.example.com/bar"),
        //         PD_Literal("copyToBuffer path") );
        // m->commit();
    }
    outDoc->finishRawCreation();
    //
    // OK now we have a complete and valid document containing our selected 
    // content. We export this to an in memory GSF buffer
    //
    IE_Exp * pNewExp = NULL; 
    char *szTempFileName = NULL;
    GError *err = NULL;
    g_file_open_tmp ("XXXXXX", &szTempFileName, &err);
    GsfOutput * outBuf =  gsf_output_stdio_new (szTempFileName,&err);
    IEFileType ftODT = IE_Exp::fileTypeForMimetype("application/vnd.oasis.opendocument.text");
    UT_Error aerr = IE_Exp::constructExporter(outDoc,outBuf,
					     ftODT,&pNewExp);
    if(pNewExp == NULL)
    {
         return aerr;
    }
    aerr = pNewExp->writeFile(szTempFileName);
    if(aerr != UT_OK)
    {
	delete pNewExp;
	delete pRangeListener;
	UNREFP( outDoc);
	g_remove(szTempFileName);
	g_free (szTempFileName);
	return aerr;
    }
    //
    // File is closed at the end of the export. Open it again.
    //

    GsfInput *  fData = gsf_input_stdio_new(szTempFileName,&err);
    UT_DebugOnly<UT_sint32> siz = gsf_input_size(fData);
    const UT_Byte * pData = gsf_input_read(fData,gsf_input_size(fData),NULL);
    UT_DEBUGMSG(("Writing %d bytes to clipboard \n", (UT_sint32)siz));
    bufODT->append( pData, gsf_input_size(fData));
    
    delete pNewExp;
    delete pRangeListener;
    UNREFP( outDoc);
    g_remove(szTempFileName);
    g_free (szTempFileName);
    return aerr;
}
Пример #19
0
PL_Listener * IE_Exp_WordPerfect::_constructListener(void)
{
	UT_DEBUGMSG(("WordPerfect Exporter: _constructListener\n"));	
	return new WordPerfect_Listener(getDoc(), this);
}
Пример #20
0
/**
 * This writes out our AbiWord file as an OpenOffice
 * compound document
 */
UT_Error IE_Exp_OpenDocument::_writeDocument(void)
{
	ODe_DocumentData docData(getDoc());
	ODe_AuxiliaryData auxData;
	ODe_AbiDocListener* pAbiDocListener = NULL;
	ODe_AbiDocListenerImpl* pAbiDocListenerImpl = NULL;
    
	UT_return_val_if_fail (getFp(), UT_ERROR);

    PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF();
    auxData.m_additionalRDF = rdf->createScratchModel();
    
	const std::string & prop = getProperty ("uncompressed");
	
	if (!prop.empty() && UT_parseBool (prop.c_str (), false))
	  {
	    m_odt = GSF_OUTFILE(g_object_ref(G_OBJECT(getFp())));
	  }
	else
	  {
	    GError* error = NULL;
	    m_odt = GSF_OUTFILE (gsf_outfile_zip_new (getFp(), &error));
	    
	    if (error)
	      {
		UT_DEBUGMSG(("Error writing odt file: %s\n", error->message));
		UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
	      }
	  }

	UT_return_val_if_fail(m_odt, UT_ERROR);

	// Needed to ensure that all *printf writes numbers correctly,
	// like "45.56mm" instead of "45,56mm".
	UT_LocaleTransactor numericLocale (LC_NUMERIC, "C");
	{
		GsfOutput * mimetype = gsf_outfile_new_child_full (m_odt, "mimetype", FALSE, "compression-level", 0, (void*)0);
		if (!mimetype)
		{
			ODe_gsf_output_close(GSF_OUTPUT(m_odt));
			return UT_ERROR;
		}

		ODe_gsf_output_write(mimetype,
				39 /*39 == strlen("application/vnd.oasis.opendocument.text")*/,
				(const guint8 *)"application/vnd.oasis.opendocument.text");

		ODe_gsf_output_close(mimetype);
    }

	if (!ODe_MetaDataWriter::writeMetaData(getDoc(), m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}

    if (!ODe_SettingsWriter::writeSettings(getDoc(), m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
	return UT_ERROR;
	}

	if (!ODe_PicturesWriter::writePictures(getDoc(), m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}


	if (!ODe_ManifestWriter::writeManifest(getDoc(), m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}


    // Gather all paragraph style names used by heading paragraphs
    // (ie. all paragraph styles that are used to build up TOCs).

    pAbiDocListenerImpl = new ODe_HeadingSearcher_Listener(docData.m_styles, auxData);
    pAbiDocListener = new ODe_AbiDocListener(getDoc(),
                                             pAbiDocListenerImpl, false);

	if (!getDoc()->tellListener(static_cast<PL_Listener *>(pAbiDocListener)))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}
    pAbiDocListener->finished();
    
    DELETEP(pAbiDocListener);
    DELETEP(pAbiDocListenerImpl);

    // Now that we have all paragraph styles that build up the TOCs in the 
    // document (if any), we can build up the TOC bodies. We do this because
    // OpenOffice.org requires the TOC bodies to be present and filled
    // when initially opening the document. Without it, it will show 
    // an empty TOC until the user regenerates it, which is not that pretty.
    // Annoyingly we have to build up the TOC ourselves during export, as
    // it doesn't exist within AbiWord's PieceTable. Until that changes, this
    // is the best we can do.

    if (auxData.m_pTOCContents) {
        pAbiDocListenerImpl = new ODe_TOC_Listener(auxData);
        pAbiDocListener = new ODe_AbiDocListener(getDoc(),
                                                 pAbiDocListenerImpl, false);

	    if (!getDoc()->tellListener(static_cast<PL_Listener *>(pAbiDocListener)))
	    {
		    ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		    return UT_ERROR;
	    }
        pAbiDocListener->finished();
        
        DELETEP(pAbiDocListener);
        DELETEP(pAbiDocListenerImpl);
    }

    
    // Gather document content and styles

    if (!docData.doPreListeningWork()) {
      ODe_gsf_output_close(GSF_OUTPUT(m_odt));
      return UT_ERROR;
    }

    pAbiDocListenerImpl = new ODe_Main_Listener(docData, auxData);
    pAbiDocListener = new ODe_AbiDocListener(getDoc(),
                                             pAbiDocListenerImpl, false);

	if (!getDoc()->tellListener(static_cast<PL_Listener *>(pAbiDocListener)))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}
	pAbiDocListener->finished();
    
	DELETEP(pAbiDocListener);
	DELETEP(pAbiDocListenerImpl);
    
	if (!docData.doPostListeningWork())
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}

    // Write RDF.
    if (!ODe_RDFWriter::writeRDF(getDoc(), m_odt, auxData.m_additionalRDF ))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}
    
    // Write content and styles
        
	if (!docData.writeStylesXML(m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}
	if (!docData.writeContentXML(m_odt))
	{
		ODe_gsf_output_close(GSF_OUTPUT(m_odt));
		return UT_ERROR;
	}

	ODe_gsf_output_close(GSF_OUTPUT(m_odt));
	return UT_OK;
}
void AP_Preview_Annotation::setActiveFrame(XAP_Frame *pFrame)
{
	UT_DEBUGMSG(("AP_Preview_Annotation: setActiveFrame\n"));
	notifyActiveFrame(pFrame);
}
Пример #22
0
bool pt_PieceTable::_createStrux(PTStruxType pts,
									PT_AttrPropIndex indexAP,
									pf_Frag_Strux ** ppfs)
{
	// create a strux frag for this.
	// return *pfs and true if successful.

	// create an unlinked strux fragment.

	pf_Frag_Strux * pfs = NULL;
	switch (pts)
	{
	case PTX_Section:
		pfs = new pf_Frag_Strux_Section(this,indexAP);
		break;

	case PTX_Block:
		pfs = new pf_Frag_Strux_Block(this,indexAP);
		break;

	case PTX_SectionHdrFtr:
		// should this be a normal section creation instead?
		pfs = new pf_Frag_Strux_SectionHdrFtr(this,indexAP);
		break;

	case PTX_SectionFootnote:
		pfs = new pf_Frag_Strux_SectionFootnote(this, indexAP);
		break;

	case PTX_SectionAnnotation:
		pfs = new pf_Frag_Strux_SectionAnnotation(this, indexAP);
		break;


	case PTX_SectionEndnote:
		pfs = new pf_Frag_Strux_SectionEndnote(this, indexAP);
		break;

	case PTX_SectionFrame:
		pfs = new pf_Frag_Strux_SectionFrame(this, indexAP);
		break;

	case PTX_SectionTable:
		pfs = new pf_Frag_Strux_SectionTable(this, indexAP);
		break;

	case PTX_EndFrame:
		pfs = new pf_Frag_Strux_SectionEndFrame(this, indexAP);
		break;
	case PTX_SectionCell:
		pfs = new pf_Frag_Strux_SectionCell(this, indexAP);
		break;
	case PTX_SectionTOC:
		pfs = new pf_Frag_Strux_SectionTOC(this, indexAP);
		break;
	case PTX_EndTable:
		pfs = new pf_Frag_Strux_SectionEndTable(this, indexAP);
		break;
	case PTX_EndCell:
		pfs = new pf_Frag_Strux_SectionEndCell(this, indexAP);
		break;
	case PTX_EndFootnote:
		pfs = new pf_Frag_Strux_SectionEndFootnote(this, indexAP);
		break;
	case PTX_EndAnnotation:
		pfs = new pf_Frag_Strux_SectionEndAnnotation(this, indexAP);
		break;
	case PTX_EndEndnote:
		pfs = new pf_Frag_Strux_SectionEndEndnote(this, indexAP);
		break;
	case PTX_EndTOC:
		pfs = new pf_Frag_Strux_SectionEndTOC(this, indexAP);
		break;

	default:
		UT_ASSERT_HARMLESS(UT_NOT_IMPLEMENTED);
		break;
	}

	if (!pfs)
	{
		UT_DEBUGMSG(("Could not create structure fragment.\n"));
		// we forget about the AP that we created
		return false;
	}

	*ppfs = pfs;
	return true;
}
Пример #23
0
void TCPAccountHandler::storeProperties()
{
	UT_DEBUGMSG(("TCPAccountHandler::storeProperties() - TODO: implement me\n"));
}
BOOL AP_Win32Dialog_MailMerge::_onCommand(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	WORD wNotifyCode = HIWORD(wParam);
	WORD wId = LOWORD(wParam);
	HWND hWndCtrl = (HWND)lParam;

	switch (wId)
	{
		case AP_RID_DIALOG_MAILMERGE_LISTBOX:
		if (HIWORD(wParam)==LBN_DBLCLK)
		{
			UT_Win32LocaleString str;
			int nItem = SendMessageW(GetDlgItem(m_hDlg, AP_RID_DIALOG_MAILMERGE_LISTBOX), LB_GETCURSEL, 0, 0);
			
			if (nItem!=LB_ERR)
			{	
				// get the mail merge field from the listbox
				HWND lBox = GetDlgItem(m_hDlg, AP_RID_DIALOG_MAILMERGE_LISTBOX);
				UT_sint32 len = SendMessageW(lBox, LB_GETTEXTLEN, nItem, (LPARAM)0);
				wchar_t* szBuff = (wchar_t*)g_malloc(sizeof(wchar_t) * (len + 1));
				SendMessageW(lBox, LB_GETTEXT, nItem, (LPARAM)szBuff);
				str.fromLocale(szBuff);
				FREEP(szBuff);

				setMergeField(str.utf8_str());			
				addClicked();
			}
			return 1;
		}
		else
		{
			return 0;
		}
		
		case AP_RID_DIALOG_MAILMERGE_BTN_INSERT:		
		{	
			UT_Win32LocaleString str;	
			int nChars = getDlgItemText(AP_RID_DIALOG_MAILMERGE_EDIT_FIELD, str);
			if (nChars > 0)
			{
				setMergeField(str.utf8_str ());
				addClicked();
			} 
			else
			{
				int nItem = SendMessageW(GetDlgItem(m_hDlg, AP_RID_DIALOG_MAILMERGE_LISTBOX), LB_GETCURSEL, 0, 0);
			
				if (nItem!=LB_ERR)
				{	
					// get the mail merge field from the listbox
					HWND lBox = GetDlgItem(m_hDlg, AP_RID_DIALOG_MAILMERGE_LISTBOX);
					UT_sint32 len = SendMessageW(lBox, LB_GETTEXTLEN, nItem, (LPARAM)0);
					wchar_t* szBuff = (wchar_t*)g_malloc(sizeof(wchar_t) * (len + 1));
					SendMessageW(lBox, LB_GETTEXT, nItem, (LPARAM)szBuff);
					str.fromLocale(szBuff);
					FREEP(szBuff);

					setMergeField(str.utf8_str());
					addClicked();
				}				 
			}

			return 1;
		}
		
		case AP_RID_DIALOG_MAILMERGE_BTN_OPEN:		
		{			
			eventOpen();
			SetFocus(m_hDlg);
			return 1;
		}	
				
		case AP_RID_DIALOG_MAILMERGE_BTN_CLOSE:		
		case IDCANCEL:		// We want to close button work
		{			
			destroy();
			return 1;
		}	
		
		default:							// we did not handle this notification
			UT_DEBUGMSG(("WM_Command for id %ld\n",wId));
			return 0;						// return zero to let windows take care of it.
	}
}
void OXMLi_ListenerState_Table::endElement (OXMLi_EndElementRequest * rqst)
{
	if (nameMatches(rqst->pName, NS_W_KEY, "tbl"))
	{
		if(m_tableStack.empty() || rqst->stck->empty())
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_SharedElement table = rqst->stck->top();
		rqst->stck->pop(); //pop table
		if(rqst->stck->empty())
		{
			OXML_SharedSection last = rqst->sect_stck->top();
			last->appendElement(table);
		}
		else
		{
			OXML_SharedElement container = rqst->stck->top();
			container->appendElement(table);
		}
		m_tableStack.pop();
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tr"))
	{
		if(m_rowStack.empty() || (rqst->stck->size() < 2))
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_SharedElement row = rqst->stck->top();
		rqst->stck->pop(); //pop row
		OXML_SharedElement table = rqst->stck->top();
		table->appendElement(row);
		m_rowStack.pop();
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tc"))
	{
		if(m_tableStack.empty() || m_cellStack.empty() || (rqst->stck->size() < 2))
		{
			rqst->handled = false;
			rqst->valid = false;
			return;
		}

		OXML_SharedElement cell = rqst->stck->top();
		rqst->stck->pop(); //pop cell
		OXML_SharedElement row = rqst->stck->top();
		OXML_Element_Cell* pCell = m_cellStack.top();
		if(!pCell->startsHorizontalMerge() && !pCell->startsVerticalMerge())
		{
			//do nothing in this case
		}
		else if(!pCell->startsVerticalMerge())
		{
			OXML_Element_Table* table = m_tableStack.top();
			if(!table->incrementBottomVerticalMergeStart(pCell))
			{
				//this means there is no cell before this starting a vertical merge
				//revert back to vertical merge start instead of continue
				pCell->setVerticalMergeStart(true);
				UT_DEBUGMSG(("FRT:OpenXML importer, invalid <vMerge val=continue> attribute.\n"));
			}
		}
		else if(!pCell->startsHorizontalMerge())
		{
			OXML_Element_Table* table = m_tableStack.top();
			if(!table->incrementRightHorizontalMergeStart(pCell))
			{
				//this means there is no cell before this starting a horizontal merge
				//revert back to horizontal merge start instead of continue
				pCell->setHorizontalMergeStart(true);
				UT_DEBUGMSG(("FRT:OpenXML importer, invalid <hMerge val=continue> attribute.\n"));
			}
		}
		else //(pCell->startsHorizontalMerge() && pCell->startsVerticalMerge())
		{
			OXML_Element_Row* pRow = m_rowStack.top();
			row->appendElement(cell);
		}
		m_cellStack.pop();
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "gridSpan") ||
			nameMatches(rqst->pName, NS_W_KEY, "vMerge") ||
			nameMatches(rqst->pName, NS_W_KEY, "hMerge") ||
			nameMatches(rqst->pName, NS_W_KEY, "gridCol") ||
			nameMatches(rqst->pName, NS_W_KEY, "trHeight") ||
			nameMatches(rqst->pName, NS_W_KEY, "left") ||
			nameMatches(rqst->pName, NS_W_KEY, "right") ||
			nameMatches(rqst->pName, NS_W_KEY, "top") ||
			nameMatches(rqst->pName, NS_W_KEY, "bottom") ||
			nameMatches(rqst->pName, NS_W_KEY, "tblStyle"))
	{
		rqst->handled = true;
	}	
	else if(nameMatches(rqst->pName, NS_W_KEY, "tblPr"))
	{
		if(!rqst->context->empty() && !contextMatches(rqst->context->back(), NS_W_KEY, "tbl") && !m_tableStack.empty())
		{
			m_tableStack.pop(); //pop the dummy table
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "trPr"))
	{
		if(!rqst->context->empty() && !contextMatches(rqst->context->back(), NS_W_KEY, "tr") && !m_rowStack.empty())
		{
			m_rowStack.pop(); //pop the dummy row
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "tcPr"))
	{
		if(!rqst->context->empty() && !contextMatches(rqst->context->back(), NS_W_KEY, "tc") && !m_cellStack.empty())
		{
			m_cellStack.pop(); //pop the dummy cell
		}
		rqst->handled = true;
	}
	else if(nameMatches(rqst->pName, NS_W_KEY, "shd"))
	{
		std::string contextTag = rqst->context->empty() ? "" : rqst->context->back();
		rqst->handled = contextMatches(contextTag, NS_W_KEY, "tcPr") || contextMatches(contextTag, NS_W_KEY, "tblPr");
	}
	//TODO: more coming here
}
UT_Error IE_Imp_PalmDoc::_parseFile(GsfInput * pdfp)
{
	UT_GrowBuf gbBlock(1024);
	bool bEatLF = false;
	bool bEmptyFile = true;
	UT_UCSChar c;
	UT_UCS4Char wc;

	pdb_header	header;
	doc_record0	rec0;
	bool		bCompressed = false;
	int		num_records, rec_num;
	DWord		file_size, offset;

	gsf_input_read( pdfp, PDB_HEADER_SIZE, (guint8*)&header);
	if (strncmp( header.type,    DOC_TYPE,    sizeof(header.type) ) ||
	    strncmp( header.creator, DOC_CREATOR, sizeof(header.creator) ))
        {
		UT_DEBUGMSG(("This is not a DOC file!\n"));

		// Create an empty paragraph.
		X_ReturnNoMemIfError(appendStrux(PTX_Block, NULL));
		return UT_OK;
	}

	num_records = _swap_Word( header.numRecords ) - 1;

	gsf_input_seek( pdfp, PDB_HEADER_SIZE, G_SEEK_SET );
	GET_DWord( pdfp, offset );
	gsf_input_seek( pdfp, offset, G_SEEK_SET );
	gsf_input_read( pdfp, sizeof(rec0), (guint8*)&rec0);

	if ( _swap_Word( rec0.version ) == 2 )
		bCompressed = true;

	gsf_input_seek( pdfp, 0, G_SEEK_END );
	file_size = gsf_input_tell( pdfp );

	for (rec_num = 1; rec_num <= num_records; ++rec_num )
	{
		DWord next_offset;

		gsf_input_seek( pdfp, PDB_HEADER_SIZE + PDB_RECORD_HEADER_SIZE * rec_num, G_SEEK_SET);
		GET_DWord( pdfp, offset );
		if( rec_num < num_records )
		{
			gsf_input_seek( pdfp, PDB_HEADER_SIZE + PDB_RECORD_HEADER_SIZE * (rec_num + 1), G_SEEK_SET);
			GET_DWord( pdfp, next_offset );
		}
		else
			next_offset = file_size;

		gsf_input_seek( pdfp, offset, G_SEEK_SET );

		// be overly cautious here
		_zero_fill (m_buf->buf, BUFFER_SIZE);
		gsf_input_read(pdfp, next_offset - offset, m_buf->buf);
		m_buf->position = next_offset - offset;

		if ( bCompressed )
			_uncompress( m_buf );

		m_buf->position = 0;

		while ( (m_buf->position) < (m_buf->len) )
		{
		  // don't copy over null chars
		        if (m_buf->buf[m_buf->position] == '\0')
			  {
			    ++m_buf->position;
			    continue;
			  }
			if( !m_Mbtowc.mbtowc( wc, m_buf->buf[m_buf->position] ) )
		 	   continue;
			c = static_cast<UT_UCSChar>(wc);
			switch (c)
			{
			case static_cast<UT_UCSChar>('\r'):
			case static_cast<UT_UCSChar>('\n'):
			
				if ((c == static_cast<UT_UCSChar>('\n')) && bEatLF)
				{
					bEatLF = false;
					break;
				}

				if (c == static_cast<UT_UCSChar>('\r'))
				{
					bEatLF = true;
				}
		
				// we interprete either CRLF, CR, or LF as a paragraph break.
		
				// start a paragraph and emit any text that we
				// have accumulated.
				X_ReturnNoMemIfError(appendStrux(PTX_Block, NULL));
				bEmptyFile = false;
				if (gbBlock.getLength() > 0)
				{
					X_ReturnNoMemIfError(appendSpan(reinterpret_cast<const UT_UCSChar*>(gbBlock.getPointer(0)), gbBlock.getLength()));
					gbBlock.truncate(0);
				}
				break;

			default:
				bEatLF = false;
				X_ReturnNoMemIfError(gbBlock.ins(gbBlock.getLength(),reinterpret_cast<const UT_GrowBufElement *>(&c),1));
				break;
			}

			++m_buf->position;
		} 

	}
	if (gbBlock.getLength() > 0 || bEmptyFile)
	{
		// if we have text left over (without final CR/LF),
		// or if we read an empty file,
		// create a paragraph and emit the text now.
		X_ReturnNoMemIfError(appendStrux(PTX_Block, NULL));
		if (gbBlock.getLength() > 0)
			X_ReturnNoMemIfError(appendSpan(reinterpret_cast<const UT_UCSChar *>(gbBlock.getPointer(0)), gbBlock.getLength()));
	}

	return UT_OK;
}
Пример #27
0
/*! 
  get the current contents of the selection in the
  window last known to have a selection using one
  of the formats in the given list.

  \param formatList the list of acceptable formats
  \param ppData
  \param pLen a pointer to an integer representing the length
  \param pszFormatFound a pointer for the data to be returned in
  \return True if successful, false otherwise.
*/
bool AP_UnixApp::getCurrentSelection(const char** formatList,
									 void ** ppData, UT_uint32 * pLen,
									 const char **pszFormatFound)
{
    int j;
	
    *ppData = NULL;				// assume failure
    *pLen = 0;
    *pszFormatFound = NULL;
	
    if (!m_pViewSelection || !m_pFrameSelection || !m_bHasSelection)
		return false;		// can't do it, give up.

    PD_DocumentRange dr;

    if (m_cacheSelectionView == m_pViewSelection)
    {
		dr = m_cacheDocumentRangeOfSelection;
    }
    else
    {
		// TODO if we ever support multiple view types, we'll have to
		// TODO change this.
		FV_View * pFVView = static_cast<FV_View *>(m_pViewSelection);
	
		pFVView->getDocumentRangeOfCurrentSelection(&dr);
    }
	
    m_selectionByteBuf.truncate(0);

    for (j=0; (formatList[j]); j++)
    {
		if ( AP_UnixClipboard::isRichTextTag(formatList[j]) )
		{
			IE_Exp_RTF * pExpRtf = new IE_Exp_RTF(dr.m_pDoc);
			if (!pExpRtf)
				return false;		// give up on memory errors

			pExpRtf->copyToBuffer(&dr,&m_selectionByteBuf);
			DELETEP(pExpRtf);
			goto ReturnThisBuffer;
		}

		if ( AP_UnixClipboard::isHTMLTag(formatList[j]) )
		{
			IE_Exp_HTML * pExpHTML = new IE_Exp_HTML(dr.m_pDoc);
			if (!pExpHTML)
				return false;

			pExpHTML->set_HTML4 (!strcmp (formatList[j], "text/html"));
			pExpHTML->copyToBuffer(&dr,&m_selectionByteBuf);
			DELETEP(pExpHTML);
			goto ReturnThisBuffer;
		}

		if ( AP_UnixClipboard::isImageTag(formatList[j]) )
		{
			// TODO: we have to make a good way to tell if the current selection is just an image
			FV_View * pView = NULL;
			if(getLastFocussedFrame())
				pView = static_cast<FV_View*>(getLastFocussedFrame()->getCurrentView());

			if (pView && !pView->isSelectionEmpty())
				{
					// don't own, don't g_free
					const UT_ByteBuf * png = 0;
	  
					pView->saveSelectedImage (&png);
					if (png && png->getLength() > 0)
						{
							m_selectionByteBuf.ins (0, png->getPointer (0), png->getLength ());
							goto ReturnThisBuffer;
						}
				}
		}
			
		if ( AP_UnixClipboard::isTextTag(formatList[j]) )
		{
			IE_Exp_Text * pExpText = new IE_Exp_Text(dr.m_pDoc, "UTF-8");
			if (!pExpText)
				return false;

			pExpText->copyToBuffer(&dr,&m_selectionByteBuf);
			DELETEP(pExpText);
			goto ReturnThisBuffer;
		}

		// TODO add other formats as necessary
    }

    UT_DEBUGMSG(("Clipboard::getCurrentSelection: cannot create anything in one of requested formats.\n"));
    return false;

 ReturnThisBuffer:
    UT_DEBUGMSG(("Clipboard::getCurrentSelection: copying %d bytes in format [%s].\n",
		 m_selectionByteBuf.getLength(),formatList[j]));
    *ppData = const_cast<void *>(static_cast<const void *>(m_selectionByteBuf.getPointer(0)));
    *pLen = m_selectionByteBuf.getLength();
    *pszFormatFound = formatList[j];
    return true;
}
Пример #28
0
UT_Error IE_Imp_EPUB::readStructure()
{
    getDoc()->createRawDocument();
    getDoc()->finishRawCreation();

    for (std::vector<std::string>::iterator i = m_spine.begin(); i
            != m_spine.end(); i++)
    {
        std::map<std::string, std::string>::iterator iter =
                m_manifestItems.find(*i);

        if (iter == m_manifestItems.end())
        {
            UT_DEBUGMSG(("Manifest item with id %s not found\n", (*i).c_str()));
            return UT_ERROR;
        }
	std::string itemPath = m_tmpDir + G_DIR_SEPARATOR_S + (iter->second);
        PT_DocPosition posEnd = 0;
        getDoc()->getBounds(true, posEnd);

        if (i != m_spine.begin())
        {
            getDoc()->insertStrux(posEnd, PTX_Section, NULL, NULL);
            getDoc()->insertStrux(posEnd+1, PTX_Block, NULL, NULL);
            posEnd+=2;
        }

        GsfInput* itemInput = UT_go_file_open(itemPath.c_str(), NULL);
        if (itemInput == NULL)
        {
            UT_DEBUGMSG(("Can`t open item for reading\n"));
            return UT_ERROR;
        }

        PD_Document *currentDoc = new PD_Document();
        currentDoc->createRawDocument();
        const char *suffix = strchr(itemPath.c_str(), '.');
        XAP_App::getApp()->getPrefs()->setIgnoreNextRecent();
        if (currentDoc->importFile(itemPath.c_str(),
                IE_Imp::fileTypeForSuffix(suffix), true, false, NULL) != UT_OK)
        {
            UT_DEBUGMSG(("Failed to import file %s\n", itemPath.c_str()));
            return UT_ERROR;
        }

        currentDoc->finishRawCreation();
        // const gchar * attributes[3] = {
        //     "listid",
        //     "0",
        //     0
        // };

        // PT_DocPosition pos;
        // currentDoc->getBounds(true, pos);
        // currentDoc->insertStrux(pos, PTX_Block, attributes, NULL, NULL);

        IE_Imp_PasteListener * pPasteListener = new IE_Imp_PasteListener(
                getDoc(), posEnd, currentDoc);
        currentDoc->tellListener(static_cast<PL_Listener *> (pPasteListener));


        DELETEP(pPasteListener);
        UNREFP(currentDoc);
        g_object_unref(G_OBJECT(itemInput));
    }

    return UT_OK;
}
Пример #29
0
/*!
* Try loading a string-set.
* \param szStringSet Language id, e.g. de_AT
* \param pDefaultStringSet String set to be used for untranslated strings.
* \return AP_DiskStringSet * on success, NULL if not found
*/
AP_DiskStringSet * 
AP_UnixApp::loadStringsFromDisk(const char 			* szStringSet, 
								AP_BuiltinStringSet * pDefaultStringSet)
{
	UT_ASSERT(pDefaultStringSet);

	const char * szDirectory = NULL;
	getPrefsValueDirectory(true,
			       static_cast<const gchar*>(AP_PREF_KEY_StringSetDirectory),
			       static_cast<const gchar**>(&szDirectory));
	UT_return_val_if_fail((szDirectory) && (*szDirectory), NULL);

	UT_String szPathVariant[4];
	char * p_strbuf = strdup("");
	char * p_modifier = NULL;
	int  cur_id = 0;
	bool three_letters = false; // some have 3!

	if (szStringSet) {
		FREEP(p_strbuf);
		p_strbuf = strdup(szStringSet);
		p_modifier = strrchr(p_strbuf,'@');
		
		char t = szStringSet[2];
		if (t && t!='-' && t!='@' && t!='_') three_letters = true;
	}

	if (p_modifier) {
		// [email protected]
		szPathVariant[cur_id] = szDirectory;
		if (szDirectory[strlen(szDirectory)-1]!='/')
			szPathVariant[cur_id] += "/";
		szPathVariant[cur_id] += p_strbuf;
		szPathVariant[cur_id] += ".strings";

		cur_id++;

		// [email protected]
		if (szStringSet && strlen(szStringSet) > 2) {
			szPathVariant[cur_id] = szDirectory;
			if (szDirectory[strlen(szDirectory)-1]!='/')
				szPathVariant[cur_id] += "/";
			szPathVariant[cur_id] += p_strbuf[0];
			szPathVariant[cur_id] += p_strbuf[1];
			if (three_letters)
				szPathVariant[cur_id] += p_strbuf[2];
			szPathVariant[cur_id] += p_modifier;
			szPathVariant[cur_id] += ".strings";
		}

		cur_id++;

		// trim modifier part
		*p_modifier = 0;
	}
	
	// fo_BA.strings
	UT_String szPath = szDirectory;
	if (szDirectory[szPath.size()-1]!='/')
		szPath += "/";
	szPath += p_strbuf;
	szPath += ".strings";

	// fo.strings
	UT_String szFallbackPath;
	if (szStringSet && strlen(szStringSet) > 2) {
		szFallbackPath = szDirectory;
		if (szDirectory[szFallbackPath.size()-1]!='/')
			szFallbackPath += "/";
		szFallbackPath += p_strbuf[0];
		szFallbackPath += p_strbuf[1];
		if (three_letters)
			szFallbackPath += p_strbuf[2];
		szFallbackPath += ".strings";
	}

	AP_DiskStringSet * pDiskStringSet = new AP_DiskStringSet(this);

	FREEP(p_strbuf);

	// trying to load specific strings first
	for (int i=0; i<cur_id; i++) {
		if (pDiskStringSet->loadStringsFromDisk(szPathVariant[i].c_str())) {
			pDiskStringSet->setFallbackStringSet(pDefaultStringSet);
			UT_DEBUGMSG(("Using [v] StringSet [%s]\n",szPathVariant[i].c_str()));
			return pDiskStringSet;
		}
	}

	// then generic ones
	if (pDiskStringSet->loadStringsFromDisk(szPath.c_str()))
	{
		pDiskStringSet->setFallbackStringSet(pDefaultStringSet);
		UT_DEBUGMSG(("Using StringSet [%s]\n",szPath.c_str()));
		return pDiskStringSet;
	}
	else if (szFallbackPath.size() && pDiskStringSet->loadStringsFromDisk(szFallbackPath.c_str())) 
	{
		pDiskStringSet->setFallbackStringSet(pDefaultStringSet);
		UT_DEBUGMSG(("Using StringSet [%s]\n",szFallbackPath.c_str()));
		return pDiskStringSet;
	}
	else
	{
		DELETEP(pDiskStringSet);
		UT_DEBUGMSG(("Unable to load StringSet [%s] -- using builtin strings instead.\n",szPath.c_str()));
		return NULL;
	}
}
Пример #30
0
/*!
 * A callback for AP_Args's doWindowlessArgs call which handles
 * platform-specific windowless args.
 * return false if we should exit normally but Window should not be displayed
 */
bool AP_Win32App::doWindowlessArgs(const AP_Args *Args, bool & bSuccess)
{
	bSuccess = true;

	AP_Win32App * pMyWin32App = static_cast<AP_Win32App*>(Args->getApp());

	if (Args->m_sGeometry)
	{
		// [--geometry <X geometry string>]
		#if 0
		gint x = 0;
		gint y = 0;
		guint width = 0;
		guint height = 0;
		
		XParseGeometry(Args->m_sGeometry, &x, &y, &width, &height);

		// set the xap-level geometry for future frame use
		Args->getApp()->setGeometry(x, y, width, height, f);
		#endif

		parseAndSetGeometry(Args->m_sGeometry);
	}
	else
	if (Args->m_sPrintTo) 
	{
		if (Args->m_sFiles[0])
		{
			UT_DEBUGMSG(("DOM: Printing file %s\n", Args->m_sFiles[0]));
			AP_Convert conv ;

			if (Args->m_sMerge)
				conv.setMergeSource (Args->m_sMerge);

			if (Args->m_impProps)
				conv.setImpProps (Args->m_impProps);
			if (Args->m_expProps)
				conv.setExpProps (Args->m_expProps);
			
			UT_String s = "AbiWord: ";
			s+= Args->m_sFiles[0];
			
            UT_Win32LocaleString prn, doc;
			prn.fromASCII (Args->m_sPrintTo);
			doc.fromASCII (s.c_str());
			GR_Graphics * pG = GR_Win32Graphics::getPrinterGraphics(prn.c_str(), doc.c_str());			
            if(!pG)
			{
				// do not assert here, if the graphics creation failed, the static
				// constructor has asserted already somewhere more relevant
				return false;
			}
			
			conv.setVerbose(Args->m_iVerbose);
			conv.print (Args->m_sFiles[0], pG, Args->m_sFileExtension);
	      
			delete pG;
		}
		else
		{
			// couldn't load document
			UT_DEBUGMSG(("Error: no file to print!\n"));
			bSuccess = false;
		}

		return false;
	}

	if(Args->m_sPluginArgs)
	{
	//
	// Start a plugin rather than the main abiword application.
	//
	    const char * szName = NULL;
		XAP_Module * pModule = NULL;
		bool bFound = false;	
		if(Args->m_sPluginArgs[0])
		{
			const char * szRequest = Args->m_sPluginArgs[0];
			const UT_GenericVector<XAP_Module*> * pVec = XAP_ModuleManager::instance().enumModules ();
			UT_DEBUGMSG((" %d plugins loaded \n",pVec->getItemCount()));
			for (UT_sint32 i = 0; (i < pVec->size()) && !bFound; i++)
			{
				pModule = pVec->getNthItem (i);
				szName = pModule->getModuleInfo()->name;
				UT_DEBUGMSG(("%s\n", szName));
				if(strcmp(szName,szRequest) == 0)
				{
					bFound = true;
				}
			}
		}
		if(!bFound)
		{
			UT_DEBUGMSG(("Plugin %s not found or loaded \n",Args->m_sPluginArgs[0]));
			bSuccess = false;
			return false;
		}

//
// You must put the name of the ev_EditMethod in the usage field
// of the plugin registered information.
//
		const char * evExecute = pModule->getModuleInfo()->usage;
		EV_EditMethodContainer* pEMC = pMyWin32App->getEditMethodContainer();
		const EV_EditMethod * pInvoke = pEMC->findEditMethodByName(evExecute);
		if(!pInvoke)
		{
			UT_DEBUGMSG(("Plugin %s invoke method %s not found \n",
				   Args->m_sPluginArgs[0],evExecute));
			bSuccess = false;
			return false;
		}
		//
		// Execute the plugin, then quit
		//
		ev_EditMethod_invoke(pInvoke, UT_String("Called From App"));
		return false;
	}

	return true;
}