-- cgit From 91d8ce3ea93f43360addbf52701a46d091e152c8 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 1 Oct 2008 18:22:22 +0000 Subject: #i92516# migrate CWS printerpullpages to svn --- vcl/aqua/inc/aquaprintview.h | 9 +- vcl/aqua/inc/salprn.h | 18 +- vcl/aqua/source/gdi/aquaprintview.mm | 10 +- vcl/aqua/source/gdi/salprn.cxx | 119 +++++----- vcl/inc/vcl/print.h | 13 +- vcl/inc/vcl/print.hxx | 92 ++++++-- vcl/inc/vcl/prndlg.hxx | 127 +++++++++-- vcl/inc/vcl/salprn.hxx | 6 +- vcl/inc/vcl/svdata.hxx | 3 +- vcl/inc/vcl/svids.hrc | 43 +++- vcl/prj/d.lst | 1 - vcl/source/app/salvtables.cxx | 2 +- vcl/source/app/svdata.cxx | 11 +- vcl/source/gdi/impprn.cxx | 4 +- vcl/source/gdi/makefile.mk | 4 +- vcl/source/gdi/print.cxx | 4 +- vcl/source/gdi/print3.cxx | 408 +++++++++++++++++++++++++++++++++++ vcl/source/src/makefile.mk | 5 +- vcl/source/src/print.src | 247 +++++++++++++++++++++ vcl/source/src/stdtext.src | 7 +- vcl/source/window/makefile.mk | 3 +- vcl/source/window/printdlg.cxx | 405 ++++++++++++++++++++++++++++++++++ 22 files changed, 1413 insertions(+), 128 deletions(-) create mode 100644 vcl/source/gdi/print3.cxx create mode 100644 vcl/source/src/print.src create mode 100644 vcl/source/window/printdlg.cxx diff --git a/vcl/aqua/inc/aquaprintview.h b/vcl/aqua/inc/aquaprintview.h index c5ce20c17425..f879936d1435 100755 --- a/vcl/aqua/inc/aquaprintview.h +++ b/vcl/aqua/inc/aquaprintview.h @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: aquaprintview.h,v $ - * $Revision: 1.3 $ + * $Revision: 1.3.114.1 $ * * This file is part of OpenOffice.org. * @@ -37,13 +37,14 @@ class ImplQPrinter; class AquaSalInfoPrinter; +namespace vcl { class PrinterListener; } @interface AquaPrintView : NSView { - ImplQPrinter* mpQPrinter; - AquaSalInfoPrinter* mpInfoPrinter; + vcl::PrinterListener* mpListener; + AquaSalInfoPrinter* mpInfoPrinter; } --(id)initWithQPrinter: (ImplQPrinter*)pPrinter withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter; +-(id)initWithListener: (vcl::PrinterListener*)pListener withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter; -(MacOSBOOL)knowsPageRange: (NSRangePointer)range; -(NSRect)rectForPage: (int)page; -(NSPoint)locationOfPrintRect: (NSRect)aRect; diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index ec08261e8321..8bfa8ac98cae 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salprn.h,v $ - * $Revision: 1.12 $ + * $Revision: 1.12.56.1 $ * * This file is part of OpenOffice.org. * @@ -104,10 +104,10 @@ class AquaSalInfoPrinter : public SalInfoPrinter // so let's make AquaSalPrinter just a forwarder to AquaSalInfoPrinter // and concentrate the real work in one class // implement pull model print system - BOOL StartJob( const String* pFileName, - const String& rAppName, - ImplJobSetup* pSetupData, - ImplQPrinter* pQPrinter, + BOOL StartJob( const String* i_pFileName, + const String& i_rAppName, + ImplJobSetup* i_pSetupData, + vcl::PrinterListener& i_rListener, bool bIsQuickJob ); BOOL EndJob(); BOOL AbortJob(); @@ -142,10 +142,10 @@ class AquaSalPrinter : public SalPrinter ULONG i_nCopies, BOOL i_bCollate, ImplJobSetup* i_pSetupData ); // implement pull model print system - virtual BOOL StartJob( const String* pFileName, - const String& rAppName, - ImplJobSetup* pSetupData, - ImplQPrinter* pQPrinter ); + virtual BOOL StartJob( const String* i_pFileName, + const String& i_rAppName, + ImplJobSetup* i_pSetupData, + vcl::PrinterListener& i_rListener ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/aqua/source/gdi/aquaprintview.mm b/vcl/aqua/source/gdi/aquaprintview.mm index 6099fbaed741..79efb9c80941 100755 --- a/vcl/aqua/source/gdi/aquaprintview.mm +++ b/vcl/aqua/source/gdi/aquaprintview.mm @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: aquaprintview.mm,v $ - * $Revision: 1.5 $ + * $Revision: 1.5.56.1 $ * * This file is part of OpenOffice.org. * @@ -33,15 +33,15 @@ #include "aquaprintview.h" #include "salprn.h" -#include "vcl/impprn.hxx" +#include "vcl/print.hxx" @implementation AquaPrintView --(id)initWithQPrinter: (ImplQPrinter*)pPrinter withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter +-(id)initWithListener: (vcl::PrinterListener*)pListener withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter { NSRect aRect = { { 0, 0 }, [pInfoPrinter->getPrintInfo() paperSize] }; if( (self = [super initWithFrame: aRect]) != nil ) { - mpQPrinter = pPrinter; + mpListener = pListener; mpInfoPrinter = pInfoPrinter; } return self; @@ -76,6 +76,6 @@ int nPage = (int)(aPaperSize.width * rect.origin.y + rect.origin.x); // page count is 1 based - mpQPrinter->PrintPage( nPage-1 + mpInfoPrinter->getCurPageRangeStart() ); + mpListener->printFilteredPage( nPage-1 ); } @end diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 0bbc190de546..09227c549874 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salprn.cxx,v $ - * $Revision: 1.16 $ + * $Revision: 1.16.56.2 $ * * This file is part of OpenOffice.org. * @@ -125,8 +125,8 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const if( mePageOrientation == ORIENTATION_PORTRAIT ) { double dX = 0, dY = aPaperSize.height; - dX += [mpPrintInfo leftMargin]; - dY -= [mpPrintInfo topMargin]; + // dX += [mpPrintInfo leftMargin]; + // dY -= [mpPrintInfo topMargin]; CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetX, dY - mnStartPageOffsetY ); CGContextScaleCTM( i_rContext, 0.1, -0.1 ); } @@ -134,8 +134,8 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const { CGContextRotateCTM( i_rContext, M_PI/2 ); double dX = aPaperSize.height, dY = -aPaperSize.width; - dY += [mpPrintInfo topMargin]; - dX -= [mpPrintInfo rightMargin]; + // dY += [mpPrintInfo topMargin]; + // dX -= [mpPrintInfo rightMargin]; CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetY, dY - mnStartPageOffsetX ); CGContextScaleCTM( i_rContext, -0.1, 0.1 ); @@ -447,77 +447,68 @@ void AquaSalInfoPrinter::GetPageInfo( const ImplJobSetup*, } } -BOOL AquaSalInfoPrinter::StartJob( const String* pFileName, - const String& rAppName, - ImplJobSetup* pSetupData, - ImplQPrinter* pQPrinter, +BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, + const String& i_rAppName, + ImplJobSetup* i_pSetupData, + vcl::PrinterListener& i_rListener, bool bIsQuickJob ) { if( mbJob ) return FALSE; BOOL bSuccess = FALSE; - std::vector aPaperRanges; - if( ! pQPrinter->GetPaperRanges( aPaperRanges, true ) ) - return FALSE; - size_t nRanges = aPaperRanges.size(); + // FIXME: make paper ranges work again + mnCurPageRangeStart = 1; + mnCurPageRangeCount = i_rListener.getPageCount(); + AquaSalInstance* pInst = GetSalData()->mpFirstInstance; - for( ULONG nCurRange = 0; nCurRange < nRanges-1; nCurRange++ ) - { - mnStartPageOffsetX = mnStartPageOffsetY = 0; + mnStartPageOffsetX = mnStartPageOffsetY = 0; - // update job data - ImplJobSetup* pSetup = pQPrinter->GetPageSetup( aPaperRanges[ nCurRange ] ); - if( pSetup ) - SetData( ~0, pSetup ); - DBG_ASSERT( pSetup, "no job setup for range" ); + // update job data + if( i_pSetupData ) + SetData( ~0, i_pSetupData ); - mnCurPageRangeStart = aPaperRanges[nCurRange]; - mnCurPageRangeCount = aPaperRanges[nCurRange+1] - aPaperRanges[nCurRange]; - // create view - NSView* pPrintView = [[AquaPrintView alloc] initWithQPrinter: pQPrinter withInfoPrinter: this]; + // create view + NSView* pPrintView = [[AquaPrintView alloc] initWithListener: &i_rListener withInfoPrinter: this]; - NSMutableDictionary* pPrintDict = [mpPrintInfo dictionary]; + NSMutableDictionary* pPrintDict = [mpPrintInfo dictionary]; - // set filename - if( pFileName ) - { - [mpPrintInfo setJobDisposition: NSPrintSaveJob]; - NSString* pPath = CreateNSString( *pFileName ); - [pPrintDict setObject: pPath forKey: NSPrintSavePath]; - [pPath release]; - - // in this case we can only deliver the print job in one file - mnCurPageRangeStart = 0; - mnCurPageRangeCount = aPaperRanges.back(); - nCurRange = nRanges; - } + // set filename + if( i_pFileName ) + { + [mpPrintInfo setJobDisposition: NSPrintSaveJob]; + NSString* pPath = CreateNSString( *i_pFileName ); + [pPrintDict setObject: pPath forKey: NSPrintSavePath]; + [pPath release]; + } - [pPrintDict setObject: [[NSNumber numberWithInt: (int)pQPrinter->GetCopyCount()] autorelease] forKey: NSPrintCopies]; - [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; - [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; - [pPrintDict setObject: [[NSNumber numberWithInt: (int)mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; + // FIXME copies + // [pPrintDict setObject: [[NSNumber numberWithInt: (int)pQPrinter->GetCopyCount()] autorelease] forKey: NSPrintCopies]; + [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; + [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; + [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; - // create print operation - NSPrintOperation* pPrintOperation = [NSPrintOperation printOperationWithView: pPrintView printInfo: mpPrintInfo]; + // create print operation + NSPrintOperation* pPrintOperation = [NSPrintOperation printOperationWithView: pPrintView printInfo: mpPrintInfo]; - if( pPrintOperation ) - { - bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); - [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; - // [pPrintOperation setShowsProgressPanel: NO]; - bSuccess = TRUE; - mbJob = true; - pInst->startedPrintJob(); - [pPrintOperation runOperation]; - pInst->endedPrintJob(); - mbJob = false; - } + if( pPrintOperation ) + { + bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); + [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; + [pPrintOperation setShowsProgressPanel: bShowPanel ? YES : NO]; + bSuccess = TRUE; + mbJob = true; + pInst->startedPrintJob(); + [pPrintOperation runOperation]; + pInst->endedPrintJob(); + mbJob = false; } + mnCurPageRangeStart = mnCurPageRangeCount = 0; + return bSuccess; } @@ -583,22 +574,22 @@ AquaSalPrinter::~AquaSalPrinter() // ----------------------------------------------------------------------- -BOOL AquaSalPrinter::StartJob( const String* pFileName, - const String& rAppName, - ImplJobSetup* pSetupData, - ImplQPrinter* pQPrinter ) +BOOL AquaSalPrinter::StartJob( const String* i_pFileName, + const String& i_rAppName, + ImplJobSetup* i_pSetupData, + vcl::PrinterListener& i_rListener ) { bool bIsQuickJob = false; std::hash_map< rtl::OUString, rtl::OUString, rtl::OUStringHash >::const_iterator quick_it = - pSetupData->maValueMap.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ); + i_pSetupData->maValueMap.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ); - if( quick_it != pSetupData->maValueMap.end() ) + if( quick_it != i_pSetupData->maValueMap.end() ) { if( quick_it->second.equalsIgnoreAsciiCaseAscii( "true" ) ) bIsQuickJob = true; } - return mpInfoPrinter->StartJob( pFileName, rAppName, pSetupData, pQPrinter, bIsQuickJob ); + return mpInfoPrinter->StartJob( i_pFileName, i_rAppName, i_pSetupData, i_rListener, bIsQuickJob ); } // ----------------------------------------------------------------------- diff --git a/vcl/inc/vcl/print.h b/vcl/inc/vcl/print.h index 51cbb5dee0cf..bc74b6441f28 100644 --- a/vcl/inc/vcl/print.h +++ b/vcl/inc/vcl/print.h @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: print.h,v $ - * $Revision: 1.4 $ + * $Revision: 1.4.114.2 $ * * This file is part of OpenOffice.org. * @@ -31,15 +31,18 @@ #ifndef _SV_PRINT_H #define _SV_PRINT_H -#include -#include -#include +#include "vcl/sv.h" +#include "vcl/dllapi.h" #include #include struct SalPrinterQueueInfo; class QueueInfo; +class JobSetup; + +namespace vcl +{ class PrinterListener; } // ------------------------ // - private printer data - @@ -87,5 +90,7 @@ public: // -------------- void ImplDeletePrnQueueList(); +void SAL_DLLPRIVATE ImplUpdateJobSetupPaper( JobSetup& rJobSetup ); + #endif // _SV_PRINT_H diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index c6a4a6c1adf9..e6199437ca4a 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: print.hxx,v $ - * $Revision: 1.6 $ + * $Revision: 1.6.114.5 $ * * This file is part of OpenOffice.org. * @@ -31,14 +31,19 @@ #ifndef _SV_PRINT_HXX #define _SV_PRINT_HXX -#include -#include -#include -#include -#include -#include -#include -#include +#include "tools/errcode.hxx" +#include "vcl/sv.h" +#include "vcl/dllapi.h" +#include "vcl/outdev.hxx" +#include "vcl/prntypes.hxx" +#include "vcl/jobset.hxx" +#include "vcl/gdimtf.hxx" +#include "tools/stream.hxx" +#include "tools/multisel.hxx" + +#include "com/sun/star/beans/XPropertySet.hpp" + +#include struct SalPrinterInfoQueue; class SalInfoPrinter; @@ -47,12 +52,12 @@ class SalPrinter; class VirtualDevice; class Window; class ImplQPrinter; -class RmPrinter; struct ImplPrivatePrinterData; -namespace com { namespace sun { namespace star { namespace uno { - class Any; -} } } } +namespace vcl { + class PrinterListener; + class PrintDialog; +} // ----------------- // - Printer-Types - @@ -264,6 +269,11 @@ private: SAL_DLLPRIVATE void ImplUpdateFontList(); SAL_DLLPRIVATE void ImplFindPaperFormatForUserSize( JobSetup& ); DECL_DLLPRIVATE_LINK( ImplDestroyPrinterAsync, void* ); + + SAL_DLLPRIVATE bool StartJob( const XubString& rJobName, boost::shared_ptr& ); + + static SAL_DLLPRIVATE ULONG ImplSalPrinterErrorCodeToVCL( ULONG nError ); + public: SAL_DLLPRIVATE void ImplEndPrint(); SAL_DLLPRIVATE void ImplUpdateQuickStatus(); @@ -421,6 +431,62 @@ public: * if the printer list changed */ static void updatePrinters(); + + /** execute a print job + + starts a print job asynchronously (that is will return + + */ + static void PrintJob( const boost::shared_ptr& i_pListener, + const JobSetup& i_rInitSetup, + const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& i_xJobOptions + ); + + // implementation detail of PrintJob being asynchronous + // not exported, not usable outside vcl + static void SAL_DLLPRIVATE ImplPrintJob( const boost::shared_ptr& i_pListener, + const JobSetup& i_rInitSetup, + const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& i_xJobOptions + ); +}; + +namespace vcl +{ +class ImplPrinterListenerData; + +class VCL_DLLPUBLIC PrinterListener +{ + ImplPrinterListenerData* mpImplData; +public: + PrinterListener(); + virtual ~PrinterListener(); + + const boost::shared_ptr& getPrinter() const; + const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& getJobParameters() const; + const MultiSelection& getPageSelection() const; + + virtual int getPageCount() const = 0; // must be overloaded by the app + /* get the page parameters, namely the jobsetup that should be active for the page + (describing among others the physical page size) and the "page size". In writer + case this would probably be the same as the JobSetup since writer sets the page size + draw/impress for example print their page on the paper set on the printer, + possibly adjusting the page size to fit. That means the page size can be different from + the paper size. + */ + virtual void getPageParameters( int i_nPage, JobSetup& o_rPageSetup, Size& o_rPageSize ) const = 0; // must be overloaded by the app, return page size in 1/100th mm + virtual void printPage( int i_nPage ) const = 0; // must be overloaded by the app + virtual void setListeners(); // optionally set listeners on mxJobParameters + virtual void jobFinished(); // optionally release resources bound to the job + + void printFilteredPage( int i_nPage ); + + // implementation details, not usable outsid vcl + void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); + void SAL_DLLPRIVATE setJobParameters( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& ); + void SAL_DLLPRIVATE setPageSelection( const MultiSelection& ); }; +} + + #endif // _SV_PRINT_HXX diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 4fd6eaa999da..f5b4a35e0331 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prndlg.hxx,v $ - * $Revision: 1.3 $ + * $Revision: 1.3.114.5 $ * * This file is part of OpenOffice.org. * @@ -33,19 +33,122 @@ #include -#include +#include "vcl/print.hxx" +#include "vcl/print.h" -class Printer; +#include "vcl/dialog.hxx" +#include "vcl/fixed.hxx" +#include "vcl/button.hxx" +#include "vcl/scrbar.hxx" +#include "vcl/gdimtf.hxx" +#include "vcl/lstbox.hxx" +#include "vcl/field.hxx" +#include "vcl/tabctrl.hxx" +#include "vcl/tabpage.hxx" -class VCL_DLLPUBLIC SystemDialog : public ModalDialog +#include "tools/multisel.hxx" + +#include + + +namespace vcl { -public: - SystemDialog( Window* pParent, WinBits nWinStyle ) : - ModalDialog( pParent, nWinStyle ) {} - SystemDialog( Window* pParent, const ResId& rResId ) : - ModalDialog( pParent, rResId ) {} - - virtual short Execute() { return 0; } -}; + class PrintDialog : public ModalDialog + { + class PrintPreviewWindow : public Window + { + GDIMetaFile maMtf; + public: + PrintPreviewWindow( Window* pParent, const ResId& ); + virtual ~PrintPreviewWindow(); + + virtual void Paint( const Rectangle& rRect ); + + void setPreview( const GDIMetaFile& ); + }; + + class PrinterTabPage : public TabPage + { + public: + ListBox maPrinters; + PushButton maSetupButton; + FixedText maType; + FixedText maTypeText; + FixedText maStatus; + FixedText maStatusText; + FixedText maLocation; + FixedText maLocText; + FixedText maComment; + FixedText maCommentText; + CheckBox maToFileBox; + + PrinterTabPage( Window*, const ResId& ); + virtual ~PrinterTabPage(); + }; + + class JobTabPage : public TabPage + { + public: + FixedLine maPrintRange; + RadioButton maAllButton; + RadioButton maPagesButton; + RadioButton maSelectionButton; + Edit maPagesEdit; + + FixedLine maCopies; + FixedText maCopyCount; + NumericField maCopyCountField; + CheckBox maCollateBox; + FixedImage maCollateImage; + + Image maCollateImg; + Image maCollateHCImg; + Image maNoCollateImg; + Image maNoCollateHCImg; + + JobTabPage( Window*, const ResId& ); + virtual ~JobTabPage(); + }; + + OKButton maOKButton; + CancelButton maCancelButton; + PrintPreviewWindow maPreviewWindow; + FixedText maPageText; + ScrollBar maPageScrollbar; + + TabControl maTabCtrl; + PrinterTabPage maPrinterPage; + JobTabPage maJobPage; + + FixedLine maButtonLine; + + boost::shared_ptr< PrinterListener > maPListener; + + rtl::OUString maPageStr; + sal_Int32 mnCurPage; + sal_Int32 mnCachedPages; + Rectangle maPreviewSpace; + + void preparePreview(); + void setPreviewText( sal_Int32 ); + void updatePrinterText(); + void checkControlDependencies(); + + DECL_LINK( ScrollHdl, ScrollBar* ); + DECL_LINK( ScrollEndHdl, ScrollBar* ); + DECL_LINK( SelectHdl, ListBox* ); + DECL_LINK( ClickHdl, Button* ); + DECL_LINK( ModifyHdl, Edit* ); + public: + PrintDialog( Window*, const boost::shared_ptr< PrinterListener >& ); + virtual ~PrintDialog(); + + bool isPrintToFile(); + MultiSelection getPageSelection(); + int getCopyCount(); + bool isCollate(); + }; +} + #endif // _SV_PRNDLG_HXX diff --git a/vcl/inc/vcl/salprn.hxx b/vcl/inc/vcl/salprn.hxx index a80c5873cbfb..d76040f8cb8b 100644 --- a/vcl/inc/vcl/salprn.hxx +++ b/vcl/inc/vcl/salprn.hxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salprn.hxx,v $ - * $Revision: 1.5 $ + * $Revision: 1.5.114.1 $ * * This file is part of OpenOffice.org. * @@ -41,7 +41,7 @@ class SalGraphics; class SalFrame; struct ImplJobSetup; -class ImplQPrinter; +namespace vcl { class PrinterListener; } // ----------------------- // - SalPrinterQueueInfo - @@ -125,7 +125,7 @@ public: // public for Sal Implementation virtual BOOL StartJob( const String* pFileName, const String& rAppName, ImplJobSetup* pSetupData, - ImplQPrinter* pQPrinter ); + vcl::PrinterListener& rListener ); virtual BOOL EndJob() = 0; virtual BOOL AbortJob() = 0; diff --git a/vcl/inc/vcl/svdata.hxx b/vcl/inc/vcl/svdata.hxx index 536f629bfa9e..e252cb5793f1 100644 --- a/vcl/inc/vcl/svdata.hxx +++ b/vcl/inc/vcl/svdata.hxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svdata.hxx,v $ - * $Revision: 1.13 $ + * $Revision: 1.13.16.1 $ * * This file is part of OpenOffice.org. * @@ -352,6 +352,7 @@ void ImplDeInitSVData(); void ImplDestroySVData(); Window* ImplGetDefaultWindow(); VCL_DLLPUBLIC ResMgr* ImplGetResMgr(); +VCL_DLLPUBLIC ResId VclResId( sal_Int32 nId ); // throws std::bad_alloc if no res mgr DockingManager* ImplGetDockingManager(); void ImplWindowAutoMnemonic( Window* pWindow ); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 47654c33bfd5..93a8b5cf3d46 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svids.hrc,v $ - * $Revision: 1.8 $ + * $Revision: 1.8.84.3 $ * * This file is part of OpenOffice.org. * @@ -73,6 +73,44 @@ #define SV_MENU_MAC_SHOWALL 2005 #define SV_MENU_MAC_QUITAPP 2006 +#define SV_DLG_PRINT 2048 +#define SV_PRINT_OK 1 +#define SV_PRINT_CANCEL 2 +#define SV_PRINT_PAGE_TXT 3 +#define SV_PRINT_PAGE_PREVIEW 4 +#define SV_PRINT_PAGE_SCROLL 5 +#define SV_PRINT_TABCTRL 6 + +#define SV_PRINT_TAB_PRINTER 1 +#define SV_PRINT_PRINTERS 1 +#define SV_PRINT_PRT_TYPE 2 +#define SV_PRINT_PRT_TYPE_TXT 3 +#define SV_PRINT_PRT_STATUS 4 +#define SV_PRINT_PRT_STATUS_TXT 5 +#define SV_PRINT_PRT_LOCATION 6 +#define SV_PRINT_PRT_LOCATION_TXT 7 +#define SV_PRINT_PRT_COMMENT 8 +#define SV_PRINT_PRT_COMMENT_TXT 9 +#define SV_PRINT_PRT_TOFILE 10 +#define SV_PRINT_PRT_SETUP 11 + +#define SV_PRINT_TAB_JOB 2 +#define SV_PRINT_RANGE 1 +#define SV_PRINT_ALL 2 +#define SV_PRINT_PAGERANGE 3 +#define SV_PRINT_SELECTION 4 +#define SV_PRINT_PAGERANGE_EDIT 5 +#define SV_PRINT_COPIES 6 +#define SV_PRINT_COPYCOUNT 7 +#define SV_PRINT_COPYCOUNT_FIELD 8 +#define SV_PRINT_COLLATE 9 +#define SV_PRINT_COLLATE_IMAGE 10 +#define SV_PRINT_BUTTONLINE 11 +#define SV_PRINT_COLLATE_IMG 12 +#define SV_PRINT_NOCOLLATE_IMG 13 +#define SV_PRINT_COLLATE_HC_IMG 14 +#define SV_PRINT_NOCOLLATE_HC_IMG 15 + #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 #define SV_HELPTEXT_MAXIMIZE 10002 @@ -107,7 +145,8 @@ #define SV_STDTEXT_ABOUT 10204 #define SV_STDTEXT_PREFERENCES 10205 #define SV_MAC_SCREENNNAME 10206 -#define SV_STDTEXT_LAST SV_MAC_SCREENNNAME +#define SV_STDTEXT_ALLFILETYPES 10207 +#define SV_STDTEXT_LAST SV_STDTEXT_ALLFILETYPES #define SV_ACCESSERROR_FIRST SV_ACCESSERROR_WRONG_VERSION #define SV_ACCESSERROR_WRONG_VERSION 10500 diff --git a/vcl/prj/d.lst b/vcl/prj/d.lst index 919fdc5f944e..39d3e8aa9c02 100644 --- a/vcl/prj/d.lst +++ b/vcl/prj/d.lst @@ -87,7 +87,6 @@ mkdir: %_DEST%\inc%_EXT%\vcl\plug\vcl ..\inc\vcl\outdev3d.hxx %_DEST%\inc%_EXT%\vcl\outdev3d.hxx ..\inc\vcl\pointr.hxx %_DEST%\inc%_EXT%\vcl\pointr.hxx ..\inc\vcl\print.hxx %_DEST%\inc%_EXT%\vcl\print.hxx -..\inc\vcl\prndlg.hxx %_DEST%\inc%_EXT%\vcl\prndlg.hxx ..\inc\vcl\prntypes.hxx %_DEST%\inc%_EXT%\vcl\prntypes.hxx ..\inc\vcl\ptrstyle.hxx %_DEST%\inc%_EXT%\vcl\ptrstyle.hxx ..\inc\vcl\regband.hxx %_DEST%\inc%_EXT%\vcl\regband.hxx diff --git a/vcl/source/app/salvtables.cxx b/vcl/source/app/salvtables.cxx index 69868ed38e55..cd169fc81fe7 100644 --- a/vcl/source/app/salvtables.cxx +++ b/vcl/source/app/salvtables.cxx @@ -91,7 +91,7 @@ SalPrinter::~SalPrinter() } BOOL SalPrinter::StartJob( const String*, const String&, - ImplJobSetup*, ImplQPrinter* ) + ImplJobSetup*, vcl::PrinterListener& ) { return FALSE; } diff --git a/vcl/source/app/svdata.cxx b/vcl/source/app/svdata.cxx index edfd6a24bff9..56ba933e3931 100644 --- a/vcl/source/app/svdata.cxx +++ b/vcl/source/app/svdata.cxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svdata.cxx,v $ - * $Revision: 1.56 $ + * $Revision: 1.56.114.1 $ * * This file is part of OpenOffice.org. * @@ -220,6 +220,15 @@ ResMgr* ImplGetResMgr() return pSVData->mpResMgr; } +ResId VclResId( sal_Int32 nId ) +{ + ResMgr* pMgr = ImplGetResMgr(); + if( ! pMgr ) + throw std::bad_alloc(); + + return ResId( nId, *pMgr ); +} + DockingManager* ImplGetDockingManager() { ImplSVData* pSVData = ImplGetSVData(); diff --git a/vcl/source/gdi/impprn.cxx b/vcl/source/gdi/impprn.cxx index 5da5f951f203..a40357f003dc 100644 --- a/vcl/source/gdi/impprn.cxx +++ b/vcl/source/gdi/impprn.cxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impprn.cxx,v $ - * $Revision: 1.19 $ + * $Revision: 1.19.54.1 $ * * This file is part of OpenOffice.org. * @@ -464,10 +464,12 @@ void ImplQPrinter::EndQueuePrint() DBG_ASSERT( mpPrinter, "no SalPrinter in ImplQPrinter" ); if( mpPrinter ) { + #if 0 mpPrinter->StartJob( mbPrintFile ? &maPrintFile : NULL, Application::GetDisplayName(), maJobSetup.ImplGetConstData(), this ); + #endif EndJob(); mpParent->ImplEndPrint(); } diff --git a/vcl/source/gdi/makefile.mk b/vcl/source/gdi/makefile.mk index 7d68fbe40d3f..6a856df59d02 100644 --- a/vcl/source/gdi/makefile.mk +++ b/vcl/source/gdi/makefile.mk @@ -8,7 +8,7 @@ # # $RCSfile: makefile.mk,v $ # -# $Revision: 1.33 $ +# $Revision: 1.33.92.1 $ # # This file is part of OpenOffice.org. # @@ -96,6 +96,7 @@ SLOFILES= $(SLO)$/salmisc.obj \ $(SLO)$/fontcvt.obj \ $(SLO)$/print.obj \ $(SLO)$/print2.obj \ + $(SLO)$/print3.obj \ $(SLO)$/regband.obj \ $(SLO)$/region.obj \ $(SLO)$/wall.obj \ @@ -121,6 +122,7 @@ EXCEPTIONSFILES= $(SLO)$/salmisc.obj \ $(SLO)$/gfxlink.obj \ $(SLO)$/print.obj \ $(SLO)$/print2.obj \ + $(SLO)$/print3.obj \ $(SLO)$/sallayout.obj \ $(SLO)$/image.obj \ $(SLO)$/impimage.obj \ diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index 11bed4b7ae67..45f6a5c7d0c2 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: print.cxx,v $ - * $Revision: 1.65 $ + * $Revision: 1.65.114.1 $ * * This file is part of OpenOffice.org. * @@ -1309,7 +1309,7 @@ void Printer::PrintPage() // ----------------------------------------------------------------------- -ULONG ImplSalPrinterErrorCodeToVCL( ULONG nError ) +ULONG Printer::ImplSalPrinterErrorCodeToVCL( ULONG nError ) { ULONG nVCLError; switch ( nError ) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx new file mode 100644 index 000000000000..e92d5c250112 --- /dev/null +++ b/vcl/source/gdi/print3.cxx @@ -0,0 +1,408 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: print3.cxx,v $ + * $Revision: 1.1.2.11 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "precompiled_vcl.hxx" + +#include "vcl/print.hxx" +#include "vcl/prndlg.hxx" +#include "vcl/svapp.hxx" +#include "vcl/svdata.hxx" +#include "vcl/salinst.hxx" +#include "vcl/salprn.hxx" +#include "vcl/svids.hrc" + +#include "tools/urlobj.hxx" +#include "tools/multisel.hxx" + +#include "com/sun/star/ui/dialogs/XFilePicker.hpp" +#include "com/sun/star/ui/dialogs/XFilterManager.hpp" +#include "com/sun/star/ui/dialogs/TemplateDescription.hpp" +#include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp" +#include "com/sun/star/lang/XMultiServiceFactory.hpp" +#include "comphelper/processfactory.hxx" + +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace vcl; + +class vcl::ImplPrinterListenerData +{ +public: + boost::shared_ptr mpPrinter; + com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet > mxJobParameters; + MultiSelection maSelection; +}; + +PrinterListener::PrinterListener() + : mpImplData( new ImplPrinterListenerData ) +{ +} + +static rtl::OUString queryFile( Printer* pPrinter ) +{ + rtl::OUString aResult; + + uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); + if( xFactory.is() ) + { + uno::Sequence< uno::Any > aTempl( 1 ); + aTempl.getArray()[0] <<= ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION; + uno::Reference< ui::dialogs::XFilePicker > xFilePicker( + xFactory->createInstanceWithArguments( + ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.dialogs.FilePicker" ) ), + aTempl ), uno::UNO_QUERY ); + DBG_ASSERT( xFilePicker.is(), "could not get FilePicker service" ); + + uno::Reference< ui::dialogs::XFilterManager > xFilterMgr( xFilePicker, uno::UNO_QUERY ); + if( xFilePicker.is() && xFilterMgr.is() ) + { + try + { +#ifdef UNX + // add PostScript and PDF + bool bPS = true, bPDF = true; + if( pPrinter ) + { + if( pPrinter->GetCapabilities( PRINTER_CAPABILITIES_PDF ) ) + bPS = false; + else + bPDF = false; + } + if( bPS ) + xFilterMgr->appendFilter( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PostScript" ) ), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*.ps" ) ) ); + if( bPDF ) + xFilterMgr->appendFilter( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Portable Document Format" ) ), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*.pdf" ) ) ); +#elif defined WNT + (void)pPrinter; + xFilterMgr->appendFilter( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*.PRN" ) ), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*.prn" ) ) ); +#endif + // add arbitrary files + xFilterMgr->appendFilter( String( VclResId( SV_STDTEXT_ALLFILETYPES ) ), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) ); + } + catch( lang::IllegalArgumentException rExc ) + { + DBG_ERRORFILE( "caught IllegalArgumentException when registering filter\n" ); + } + + if( xFilePicker->execute() == ui::dialogs::ExecutableDialogResults::OK ) + { + uno::Sequence< ::rtl::OUString > aPathSeq( xFilePicker->getFiles() ); + INetURLObject aObj( aPathSeq[0] ); + aResult = aObj.PathToFileName(); + } + } + } + return aResult; +} + +struct PrintJobAsync +{ + boost::shared_ptr mpListener; + JobSetup maInitSetup; + Reference< beans::XPropertySet > mxJobOptions; + + PrintJobAsync( const boost::shared_ptr& i_pListener, + const JobSetup& i_rInitSetup, + const Reference< beans::XPropertySet >& i_xJobOptions + ) + : mpListener( i_pListener ), maInitSetup( i_rInitSetup ), mxJobOptions( i_xJobOptions ) + {} + + DECL_LINK( ExecJob, void* ); +}; + +IMPL_LINK( PrintJobAsync, ExecJob, void*, EMPTYARG ) +{ + Printer::ImplPrintJob( mpListener, maInitSetup, mxJobOptions ); + + // clean up, do not access members after this + delete this; + + return 0; +} + +void Printer::PrintJob( const boost::shared_ptr& i_pListener, + const JobSetup& i_rInitSetup, + const Reference< beans::XPropertySet >& i_xJobOptions + ) +{ + PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup, i_xJobOptions ); + Application::PostUserEvent( LINK( pAsync, PrintJobAsync, ExecJob ) ); +} + +void Printer::ImplPrintJob( const boost::shared_ptr& i_pListener, + const JobSetup& i_rInitSetup, + const Reference< beans::XPropertySet >& /*i_xJobOptions*/ + ) +{ + // setup printer + boost::shared_ptr pListener( i_pListener ); + boost::shared_ptr pPrinter( new Printer( i_rInitSetup.GetPrinterName() ) ); + pListener->setPrinter( pPrinter ); + + // setup page range selection + MultiSelection aSel; + int nPages = i_pListener->getPageCount(); + aSel.SetTotalRange( Range( 1, nPages ) ); + aSel.SelectAll(); + + // check if the printer brings up its own dialog + // in that case leave the work to that dialog + if( ! pListener->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) ) + { + try + { + PrintDialog aDlg( NULL, i_pListener ); + if( ! aDlg.Execute() ) + return; + if( aDlg.isPrintToFile() ) + { + rtl::OUString aFile = queryFile( pListener->getPrinter().get() ); + if( ! aFile.getLength() ) + return; + pListener->getPrinter()->EnablePrintFile( TRUE ); + pListener->getPrinter()->SetPrintFile( aFile ); + } + aSel = aDlg.getPageSelection(); + pListener->getPrinter()->SetCopyCount( aDlg.getCopyCount(), aDlg.isCollate() ); + } + catch( std::bad_alloc& ) + { + } + } + + pListener->setPageSelection( aSel ); + pListener->getPrinter()->StartJob( String( RTL_CONSTASCII_USTRINGPARAM( "FIXME: no job name" ) ), + pListener ); + + pListener->jobFinished(); +} + +bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptr& i_pListener ) +{ + mnError = PRINTER_OK; + + if ( IsDisplayPrinter() ) + return FALSE; + + if ( IsJobActive() || IsPrinting() ) + return FALSE; + + if( mpPrinterData->mbNextJobIsQuick ) + { + String aKey( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ); + if( maJobSetup.GetValue( aKey ).Len() == 0 ) + maJobSetup.SetValue( aKey, String( RTL_CONSTASCII_USTRINGPARAM( "true" ) ) ); + } + + ULONG nCopies = mnCopyCount; + BOOL bCollateCopy = mbCollateCopy; + BOOL bUserCopy = FALSE; + + if ( nCopies > 1 ) + { + ULONG nDevCopy; + + if ( bCollateCopy ) + nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COLLATECOPIES ); + else + nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COPIES ); + + // Muessen Kopien selber gemacht werden? + if ( nCopies > nDevCopy ) + { + bUserCopy = TRUE; + nCopies = 1; + bCollateCopy = FALSE; + } + } + else + bCollateCopy = FALSE; + + + ImplSVData* pSVData = ImplGetSVData(); + mpPrinter = pSVData->mpDefInst->CreatePrinter( mpInfoPrinter ); + + if ( !mpPrinter ) + return FALSE; + + XubString* pPrintFile; + if ( mbPrintFile ) + pPrintFile = &maPrintFile; + else + pPrintFile = NULL; + + maJobName = i_rJobName; + mnCurPage = 1; + mnCurPrintPage = 1; + mbPrinting = TRUE; + if( ImplGetSVData()->maGDIData.mbPrinterPullModel ) + { + mbJobActive = TRUE; + // sallayer does all necesseary page printing + if( mpPrinter->StartJob( pPrintFile, + Application::GetDisplayName(), + maJobSetup.ImplGetConstData(), + *i_pListener ) ) + { + EndJob(); + } + else + { + mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); + if ( !mnError ) + mnError = PRINTER_GENERALERROR; + pSVData->mpDefInst->DestroyPrinter( mpPrinter ); + mnCurPage = 0; + mnCurPrintPage = 0; + mbPrinting = FALSE; + mpPrinter = NULL; + + return false; + } + } + else + { + if( mpPrinter->StartJob( pPrintFile, + i_rJobName, + Application::GetDisplayName(), + nCopies, bCollateCopy, + maJobSetup.ImplGetConstData() ) ) + { + mbJobActive = TRUE; + MultiSelection aSel( i_pListener->getPageSelection() ); + for( long nPage = aSel.FirstSelected(); nPage != long(SFX_ENDOFSELECTION); nPage = aSel.NextSelected() ) + { + // remember MultiSelection is 1 based (due to user input) + i_pListener->printFilteredPage( static_cast(nPage-1) ); + } + EndJob(); + } + else + { + mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); + if ( !mnError ) + mnError = PRINTER_GENERALERROR; + pSVData->mpDefInst->DestroyPrinter( mpPrinter ); + mnCurPage = 0; + mnCurPrintPage = 0; + mbPrinting = FALSE; + mpPrinter = NULL; + + return false; + } + } + + return true; +} + +PrinterListener::~PrinterListener() +{ + delete mpImplData; +} + +const boost::shared_ptr& PrinterListener::getPrinter() const +{ + return mpImplData->mpPrinter; +} + +const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& PrinterListener::getJobParameters() const +{ + return mpImplData->mxJobParameters; +} + +const MultiSelection& PrinterListener::getPageSelection() const +{ + return mpImplData->maSelection; +} + +void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) +{ + mpImplData->mpPrinter = i_rPrinter; +} + +void PrinterListener::setJobParameters( const Reference< beans::XPropertySet >& i_pParams ) +{ + mpImplData->mxJobParameters = i_pParams; +} + +void PrinterListener::setPageSelection( const MultiSelection& i_rSel ) +{ + mpImplData->maSelection = i_rSel; +} + +void PrinterListener::printFilteredPage( int i_nPage ) +{ + // get page parameters + JobSetup aPageSetup; + Size aPageSize; + getPageParameters( i_nPage, aPageSetup, aPageSize ); + const MapMode aMapMode( MAP_100TH_MM ); + + + mpImplData->mpPrinter->Push(); + mpImplData->mpPrinter->EnableOutput( FALSE ); + mpImplData->mpPrinter->SetMapMode( aMapMode ); + + GDIMetaFile aMtf; + aMtf.Record( mpImplData->mpPrinter.get() ); + + printPage( i_nPage ); + + aMtf.Stop(); + aMtf.WindStart(); + mpImplData->mpPrinter->Pop(); + + // FIXME: do transparency filtering here when vcl92 is integrated + + mpImplData->mpPrinter->EnableOutput( TRUE ); + if( aPageSetup != mpImplData->mpPrinter->GetJobSetup() ) // set new setup if changed + mpImplData->mpPrinter->SetJobSetup( aPageSetup ); + + // actually print the page + mpImplData->mpPrinter->StartPage(); + + mpImplData->mpPrinter->Push(); + mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); + aMtf.WindStart(); + aMtf.Play( mpImplData->mpPrinter.get() ); + mpImplData->mpPrinter->Pop(); + + mpImplData->mpPrinter->EndPage(); +} + +void PrinterListener::setListeners() +{ +} + +void PrinterListener::jobFinished() +{ +} + diff --git a/vcl/source/src/makefile.mk b/vcl/source/src/makefile.mk index cf01c74b977d..7772af5a0978 100644 --- a/vcl/source/src/makefile.mk +++ b/vcl/source/src/makefile.mk @@ -8,7 +8,7 @@ # # $RCSfile: makefile.mk,v $ # -# $Revision: 1.8 $ +# $Revision: 1.8.114.1 $ # # This file is part of OpenOffice.org. # @@ -47,7 +47,8 @@ SRC1FILES= images.src \ stdtext.src \ helptext.src \ units.src \ - btntext.src + btntext.src \ + print.src RESLIB1NAME= $(RESTARGET) RESLIB1IMAGES= $(PRJ)$/source/src diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src new file mode 100644 index 000000000000..b85783b02ddd --- /dev/null +++ b/vcl/source/src/print.src @@ -0,0 +1,247 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: print.src,v $ + * $Revision: 1.1.2.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "vcl/svids.hrc" + +ModalDialog SV_DLG_PRINT +{ + Text [en-US] = "Printing"; + Closeable = TRUE; + Sizeable = FALSE; + Moveable = TRUE; + SVLook = TRUE; + + Size = MAP_APPFONT( 350, 195 ); + + OKButton SV_PRINT_OK + { + DefButton = TRUE; + Pos = MAP_APPFONT( 240, 175 ); + Size = MAP_APPFONT( 50, 15 ); + }; + CancelButton SV_PRINT_CANCEL + { + Pos = MAP_APPFONT( 295, 175 ); + Size = MAP_APPFONT( 50, 15 ); + }; + + Window SV_PRINT_PAGE_PREVIEW + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 130, 130 ); + Border = TRUE; + }; + ScrollBar SV_PRINT_PAGE_SCROLL + { + Pos = MAP_APPFONT( 5, 140 ); + Size = MAP_APPFONT( 130, 10 ); + SVLook = TRUE; + HScroll = TRUE; + TabStop = TRUE; + }; + FixedText SV_PRINT_PAGE_TXT + { + Pos = MAP_APPFONT( 5,150 ); + Size = MAP_APPFONT( 130, 10 ); + Text [ en-US ] = "Page %p of %n"; + Center = TRUE; + }; + TabControl SV_PRINT_TABCTRL + { + Pos = MAP_APPFONT( 140, 5 ); + Size = MAP_APPFONT( 205, 155 ); + }; + FixedLine SV_PRINT_BUTTONLINE + { + Pos = MAP_APPFONT( 0, 165 ); + Size = MAP_APPFONT( 350, 8 ); + }; + + TabPage SV_PRINT_TAB_PRINTER + { + Text [en-US] = "Printer"; + Hide = TRUE; + + ListBox SV_PRINT_PRINTERS + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 200 ); + DropDown = TRUE; + }; + PushButton SV_PRINT_PRT_SETUP + { + Pos = MAP_APPFONT( 115, 5 ); + Size = MAP_APPFONT( 50, 15 ); + Text [en-US] = "Properties..."; + }; + FixedText SV_PRINT_PRT_TYPE + { + Pos = MAP_APPFONT( 5, 30 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "Type"; + }; + FixedText SV_PRINT_PRT_TYPE_TXT + { + Pos = MAP_APPFONT( 50, 30 ); + Size = MAP_APPFONT( 200, 10 ); + }; + FixedText SV_PRINT_PRT_STATUS + { + Pos = MAP_APPFONT( 5, 42 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "Status"; + }; + FixedText SV_PRINT_PRT_STATUS_TXT + { + Pos = MAP_APPFONT( 50, 42 ); + Size = MAP_APPFONT( 200, 10 ); + }; + FixedText SV_PRINT_PRT_LOCATION + { + Pos = MAP_APPFONT( 5, 54 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "Location"; + }; + FixedText SV_PRINT_PRT_LOCATION_TXT + { + Pos = MAP_APPFONT( 50, 54 ); + Size = MAP_APPFONT( 200, 10 ); + }; + FixedText SV_PRINT_PRT_COMMENT + { + Pos = MAP_APPFONT( 5, 66 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "Comment"; + }; + FixedText SV_PRINT_PRT_COMMENT_TXT + { + Pos = MAP_APPFONT( 50, 66 ); + Size = MAP_APPFONT( 200, 10 ); + }; + CheckBox SV_PRINT_PRT_TOFILE + { + Pos = MAP_APPFONT( 5, 80 ); + Size = MAP_APPFONT( 200, 12 ); + Text [en-US] = "Print to file"; + }; + }; + + TabPage SV_PRINT_TAB_JOB + { + Text [en-US] = "Job Setup"; + Hide = TRUE; + + FixedLine SV_PRINT_RANGE + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 150, 10 ); + Text [en-US] = "Print range"; + }; + RadioButton SV_PRINT_ALL + { + Pos = MAP_APPFONT( 10, 15 ); + Size = MAP_APPFONT( 145, 15 ); + Text [en-US] = "All pages"; + Check = TRUE; + }; + RadioButton SV_PRINT_PAGERANGE + { + Pos = MAP_APPFONT( 10, 30 ); + Size = MAP_APPFONT( 60, 15 ); + Text [en-US] = "Pages"; + }; + Edit SV_PRINT_PAGERANGE_EDIT + { + Pos = MAP_APPFONT( 70, 30 ); + Size = MAP_APPFONT( 80, 15 ); + Border = TRUE; + }; + RadioButton SV_PRINT_SELECTION + { + Pos = MAP_APPFONT( 10, 45 ); + Size = MAP_APPFONT( 145, 15 ); + Text [en-US] = "Selection"; + }; + + FixedLine SV_PRINT_COPIES + { + Pos = MAP_APPFONT( 5, 70 ); + Size = MAP_APPFONT( 150, 10 ); + Text [en-US] = "Copies"; + }; + FixedText SV_PRINT_COPYCOUNT + { + Pos = MAP_APPFONT( 10, 80 ); + Size = MAP_APPFONT( 80, 10 ); + Text [en-US] = "Number of copies"; + }; + NumericField SV_PRINT_COPYCOUNT_FIELD + { + Pos = MAP_APPFONT( 90, 80 ); + Size = MAP_APPFONT( 40, 10 ); + Border = TRUE; + Spin = TRUE; + Minimum = 1; + Maximum = 16384; + Value = 1; + }; + FixedImage SV_PRINT_COLLATE_IMAGE + { + Pos = MAP_APPFONT( 10, 100 ); + Size = MAP_PIXEL( 80, 30 ); + }; + CheckBox SV_PRINT_COLLATE + { + Pos = MAP_APPFONT( 80, 100 ); + Size = MAP_APPFONT( 70, 10 ); + Text [en-US] = "Collate"; + }; + + Image SV_PRINT_COLLATE_IMG + { + ImageBitmap = Bitmap { File = "collate.png" ; }; + }; + + Image SV_PRINT_NOCOLLATE_IMG + { + ImageBitmap = Bitmap { File = "ncollate.png" ; }; + }; + + Image SV_PRINT_COLLATE_HC_IMG + { + ImageBitmap = Bitmap { File = "collate_h.png" ; }; + }; + + Image SV_PRINT_NOCOLLATE_HC_IMG + { + ImageBitmap = Bitmap { File = "ncollate_h.png" ; }; + }; + }; +}; diff --git a/vcl/source/src/stdtext.src b/vcl/source/src/stdtext.src index 5ad1cdceeb61..d4dca4915b6b 100644 --- a/vcl/source/src/stdtext.src +++ b/vcl/source/src/stdtext.src @@ -7,7 +7,7 @@ * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stdtext.src,v $ - * $Revision: 1.53 $ + * $Revision: 1.53.84.1 $ * * This file is part of OpenOffice.org. * @@ -123,3 +123,8 @@ String SV_MAC_SCREENNNAME { Text [en-US] = "Screen %d"; }; + +String SV_STDTEXT_ALLFILETYPES +{ + Text [en-US] = "Any type"; +}; diff --git a/vcl/source/window/makefile.mk b/vcl/source/window/makefile.mk index cdd4aef73bb0..cadea48f6f7a 100644 --- a/vcl/source/window/makefile.mk +++ b/vcl/source/window/makefile.mk @@ -8,7 +8,7 @@ # # $RCSfile: makefile.mk,v $ # -# $Revision: 1.25 $ +# $Revision: 1.25.114.1 $ # # This file is part of OpenOffice.org. # @@ -70,6 +70,7 @@ SLOFILES= \ $(SLO)$/mnemonicengine.obj \ $(SLO)$/msgbox.obj \ $(SLO)$/scrwnd.obj \ + $(SLO)$/printdlg.obj \ $(SLO)$/seleng.obj \ $(SLO)$/split.obj \ $(SLO)$/splitwin.obj \ diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx new file mode 100644 index 000000000000..9270562358be --- /dev/null +++ b/vcl/source/window/printdlg.cxx @@ -0,0 +1,405 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: printdlg.cxx,v $ + * $Revision: 1.1.2.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "precompiled_vcl.hxx" + +#include "vcl/print.hxx" +#include "vcl/prndlg.hxx" +#include "vcl/dialog.hxx" +#include "vcl/button.hxx" +#include "vcl/svdata.hxx" +#include "vcl/svids.hrc" +#include "vcl/wall.hxx" +#include "vcl/jobset.h" + +#include "rtl/ustrbuf.hxx" + +using namespace vcl; + +PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) + : Window( i_pParent, i_rId ) +{ +} + +PrintDialog::PrintPreviewWindow::~PrintPreviewWindow() +{ +} + +void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) +{ + Window::Paint( i_rRect ); + + SetFillColor( Color( COL_WHITE ) ); + SetLineColor(); + DrawRect( Rectangle( Point( 0, 0 ), GetSizePixel() )); + Push(); + SetMapMode( MAP_100TH_MM ); + maMtf.WindStart(); + maMtf.Play( this, Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ); + Pop(); +} + +void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview ) +{ + maMtf = i_rNewPreview; + Invalidate(); +} + +PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rResId ) + : TabPage( i_pParent, rResId ) + , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) + , maSetupButton( this, VclResId( SV_PRINT_PRT_SETUP ) ) + , maType( this, VclResId( SV_PRINT_PRT_TYPE ) ) + , maTypeText( this, VclResId( SV_PRINT_PRT_TYPE_TXT ) ) + , maStatus( this, VclResId( SV_PRINT_PRT_STATUS ) ) + , maStatusText(this, VclResId( SV_PRINT_PRT_STATUS_TXT ) ) + , maLocation( this, VclResId( SV_PRINT_PRT_LOCATION ) ) + , maLocText( this, VclResId( SV_PRINT_PRT_LOCATION_TXT ) ) + , maComment( this, VclResId( SV_PRINT_PRT_COMMENT ) ) + , maCommentText( this, VclResId( SV_PRINT_PRT_COMMENT_TXT ) ) + , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) +{ + FreeResource(); +} + +PrintDialog::PrinterTabPage::~PrinterTabPage() +{ +} + +PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) + : TabPage( i_pParent, rResId ) + , maPrintRange( this, VclResId( SV_PRINT_RANGE ) ) + , maAllButton( this, VclResId( SV_PRINT_ALL ) ) + , maPagesButton( this, VclResId( SV_PRINT_PAGERANGE ) ) + , maSelectionButton( this, VclResId( SV_PRINT_SELECTION ) ) + , maPagesEdit( this, VclResId( SV_PRINT_PAGERANGE_EDIT ) ) + , maCopies( this, VclResId( SV_PRINT_COPIES ) ) + , maCopyCount( this, VclResId( SV_PRINT_COPYCOUNT ) ) + , maCopyCountField( this, VclResId( SV_PRINT_COPYCOUNT_FIELD ) ) + , maCollateBox( this, VclResId( SV_PRINT_COLLATE ) ) + , maCollateImage( this, VclResId( SV_PRINT_COLLATE_IMAGE ) ) + , maCollateImg( VclResId( SV_PRINT_COLLATE_IMG ) ) + , maCollateHCImg( VclResId( SV_PRINT_COLLATE_HC_IMG ) ) + , maNoCollateImg( VclResId( SV_PRINT_NOCOLLATE_IMG ) ) + , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) +{ + FreeResource(); +} + +PrintDialog::JobTabPage::~JobTabPage() +{ +} + +PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rListener ) + : ModalDialog( i_pParent, VclResId( SV_DLG_PRINT ) ) + , maOKButton( this, VclResId( SV_PRINT_OK ) ) + , maCancelButton( this, VclResId( SV_PRINT_CANCEL ) ) + , maPreviewWindow( this, VclResId( SV_PRINT_PAGE_PREVIEW ) ) + , maPageText( this, VclResId( SV_PRINT_PAGE_TXT ) ) + , maPageScrollbar( this, VclResId( SV_PRINT_PAGE_SCROLL ) ) + , maTabCtrl( this, VclResId( SV_PRINT_TABCTRL ) ) + , maPrinterPage( &maTabCtrl, VclResId( SV_PRINT_TAB_PRINTER ) ) + , maJobPage( &maTabCtrl, VclResId( SV_PRINT_TAB_JOB ) ) + , maButtonLine( this, VclResId( SV_PRINT_BUTTONLINE ) ) + , maPListener( i_rListener ) + , mnCurPage( 0 ) + , mnCachedPages( 0 ) +{ + FreeResource(); + + // insert the tab pages + maTabCtrl.InsertPage( SV_PRINT_PAGE_PREVIEW, maPrinterPage.GetText() ); + maTabCtrl.SetTabPage( SV_PRINT_PAGE_PREVIEW, &maPrinterPage ); + maTabCtrl.InsertPage( SV_PRINT_TAB_JOB, maJobPage.GetText() ); + maTabCtrl.SetTabPage( SV_PRINT_TAB_JOB, &maJobPage ); + + maPageStr = maPageText.GetText(); + // save space for the preview window + maPreviewSpace = Rectangle( maPreviewWindow.GetPosPixel(), maPreviewWindow.GetSizePixel() ); + // get the first page + preparePreview(); + + // set up the scrollbar for the preview pages + maPageScrollbar.SetScrollHdl( LINK( this, PrintDialog, ScrollHdl ) ); + maPageScrollbar.SetEndScrollHdl( LINK( this, PrintDialog, ScrollEndHdl ) ); + maPageScrollbar.EnableDrag( TRUE ); + + // fill printer listbox + const std::vector< rtl::OUString >& rQueues( Printer::GetPrinterQueues() ); + for( std::vector< rtl::OUString >::const_iterator it = rQueues.begin(); + it != rQueues.end(); ++it ) + { + maPrinterPage.maPrinters.InsertEntry( *it ); + } + // select current printer + if( maPrinterPage.maPrinters.GetEntryPos( maPListener->getPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) + maPrinterPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); + else + { + // fall back to default printer + maPrinterPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); + maPListener->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); + } + // update the text fields for the printer + updatePrinterText(); + + // set a select handler + maPrinterPage.maPrinters.SetSelectHdl( LINK( this, PrintDialog, SelectHdl ) ); + + // setup page range edit + rtl::OUStringBuffer aBuf( 16 ); + aBuf.append( sal_Unicode('1') ); + if( mnCachedPages > 1 ) + { + aBuf.append( sal_Unicode('-') ); + aBuf.append( mnCachedPages ); + } + maJobPage.maPagesEdit.SetText( aBuf.makeStringAndClear() ); + + // setup click handler on the various buttons + maJobPage.maCollateBox.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maJobPage.maAllButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maJobPage.maSelectionButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maJobPage.maPagesButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maPrinterPage.maSetupButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + + // setup modify hdl + maJobPage.maCopyCountField.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); + + // setup dependencies + checkControlDependencies(); +} + +PrintDialog::~PrintDialog() +{ +} + +bool PrintDialog::isPrintToFile() +{ + return maPrinterPage.maToFileBox.IsChecked(); +} + +int PrintDialog::getCopyCount() +{ + return maJobPage.maCopyCountField.GetValue(); +} + +bool PrintDialog::isCollate() +{ + return maJobPage.maCopyCountField.GetValue() > 1 ? maJobPage.maCollateBox.IsChecked() : FALSE; +} + +MultiSelection PrintDialog::getPageSelection() +{ + if( maJobPage.maPagesButton.IsChecked() ) + return MultiSelection( maJobPage.maPagesEdit.GetText() ); + else if( maJobPage.maAllButton.IsChecked() ) + { + MultiSelection aSel( Range( 1, maPListener->getPageCount() ) ); + aSel.SelectAll(); + return aSel; + } + DBG_ERROR( "NYI: Selection" ); + return MultiSelection(); +} + +void PrintDialog::checkControlDependencies() +{ + if( maJobPage.maCopyCountField.GetValue() > 1 ) + maJobPage.maCollateBox.Enable( TRUE ); + else + maJobPage.maCollateBox.Enable( FALSE ); + + maJobPage.maPagesEdit.Enable( maJobPage.maPagesButton.IsChecked() ); + Image aImg( maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateImg : maJobPage.maNoCollateImg ); + if( GetSettings().GetStyleSettings().GetFieldColor().IsDark() ) + aImg = maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateHCImg : maJobPage.maNoCollateHCImg; + + // adjust position and size of image + maJobPage.maCollateImage.SetSizePixel( aImg.GetSizePixel() ); + Point aPos( maJobPage.maCollateImage.GetPosPixel() ); + aPos.Y() = maJobPage.maCollateBox.GetPosPixel().Y(); + aPos.Y() -= (aImg.GetSizePixel().Height() - maJobPage.maCollateBox.GetSizePixel().Height())/2; + maJobPage.maCollateImage.SetPosPixel( aPos ); + maJobPage.maCollateImage.SetImage( aImg ); + + // enable setup button only for printers that can be setup + maPrinterPage.maSetupButton.Enable( maPListener->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ) ); +} + +void PrintDialog::updatePrinterText() +{ + const QueueInfo* pInfo = Printer::GetQueueInfo( maPrinterPage.maPrinters.GetSelectEntry(), true ); + if( pInfo ) + { + maPrinterPage.maTypeText.SetText( pInfo->GetDriver() ); + // FIXME: status message + // maJobPage.maStatusText.SetText(); + maPrinterPage.maLocText.SetText( pInfo->GetLocation() ); + maPrinterPage.maCommentText.SetText( pInfo->GetComment() ); + } +} + +static rtl::OUString searchAndReplace( const rtl::OUString& i_rOrig, const char* i_pRepl, sal_Int32 i_nReplLen, sal_Int32 i_nReplacement ) +{ + sal_Int32 nPos = i_rOrig.indexOfAsciiL( i_pRepl, i_nReplLen ); + if( nPos != -1 ) + { + rtl::OUStringBuffer aBuf( i_rOrig.getLength() ); + aBuf.append( i_rOrig.getStr(), nPos ); + aBuf.append( i_nReplacement ); + if( nPos + i_nReplLen < i_rOrig.getLength() ) + aBuf.append( i_rOrig.getStr() + nPos + i_nReplLen ); + return aBuf.makeStringAndClear(); + } + return i_rOrig; +} + +void PrintDialog::setPreviewText( sal_Int32 nSetPage ) +{ + rtl::OUString aNewText( searchAndReplace( maPageStr, "%p", 2, nSetPage+1 ) ); + aNewText = searchAndReplace( aNewText, "%n", 2, mnCachedPages ); + maPageText.SetText( aNewText ); +} + +void PrintDialog::preparePreview() +{ + sal_Int32 nPages = maPListener->getPageCount(); + mnCachedPages = nPages; + + setPreviewText( mnCurPage ); + + maPageScrollbar.SetRange( Range( 0, nPages-1 ) ); + maPageScrollbar.SetThumbPos( mnCurPage ); + + boost::shared_ptr aPrt( maPListener->getPrinter() ); + + + const MapMode aMapMode( MAP_100TH_MM ); + Size aPageSize; + JobSetup aPageSetup( aPrt->GetJobSetup() ); + maPListener->getPageParameters( mnCurPage, aPageSetup, aPageSize ); + ImplUpdateJobSetupPaper( aPageSetup ); // fill in physical paper size + Size aPaperSize( aPageSetup.ImplGetConstData()->mnPaperWidth, + aPageSetup.ImplGetConstData()->mnPaperHeight ); + if( aPageSetup.ImplGetConstData()->meOrientation == ORIENTATION_LANDSCAPE ) + { + aPaperSize.Width() = aPageSetup.ImplGetConstData()->mnPaperHeight; + aPaperSize.Height() = aPageSetup.ImplGetConstData()->mnPaperWidth; + } + + aPrt->Push(); + aPrt->EnableOutput( FALSE ); + aPrt->SetMapMode( aMapMode ); + + GDIMetaFile aMtf; + aMtf.SetPrefSize( aPageSize ); + aMtf.SetPrefMapMode( aMapMode ); + aMtf.Record( &(*aPrt) ); + + maPListener->printPage( mnCurPage ); + + aMtf.Stop(); + aMtf.WindStart(); + aPrt->Pop(); + + Size aPreviewSize; + Point aPreviewPos = maPreviewSpace.TopLeft(); + const long nW = maPreviewSpace.GetSize().Width(); + const long nH = maPreviewSpace.GetSize().Height(); + if( aPaperSize.Width() > aPaperSize.Height() ) + { + aPreviewSize = Size( nW, nW * aPaperSize.Height() / aPaperSize.Width() ); + aPreviewPos.Y() += (maPreviewSpace.GetHeight() - aPreviewSize.Height())/2; + } + else + { + aPreviewSize = Size( nH * aPaperSize.Width() / aPaperSize.Height(), nH ); + aPreviewPos.X() += (maPreviewSpace.GetWidth() - aPreviewSize.Width())/2; + } + maPreviewWindow.SetPosSizePixel( aPreviewPos, aPreviewSize ); + const Size aLogicSize( maPreviewWindow.PixelToLogic( maPreviewWindow.GetSizePixel(), MapMode( MAP_100TH_MM ) ) ); + aMtf.Scale( double(aLogicSize.Width())/double(aPaperSize.Width()), + double(aLogicSize.Height())/double(aPaperSize.Height()) ); + maPreviewWindow.setPreview( aMtf ); +} + +IMPL_LINK( PrintDialog, ScrollHdl, ScrollBar*, pScrBar ) +{ + if( pScrBar == &maPageScrollbar ) + { + sal_Int32 nNewPage = static_cast( maPageScrollbar.GetThumbPos() ); + setPreviewText( nNewPage ); + } + return 0; +} + +IMPL_LINK( PrintDialog, ScrollEndHdl, ScrollBar*, pScrBar ) +{ + if( pScrBar == &maPageScrollbar ) + { + sal_Int32 nNewPage = static_cast( maPageScrollbar.GetThumbPos() ); + if( nNewPage != mnCurPage ) + { + mnCurPage = nNewPage; + preparePreview(); + } + } + return 0; +} + +IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) +{ + if( pBox == &maPrinterPage.maPrinters ) + { + // set new printer + maPListener->setPrinter( boost::shared_ptr( new Printer( maPrinterPage.maPrinters.GetSelectEntry() ) ) ); + // update text fields + updatePrinterText(); + } + return 0; +} + +IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) +{ + if( pButton == &maPrinterPage.maSetupButton ) + { + maPListener->getPrinter()->Setup( this ); + } + checkControlDependencies(); + return 0; +} + +IMPL_LINK( PrintDialog, ModifyHdl, Edit*, EMPTYARG ) +{ + checkControlDependencies(); + return 0; +} + -- cgit From d47140e61cc0f58dec4c93a2eb801b03be3fa0ff Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Oct 2008 14:31:29 +0000 Subject: #i92516# prepare app specific print dialog elements --- vcl/inc/vcl/print.hxx | 40 +++++-- vcl/inc/vcl/prndlg.hxx | 8 +- vcl/source/gdi/print3.cxx | 173 +++++++++++++++++++++++------ vcl/source/window/printdlg.cxx | 239 ++++++++++++++++++++++++++++++++++++++--- 4 files changed, 403 insertions(+), 57 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index e6199437ca4a..e939c5a09705 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -41,7 +41,7 @@ #include "tools/stream.hxx" #include "tools/multisel.hxx" -#include "com/sun/star/beans/XPropertySet.hpp" +#include "com/sun/star/beans/PropertyValue.hpp" #include @@ -438,15 +438,13 @@ public: */ static void PrintJob( const boost::shared_ptr& i_pListener, - const JobSetup& i_rInitSetup, - const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& i_xJobOptions + const JobSetup& i_rInitSetup ); // implementation detail of PrintJob being asynchronous // not exported, not usable outside vcl static void SAL_DLLPRIVATE ImplPrintJob( const boost::shared_ptr& i_pListener, - const JobSetup& i_rInitSetup, - const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& i_xJobOptions + const JobSetup& i_rInitSetup ); }; @@ -462,9 +460,33 @@ public: virtual ~PrinterListener(); const boost::shared_ptr& getPrinter() const; - const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& getJobParameters() const; const MultiSelection& getPageSelection() const; + /* for implementations: get current job properties as changed by e.g. print dialog + this gets the current set of properties initially told to Printer::PrintJob + + For convenience a second sequence will be merged in to get a combined sequence. + In case of duplicate property names, the value of i_MergeList wins. + */ + com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > + getJobProperties( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rMergeList ) const; + + /* get the PorpertyValue of a Property + */ + com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); + + /* return the currently active UI options. These are the same passed to setUIOptions. + */ + const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& getUIOptions() const; + /* set possible UI options. should only be done once before passing the PrinterListener + to Printer::PrintJob + */ + void setUIOptions( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& ); + /* enable/disable an option; this can be used to implement dialog logic. + */ + void enableUIOption( const rtl::OUString& rPropName, bool bEnable ); + bool isUIOptionEnabled( const rtl::OUString& rPropName ) const; + virtual int getPageCount() const = 0; // must be overloaded by the app /* get the page parameters, namely the jobsetup that should be active for the page (describing among others the physical page size) and the "page size". In writer @@ -473,17 +495,17 @@ public: possibly adjusting the page size to fit. That means the page size can be different from the paper size. */ - virtual void getPageParameters( int i_nPage, JobSetup& o_rPageSetup, Size& o_rPageSize ) const = 0; // must be overloaded by the app, return page size in 1/100th mm + // must be overloaded by the app, return page size in 1/100th mm + virtual com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getPageParameters( int i_nPage ) const = 0; virtual void printPage( int i_nPage ) const = 0; // must be overloaded by the app - virtual void setListeners(); // optionally set listeners on mxJobParameters virtual void jobFinished(); // optionally release resources bound to the job void printFilteredPage( int i_nPage ); // implementation details, not usable outsid vcl void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); - void SAL_DLLPRIVATE setJobParameters( const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& ); void SAL_DLLPRIVATE setPageSelection( const MultiSelection& ); + void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); }; } diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index f5b4a35e0331..cbd6125aaca9 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -49,7 +49,7 @@ #include "tools/multisel.hxx" #include - +#include namespace vcl { @@ -129,16 +129,22 @@ namespace vcl sal_Int32 mnCachedPages; Rectangle maPreviewSpace; + std::list< Window* > maControls; + std::map< Window*, rtl::OUString > maControlToPropertyMap; + std::multimap< rtl::OUString, Window* > maPropertyToWindowMap; + void preparePreview(); void setPreviewText( sal_Int32 ); void updatePrinterText(); void checkControlDependencies(); + void setupOptionalUI(); DECL_LINK( ScrollHdl, ScrollBar* ); DECL_LINK( ScrollEndHdl, ScrollBar* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); DECL_LINK( ModifyHdl, Edit* ); + DECL_LINK( UIOptionsChanged, void* ); public: PrintDialog( Window*, const boost::shared_ptr< PrinterListener >& ); virtual ~PrintDialog(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e92d5c250112..4aecf29770d9 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -46,18 +46,28 @@ #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp" #include "com/sun/star/lang/XMultiServiceFactory.hpp" +#include "com/sun/star/awt/Size.hpp" #include "comphelper/processfactory.hxx" +#include +#include + using namespace com::sun::star; using namespace com::sun::star::uno; +using namespace com::sun::star::beans; using namespace vcl; class vcl::ImplPrinterListenerData { public: - boost::shared_ptr mpPrinter; - com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet > mxJobParameters; - MultiSelection maSelection; + + boost::shared_ptr mpPrinter; + MultiSelection maSelection; + Sequence< PropertyValue > maUIOptions; + std::vector< PropertyValue > maUIProperties; + std::vector< bool > maUIPropertyEnabled; + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash > maPropertyToIndex; + Link maOptionChangeHdl; }; PrinterListener::PrinterListener() @@ -126,13 +136,11 @@ struct PrintJobAsync { boost::shared_ptr mpListener; JobSetup maInitSetup; - Reference< beans::XPropertySet > mxJobOptions; PrintJobAsync( const boost::shared_ptr& i_pListener, - const JobSetup& i_rInitSetup, - const Reference< beans::XPropertySet >& i_xJobOptions + const JobSetup& i_rInitSetup ) - : mpListener( i_pListener ), maInitSetup( i_rInitSetup ), mxJobOptions( i_xJobOptions ) + : mpListener( i_pListener ), maInitSetup( i_rInitSetup ) {} DECL_LINK( ExecJob, void* ); @@ -140,7 +148,7 @@ struct PrintJobAsync IMPL_LINK( PrintJobAsync, ExecJob, void*, EMPTYARG ) { - Printer::ImplPrintJob( mpListener, maInitSetup, mxJobOptions ); + Printer::ImplPrintJob( mpListener, maInitSetup ); // clean up, do not access members after this delete this; @@ -149,17 +157,15 @@ IMPL_LINK( PrintJobAsync, ExecJob, void*, EMPTYARG ) } void Printer::PrintJob( const boost::shared_ptr& i_pListener, - const JobSetup& i_rInitSetup, - const Reference< beans::XPropertySet >& i_xJobOptions + const JobSetup& i_rInitSetup ) { - PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup, i_xJobOptions ); + PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup ); Application::PostUserEvent( LINK( pAsync, PrintJobAsync, ExecJob ) ); } void Printer::ImplPrintJob( const boost::shared_ptr& i_pListener, - const JobSetup& i_rInitSetup, - const Reference< beans::XPropertySet >& /*i_xJobOptions*/ + const JobSetup& i_rInitSetup ) { // setup printer @@ -333,11 +339,6 @@ const boost::shared_ptr& PrinterListener::getPrinter() const return mpImplData->mpPrinter; } -const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >& PrinterListener::getJobParameters() const -{ - return mpImplData->mxJobParameters; -} - const MultiSelection& PrinterListener::getPageSelection() const { return mpImplData->maSelection; @@ -348,29 +349,44 @@ void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) mpImplData->mpPrinter = i_rPrinter; } -void PrinterListener::setJobParameters( const Reference< beans::XPropertySet >& i_pParams ) +void PrinterListener::setPageSelection( const MultiSelection& i_rSel ) { - mpImplData->mxJobParameters = i_pParams; + mpImplData->maSelection = i_rSel; } -void PrinterListener::setPageSelection( const MultiSelection& i_rSel ) +static void modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) { - mpImplData->maSelection = i_rSel; + for( sal_Int32 nProperty = 0, nPropertyCount = i_rProps.getLength(); nProperty < nPropertyCount; ++nProperty ) + { + if( i_rProps[ nProperty ].Name.equalsAscii( "PageSize" ) ) + { + Size aPageSize; + awt::Size aSize; + i_rProps[ nProperty].Value >>= aSize; + aPageSize.Width() = aSize.Width; + aPageSize.Height() = aSize.Height; + + Size aCurSize( pPrinter->GetPaperSize() ); + if( aPageSize != aCurSize ) + pPrinter->SetPaperSizeUser( aPageSize ); + } + } } void PrinterListener::printFilteredPage( int i_nPage ) { // get page parameters - JobSetup aPageSetup; - Size aPageSize; - getPageParameters( i_nPage, aPageSetup, aPageSize ); + Sequence< PropertyValue > aPageParm( getPageParameters( i_nPage ) ); const MapMode aMapMode( MAP_100TH_MM ); - mpImplData->mpPrinter->Push(); - mpImplData->mpPrinter->EnableOutput( FALSE ); mpImplData->mpPrinter->SetMapMode( aMapMode ); + // modify job setup if necessary + modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); + + mpImplData->mpPrinter->EnableOutput( FALSE ); + GDIMetaFile aMtf; aMtf.Record( mpImplData->mpPrinter.get() ); @@ -383,8 +399,6 @@ void PrinterListener::printFilteredPage( int i_nPage ) // FIXME: do transparency filtering here when vcl92 is integrated mpImplData->mpPrinter->EnableOutput( TRUE ); - if( aPageSetup != mpImplData->mpPrinter->GetJobSetup() ) // set new setup if changed - mpImplData->mpPrinter->SetJobSetup( aPageSetup ); // actually print the page mpImplData->mpPrinter->StartPage(); @@ -398,11 +412,108 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->EndPage(); } -void PrinterListener::setListeners() +void PrinterListener::jobFinished() { } -void PrinterListener::jobFinished() +Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const +{ + std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; + size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size(); + for( int i = 0; i < i_rMergeList.getLength(); i++ ) + aMergeSet.insert( i_rMergeList[i].Name ); + + Sequence< PropertyValue > aResult( nResultLen ); + for( int i = 0; i < i_rMergeList.getLength(); i++ ) + aResult[i] = i_rMergeList[i]; + int nCur = i_rMergeList.getLength(); + for( size_t i = 0; i < mpImplData->maUIProperties.size(); i++ ) + { + if( aMergeSet.find( mpImplData->maUIProperties[i].Name ) == aMergeSet.end() ) + aResult[nCur++] = mpImplData->maUIProperties[i]; + } + aResult.realloc( nCur ); + return aResult; +} + +const Sequence< beans::PropertyValue >& PrinterListener::getUIOptions() const +{ + return mpImplData->maUIOptions; +} + +com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl::OUString& i_rProperty ) +{ + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + mpImplData->maPropertyToIndex.find( i_rProperty ); + return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; +} + +void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rOptions ) +{ + DBG_ASSERT( mpImplData->maUIOptions.getLength() == 0, "setUIOptions called twice !" ); + + mpImplData->maUIOptions = i_rOptions; + mpImplData->maUIProperties.clear(); + mpImplData->maPropertyToIndex.clear(); + mpImplData->maUIPropertyEnabled.clear(); + + for( int i = 0; i < i_rOptions.getLength(); i++ ) + { + Sequence< beans::PropertyValue > aOptProp; + i_rOptions[i].Value >>= aOptProp; + bool bIsEnabled = true; + bool bHaveProperty = false; + for( int n = 0; n < aOptProp.getLength(); n++ ) + { + const beans::PropertyValue& rEntry( aOptProp[ n ] ); + if( rEntry.Name.equalsAscii( "Property" ) ) + { + PropertyValue aVal; + rEntry.Value >>= aVal; + DBG_ASSERT( mpImplData->maPropertyToIndex.find( aVal.Name ) + == mpImplData->maPropertyToIndex.end(), "duplicate property entry" ); + mpImplData->maPropertyToIndex[ aVal.Name ] = i; + mpImplData->maUIProperties.push_back( aVal ); + bHaveProperty = true; + } + else if( rEntry.Name.equalsAscii( "Enabled" ) ) + { + sal_Bool bValue = sal_True; + rEntry.Value >>= bValue; + bIsEnabled = bValue; + } + } + if( bHaveProperty ) + mpImplData->maUIPropertyEnabled.push_back( bIsEnabled ); + } +} + +void PrinterListener::enableUIOption( const rtl::OUString& i_rProperty, bool i_bEnable ) +{ + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + mpImplData->maPropertyToIndex.find( i_rProperty ); + if( it != mpImplData->maPropertyToIndex.end() ) + { + // call handler only for actual changes + if( ( mpImplData->maUIPropertyEnabled[ it->second ] && ! i_bEnable ) || + ( ! mpImplData->maUIPropertyEnabled[ it->second ] && i_bEnable ) ) + { + mpImplData->maUIPropertyEnabled[ it->second ] = i_bEnable; + rtl::OUString aPropName( i_rProperty ); + mpImplData->maOptionChangeHdl.Call( &aPropName ); + } + } +} + +bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) const +{ + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + mpImplData->maPropertyToIndex.find( i_rProperty ); + return it != mpImplData->maPropertyToIndex.end() ? mpImplData->maUIPropertyEnabled[it->second] : false; +} + +void PrinterListener::setOptionChangeHdl( const Link& i_rHdl ) { + mpImplData->maOptionChangeHdl = i_rHdl; } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9270562358be..29f9bcee7c71 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -41,7 +41,12 @@ #include "rtl/ustrbuf.hxx" +#include "com/sun/star/awt/Size.hpp" + using namespace vcl; +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ) @@ -193,12 +198,23 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetOptionChangeHdl( LINK( this, PrintDialog, UIOptionsChanged ) ); + // setup dependencies checkControlDependencies(); } PrintDialog::~PrintDialog() { + while( ! maControls.empty() ) + { + delete maControls.front(); + maControls.pop_front(); + } } bool PrintDialog::isPrintToFile() @@ -230,6 +246,177 @@ MultiSelection PrintDialog::getPageSelection() return MultiSelection(); } +void PrintDialog::setupOptionalUI() +{ + Window* pCurParent = 0; + long nCurY = 0; + USHORT nOptPageId = 9; + MapMode aFontMapMode( MAP_APPFONT ); + + Size aTabSize = maTabCtrl.GetSizePixel(); + const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); + for( int i = 0; i < rOptions.getLength(); i++ ) + { + Sequence< beans::PropertyValue > aOptProp; + rOptions[i].Value >>= aOptProp; + + // extract ui element + bool bEnabled = true; + rtl::OUString aCtrlType; + rtl::OUString aText; + rtl::OUString aPropertyName; + Sequence< rtl::OUString > aChoices; + + for( int n = 0; n < aOptProp.getLength(); n++ ) + { + const beans::PropertyValue& rEntry( aOptProp[ n ] ); + if( rEntry.Name.equalsAscii( "Text" ) ) + { + rEntry.Value >>= aText; + } + else if( rEntry.Name.equalsAscii( "ControlType" ) ) + { + rEntry.Value >>= aCtrlType; + } + else if( rEntry.Name.equalsAscii( "Choices" ) ) + { + rEntry.Value >>= aChoices; + } + else if( rEntry.Name.equalsAscii( "Property" ) ) + { + PropertyValue aVal; + rEntry.Value >>= aVal; + aPropertyName = aVal.Name; + } + else if( rEntry.Name.equalsAscii( "Enabled" ) ) + { + sal_Bool bValue = sal_True; + rEntry.Value >>= bValue; + bEnabled = bValue; + } + } + if( aCtrlType.equalsAscii( "Group" ) || + aCtrlType.equalsAscii( "Radio" ) || + aCtrlType.equalsAscii( "List" ) || + aCtrlType.equalsAscii( "Bool" ) ) + { + if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + { + // add new tab page + TabPage* pNewGroup = new TabPage( &maTabCtrl ); + maControls.push_front( pNewGroup ); + pCurParent = pNewGroup; + nCurY = 5; + pNewGroup->SetText( aText ); + maTabCtrl.InsertPage( ++nOptPageId, aText ); + maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); + } + + if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) + { + // add a check box + CheckBox* pNewBox = new CheckBox( pCurParent ); + maControls.push_front( pNewBox ); + pNewBox->SetText( aText ); + + // FIXME: measure text + pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + pNewBox->LogicToPixel( Size( 100, 10 ), aFontMapMode ) ); + nCurY += 15; + + pNewBox->Show(); + sal_Bool bVal = sal_False; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal ) + pVal->Value >>= bVal; + pNewBox->Check( bVal ); + pNewBox->Enable( maPListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); + + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); + } + else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) + { + long nXPos = 5; + + if( aText.getLength() ) + { + // add a FixedText: + FixedText* pHeading = new FixedText( pCurParent ); + maControls.push_front( pHeading ); + pHeading->SetText( aText ); + Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + aPixelSize ); + pHeading->Show(); + + nXPos = 15; + nCurY += 12; + } + + // iterate options + rtl::OUString aSelectVal; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal ) + pVal->Value >>= aSelectVal; + for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + { + RadioButton* pBtn = new RadioButton( pCurParent, m == 0 ? WB_GROUP : 0 ); + maControls.push_front( pBtn ); + pBtn->SetText( aChoices[m] ); + pBtn->Check( aChoices[m] == aSelectVal ); + Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos, 12 ), aFontMapMode ) ); + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( 15, nCurY ), aFontMapMode ), + aPixelSize ); + pBtn->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pBtn->Show(); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pBtn ) ); + nCurY += 12; + } + } + else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) + { + // add a FixedText: + FixedText* pHeading = new FixedText( pCurParent ); + maControls.push_front( pHeading ); + pHeading->SetText( aText ); + Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + aPixelSize ); + pHeading->Show(); + nCurY += 12; + + ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); + maControls.push_front( pList ); + aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + pList->SetPosSizePixel( pList->LogicToPixel( Point( 15, nCurY ), aFontMapMode), + aPixelSize ); + pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pList->Show(); + + // iterate options + for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + { + pList->InsertEntry( aChoices[m] ); + } + rtl::OUString aSelectVal; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal ) + pVal->Value >>= aSelectVal; + pList->SelectEntry( aSelectVal ); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); + } + } + else + { + DBG_ERROR( "Unsupported UI option" ); + } + } +} + void PrintDialog::checkControlDependencies() { if( maJobPage.maCopyCountField.GetValue() > 1 ) @@ -303,21 +490,23 @@ void PrintDialog::preparePreview() const MapMode aMapMode( MAP_100TH_MM ); - Size aPageSize; - JobSetup aPageSetup( aPrt->GetJobSetup() ); - maPListener->getPageParameters( mnCurPage, aPageSetup, aPageSize ); - ImplUpdateJobSetupPaper( aPageSetup ); // fill in physical paper size - Size aPaperSize( aPageSetup.ImplGetConstData()->mnPaperWidth, - aPageSetup.ImplGetConstData()->mnPaperHeight ); - if( aPageSetup.ImplGetConstData()->meOrientation == ORIENTATION_LANDSCAPE ) + aPrt->Push(); + aPrt->SetMapMode( aMapMode ); + + Size aPageSize( aPrt->GetPaperSize() ); + Sequence< PropertyValue > aPageParms( maPListener->getPageParameters( mnCurPage ) ); + for( sal_Int32 nProperty = 0, nPropertyCount = aPageParms.getLength(); nProperty < nPropertyCount; ++nProperty ) { - aPaperSize.Width() = aPageSetup.ImplGetConstData()->mnPaperHeight; - aPaperSize.Height() = aPageSetup.ImplGetConstData()->mnPaperWidth; + if( aPageParms[ nProperty ].Name.equalsIgnoreAsciiCaseAscii( "PageSize" ) ) + { + awt::Size aSize; + aPageParms[ nProperty ].Value >>= aSize; + aPageSize.Width() = aSize.Width; + aPageSize.Height() = aSize.Height; + } } - aPrt->Push(); aPrt->EnableOutput( FALSE ); - aPrt->SetMapMode( aMapMode ); GDIMetaFile aMtf; aMtf.SetPrefSize( aPageSize ); @@ -334,20 +523,20 @@ void PrintDialog::preparePreview() Point aPreviewPos = maPreviewSpace.TopLeft(); const long nW = maPreviewSpace.GetSize().Width(); const long nH = maPreviewSpace.GetSize().Height(); - if( aPaperSize.Width() > aPaperSize.Height() ) + if( aPageSize.Width() > aPageSize.Height() ) { - aPreviewSize = Size( nW, nW * aPaperSize.Height() / aPaperSize.Width() ); + aPreviewSize = Size( nW, nW * aPageSize.Height() / aPageSize.Width() ); aPreviewPos.Y() += (maPreviewSpace.GetHeight() - aPreviewSize.Height())/2; } else { - aPreviewSize = Size( nH * aPaperSize.Width() / aPaperSize.Height(), nH ); + aPreviewSize = Size( nH * aPageSize.Width() / aPageSize.Height(), nH ); aPreviewPos.X() += (maPreviewSpace.GetWidth() - aPreviewSize.Width())/2; } maPreviewWindow.SetPosSizePixel( aPreviewPos, aPreviewSize ); const Size aLogicSize( maPreviewWindow.PixelToLogic( maPreviewWindow.GetSizePixel(), MapMode( MAP_100TH_MM ) ) ); - aMtf.Scale( double(aLogicSize.Width())/double(aPaperSize.Width()), - double(aLogicSize.Height())/double(aPaperSize.Height()) ); + aMtf.Scale( double(aLogicSize.Width())/double(aPageSize.Width()), + double(aLogicSize.Height())/double(aPageSize.Height()) ); maPreviewWindow.setPreview( aMtf ); } @@ -403,3 +592,21 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, EMPTYARG ) return 0; } +IMPL_LINK( PrintDialog, UIOptionsChanged, void*, i_pOption ) +{ + PropertyValue* pVal = maPListener->getValue( *reinterpret_cast< rtl::OUString* >(i_pOption) ); + if( pVal ) + { + std::pair< std::multimap< rtl::OUString, Window* >::iterator, + std::multimap< rtl::OUString, Window* >::iterator > aWindows = + maPropertyToWindowMap.equal_range( pVal->Name ); + for( std::multimap< rtl::OUString, Window* >::const_iterator it = + aWindows.first; it != aWindows.second; ++it ) + { + it->second->Enable( maPListener->isUIOptionEnabled( pVal->Name ) ); + } + } + return 0; +} + + -- cgit -- cgit From 45f81056f07d8f007e29bd13c839e65b920a24f1 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Nov 2008 14:54:11 +0000 Subject: #i92516# fix some up prop issues, add put back values --- vcl/inc/vcl/prndlg.hxx | 6 +++ vcl/source/gdi/print3.cxx | 4 +- vcl/source/window/printdlg.cxx | 102 ++++++++++++++++++++++++++++++++++++----- 3 files changed, 99 insertions(+), 13 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index cbd6125aaca9..245d0bd9748c 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -138,6 +138,7 @@ namespace vcl void updatePrinterText(); void checkControlDependencies(); void setupOptionalUI(); + com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; DECL_LINK( ScrollHdl, ScrollBar* ); DECL_LINK( ScrollEndHdl, ScrollBar* ); @@ -145,6 +146,11 @@ namespace vcl DECL_LINK( ClickHdl, Button* ); DECL_LINK( ModifyHdl, Edit* ); DECL_LINK( UIOptionsChanged, void* ); + + DECL_LINK( UIOption_CheckHdl, CheckBox* ); + DECL_LINK( UIOption_RadioHdl, RadioButton* ); + DECL_LINK( UIOption_SelectHdl, ListBox* ); + public: PrintDialog( Window*, const boost::shared_ptr< PrinterListener >& ); virtual ~PrintDialog(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 4aecf29770d9..e9468f7fe0f0 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -472,7 +472,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO rEntry.Value >>= aVal; DBG_ASSERT( mpImplData->maPropertyToIndex.find( aVal.Name ) == mpImplData->maPropertyToIndex.end(), "duplicate property entry" ); - mpImplData->maPropertyToIndex[ aVal.Name ] = i; + mpImplData->maPropertyToIndex[ aVal.Name ] = mpImplData->maUIProperties.size(); mpImplData->maUIProperties.push_back( aVal ); bHaveProperty = true; } @@ -509,7 +509,7 @@ bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) cons { std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rProperty ); - return it != mpImplData->maPropertyToIndex.end() ? mpImplData->maUIPropertyEnabled[it->second] : false; + return ((it != mpImplData->maPropertyToIndex.end()) ? mpImplData->maUIPropertyEnabled[it->second] : false); } void PrinterListener::setOptionChangeHdl( const Link& i_rHdl ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 29f9bcee7c71..6f80cd9059f6 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -295,6 +295,7 @@ void PrintDialog::setupOptionalUI() bEnabled = bValue; } } + if( aCtrlType.equalsAscii( "Group" ) || aCtrlType.equalsAscii( "Radio" ) || aCtrlType.equalsAscii( "List" ) || @@ -357,7 +358,7 @@ void PrintDialog::setupOptionalUI() // iterate options rtl::OUString aSelectVal; PropertyValue* pVal = maPListener->getValue( aPropertyName ); - if( pVal ) + if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aSelectVal; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { @@ -375,38 +376,56 @@ void PrintDialog::setupOptionalUI() nCurY += 12; } } - else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) + else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) { // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + aPixelSize.Width() += pHeading->GetTextWidth( aText ); pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); - nCurY += 12; ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); maControls.push_front( pList ); - aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); - pList->SetPosSizePixel( pList->LogicToPixel( Point( 15, nCurY ), aFontMapMode), - aPixelSize ); - pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); - pList->Show(); // iterate options + long nMaxTextWidth = 0; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { pList->InsertEntry( aChoices[m] ); + long nEntryWidth = pList->GetTextWidth( aChoices[m] ); + if( nEntryWidth > nMaxTextWidth ) + nMaxTextWidth = nEntryWidth; } + nMaxTextWidth += 30; rtl::OUString aSelectVal; PropertyValue* pVal = maPListener->getValue( aPropertyName ); - if( pVal ) + if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aSelectVal; pList->SelectEntry( aSelectVal ); + + Point aListPos; + if( nMaxTextWidth + aPixelSize.Width() < aTabSize.Width() - 10 ) + { + aListPos = pHeading->GetPosPixel(); + aListPos.X() += pHeading->GetSizePixel().Width() + 5; + } + else + { + nCurY += 12; + aListPos = pCurParent->LogicToPixel( Point( 15, nCurY ), aFontMapMode ); + } + + aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); + aPixelSize.Width() = nMaxTextWidth; + aPixelSize.Height() *= aChoices.getLength() > 15 ? 15 : aChoices.getLength(); + pList->SetPosSizePixel( aListPos, aPixelSize ); + pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pList->Show(); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); } } @@ -478,9 +497,13 @@ void PrintDialog::setPreviewText( sal_Int32 nSetPage ) void PrintDialog::preparePreview() { + // page range may have changed depending on options sal_Int32 nPages = maPListener->getPageCount(); mnCachedPages = nPages; + if( mnCurPage >= nPages ) + mnCurPage = nPages-1; + setPreviewText( mnCurPage ); maPageScrollbar.SetRange( Range( 0, nPages-1 ) ); @@ -609,4 +632,61 @@ IMPL_LINK( PrintDialog, UIOptionsChanged, void*, i_pOption ) return 0; } +PropertyValue* PrintDialog::getValueForWindow( Window* i_pWindow ) const +{ + PropertyValue* pVal = NULL; + std::map< Window*, rtl::OUString >::const_iterator it = maControlToPropertyMap.find( i_pWindow ); + if( it != maControlToPropertyMap.end() ) + { + pVal = maPListener->getValue( it->second ); + DBG_ASSERT( pVal, "property value not found" ); + } + else + { + DBG_ERROR( "changed control not in property map" ); + } + return pVal; +} + +IMPL_LINK( PrintDialog, UIOption_CheckHdl, CheckBox*, i_pBox ) +{ + PropertyValue* pVal = getValueForWindow( i_pBox ); + if( pVal ) + { + sal_Bool bVal = i_pBox->IsChecked(); + pVal->Value <<= bVal; + + // update preview and page settings + preparePreview(); + } + return 0; +} + +IMPL_LINK( PrintDialog, UIOption_RadioHdl, RadioButton*, i_pBtn ) +{ + PropertyValue* pVal = getValueForWindow( i_pBtn ); + if( pVal ) + { + rtl::OUString aVal( i_pBtn->GetText() );; + pVal->Value <<= aVal; + + // update preview and page settings + preparePreview(); + } + return 0; +} + +IMPL_LINK( PrintDialog, UIOption_SelectHdl, ListBox*, i_pBox ) +{ + PropertyValue* pVal = getValueForWindow( i_pBox ); + if( pVal ) + { + rtl::OUString aVal( i_pBox->GetSelectEntry() );; + pVal->Value <<= aVal; + + // update preview and page settings + preparePreview(); + } + return 0; +} -- cgit From b83950b29bfd4aeadf0d6dd9b1da28d48163d6f3 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Nov 2008 15:52:15 +0000 Subject: #i92516# begin sd work --- vcl/source/window/printdlg.cxx | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 6f80cd9059f6..306001e2e7a2 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -297,6 +297,7 @@ void PrintDialog::setupOptionalUI() } if( aCtrlType.equalsAscii( "Group" ) || + aCtrlType.equalsAscii( "Subgroup" ) || aCtrlType.equalsAscii( "Radio" ) || aCtrlType.equalsAscii( "List" ) || aCtrlType.equalsAscii( "Bool" ) ) @@ -313,7 +314,21 @@ void PrintDialog::setupOptionalUI() maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); } - if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) + if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) + { + FixedLine* pNewSub = new FixedLine( pCurParent ); + maControls.push_front( pNewSub ); + pNewSub->SetText( aText ); + nCurY += 4; + Size aPixelSize( aTabSize ); + aPixelSize.Width() /= 2; + aPixelSize.Height() = pCurParent->GetTextHeight() + 4; + pNewSub->SetPosSizePixel( pNewSub->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + aPixelSize ); + pNewSub->Show(); + nCurY += 12; + } + else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { // add a check box CheckBox* pNewBox = new CheckBox( pCurParent ); @@ -323,7 +338,7 @@ void PrintDialog::setupOptionalUI() // FIXME: measure text pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), pNewBox->LogicToPixel( Size( 100, 10 ), aFontMapMode ) ); - nCurY += 15; + nCurY += 12; pNewBox->Show(); sal_Bool bVal = sal_False; @@ -407,11 +422,19 @@ void PrintDialog::setupOptionalUI() pVal->Value >>= aSelectVal; pList->SelectEntry( aSelectVal ); + aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); + aPixelSize.Width() = nMaxTextWidth; + aPixelSize.Height() *= aChoices.getLength() > 15 ? 15 : aChoices.getLength(); + Point aListPos; + bool bDoAlign = false; if( nMaxTextWidth + aPixelSize.Width() < aTabSize.Width() - 10 ) { aListPos = pHeading->GetPosPixel(); aListPos.X() += pHeading->GetSizePixel().Width() + 5; + + // align heading and list box + bDoAlign = true; } else { @@ -419,14 +442,20 @@ void PrintDialog::setupOptionalUI() aListPos = pCurParent->LogicToPixel( Point( 15, nCurY ), aFontMapMode ); } - aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); - aPixelSize.Width() = nMaxTextWidth; - aPixelSize.Height() *= aChoices.getLength() > 15 ? 15 : aChoices.getLength(); pList->SetPosSizePixel( aListPos, aPixelSize ); pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pList->Show(); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); + nCurY += 16; + + if( bDoAlign ) + { + Point aPos = pHeading->GetPosPixel(); + Size aSize = pHeading->GetSizePixel(); + aPos.Y() += (pList->GetSizePixel().Height() - aSize.Height())/2; + pHeading->SetPosSizePixel( aPos, aSize ); + } } } else -- cgit From 15d5931e21971aa6e48ed4d79d460ffadf04af82 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 6 Nov 2008 15:44:05 +0000 Subject: fix a warning --- vcl/source/gdi/print3.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e9468f7fe0f0..bba5c5ad979f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -197,7 +197,7 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->getPrinter()->SetPrintFile( aFile ); } aSel = aDlg.getPageSelection(); - pListener->getPrinter()->SetCopyCount( aDlg.getCopyCount(), aDlg.isCollate() ); + pListener->getPrinter()->SetCopyCount( static_cast(aDlg.getCopyCount()), aDlg.isCollate() ); } catch( std::bad_alloc& ) { -- cgit From 35de9888cc5aabdd5e0541872bcf160ea8fd99b4 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 6 Nov 2008 15:54:09 +0000 Subject: fix a warning --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 306001e2e7a2..f87ea73f6f4f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -224,7 +224,7 @@ bool PrintDialog::isPrintToFile() int PrintDialog::getCopyCount() { - return maJobPage.maCopyCountField.GetValue(); + return static_cast(maJobPage.maCopyCountField.GetValue()); } bool PrintDialog::isCollate() -- cgit From adf0066a17538a394550237a54f6fc0027f6ed29 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 10 Nov 2008 19:55:35 +0000 Subject: #i91478# aqua implementation (continued) --- vcl/aqua/inc/aquaprintview.h | 9 +- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 596 ++++++++++++++++++++++++++ vcl/aqua/source/gdi/makefile.mk | 1 + vcl/aqua/source/gdi/salprn.cxx | 5 + 4 files changed, 610 insertions(+), 1 deletion(-) create mode 100644 vcl/aqua/source/gdi/aquaprintaccessoryview.mm diff --git a/vcl/aqua/inc/aquaprintview.h b/vcl/aqua/inc/aquaprintview.h index f879936d1435..294a6492869d 100755 --- a/vcl/aqua/inc/aquaprintview.h +++ b/vcl/aqua/inc/aquaprintview.h @@ -35,7 +35,8 @@ #include #include "postmac.h" -class ImplQPrinter; +#include "vcl/print.hxx" + class AquaSalInfoPrinter; namespace vcl { class PrinterListener; } @@ -51,5 +52,11 @@ namespace vcl { class PrinterListener; } -(void)drawRect: (NSRect)rect; @end +@interface AquaPrintAccessoryView : NSObject +{ +} ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener; +@end + #endif diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm new file mode 100644 index 000000000000..b7aa9f660dbd --- /dev/null +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -0,0 +1,596 @@ +/************************************************************************ + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: aquaprintview.mm,v $ + * $Revision: 1.5.56.1 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_vcl.hxx" + +#include "aquaprintview.h" +#include "salinst.h" +#include "vcl/print.hxx" + +#include + +using namespace vcl; +using namespace com::sun::star; +using namespace com::sun::star::beans; +using namespace com::sun::star::uno; + +#if 0 +/* below is some dark magic to inherit an NSViewController if running + on MacOS 10.5. However this is futile since as long as our base line is 10.4 + can use the deprecated method NSPrintOperation:setAccessoryView anyway. + The problem here is that as long as we're linked for 10.4, the print panel + will never show a preview and our accessory view at the same time. This is awful, + but since it was dictated by Apple that IT MUST BE SO it cannot be bad + + Anyway the code below (the load method) is really ugly, so perhaps it's better this way. +*/ + +#import + +APPKIT_EXTERN NSString *NSPrintPanelAccessorySummaryItemNameKey; +APPKIT_EXTERN NSString *NSPrintPanelAccessorySummaryItemDescriptionKey; + +#include "osl/module.h" + +@interface AquaPrintViewController : NSObject +{ + NSArray* pAry; +} ++(void)load; +-(id)init; +-(void)dealloc; +-(NSArray *)localizedSummaryItems; +-(NSSet*)keyPathsForValuesAffectingPreview; +@end + +@implementation AquaPrintViewController ++(void)load +{ + struct objc_class *pClass = (struct objc_class *)[self class]; + Class superclass = NSClassFromString(@"NSViewController"); + + if(superclass != NULL) + { + pClass->super_class = superclass; + pClass->instance_size += superclass->instance_size; + } +} + +-(id)init +{ + if( (self = [super performSelector: @selector(initWithNibName:bundle:) withObject: nil withObject: nil]) ) + { + NSObject* pKeys[] = { NSPrintPanelAccessorySummaryItemNameKey, NSPrintPanelAccessorySummaryItemDescriptionKey }; + NSObject* pVals[] = { @"the Name", @"the summary value" }; + NSDictionary* pDict = [NSDictionary dictionaryWithObjects: pVals forKeys: pKeys count: 2]; + pAry = [NSArray arrayWithObject: pDict]; + } + return self; +} + +-(void)dealloc +{ + [pAry release]; + [super dealloc]; +} + +-(NSArray *)localizedSummaryItems +{ + return pAry; +} +-(NSSet*)keyPathsForValuesAffectingPreview +{ + return [NSSet set]; +} +@end + +#endif + +class ListenerProperties +{ + vcl::PrinterListener* mpListener; + std::map< int, rtl::OUString > maTagToPropertyName; + std::map< int, rtl::OUString > maTagToValueName; + int mnNextTag; + public: + ListenerProperties( vcl::PrinterListener* i_pListener ) + : mpListener( i_pListener ), mnNextTag( 0 ) + {} + + void updatePrintJob() + { + // TODO: refresh page count etc from mpListener + } + + int addNameTag( const rtl::OUString& i_rPropertyName ) + { + int nNewTag = mnNextTag++; + maTagToPropertyName[ nNewTag ] = i_rPropertyName; + return nNewTag; + } + + int addNameAndValueTag( const rtl::OUString& i_rPropertyName, const rtl::OUString& i_rValue ) + { + int nNewTag = mnNextTag++; + maTagToPropertyName[ nNewTag ] = i_rPropertyName; + maTagToValueName[ nNewTag ] = i_rValue; + return nNewTag; + } + + void changePropertyWithNamedValue( int i_nTag ) + { + std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); + std::map< int, rtl::OUString >::const_iterator value_it = maTagToValueName.find( i_nTag ); + if( name_it != maTagToPropertyName.end() && value_it != maTagToValueName.end() ) + { + PropertyValue* pVal = mpListener->getValue( name_it->second ); + if( pVal ) + { + pVal->Value <<= value_it->second; + updatePrintJob(); + } + } + } + + void changePropertyWithBoolValue( int i_nTag, sal_Bool i_bValue ) + { + std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); + if( name_it != maTagToPropertyName.end() ) + { + PropertyValue* pVal = mpListener->getValue( name_it->second ); + if( pVal ) + { + pVal->Value <<= i_bValue; + updatePrintJob(); + } + } + } +}; + +@interface ControlTarget : NSObject +{ + ListenerProperties* mpListener; +} +-(id)initWithListenerMap: (ListenerProperties*)pListener; +-(void)triggered:(id)pSender; +-(void)dealloc; +@end + +@implementation ControlTarget +-(id)initWithListenerMap: (ListenerProperties*)pListener +{ + if( (self = [super init]) ) + { + mpListener = pListener; + } + return self; +} +-(void)triggered:(id)pSender; +{ + if( [pSender isMemberOfClass: [NSPopUpButton class]] ) + { + NSPopUpButton* pBtn = (NSPopUpButton*)pSender; + NSMenuItem* pSelected = [pBtn selectedItem]; + if( pSelected ) + { + int nTag = [pSelected tag]; + mpListener->changePropertyWithNamedValue( nTag ); + } + } + else if( [pSender isMemberOfClass: [NSButton class]] ) + { + NSButton* pBtn = (NSButton*)pSender; + int nTag = [pBtn tag]; + mpListener->changePropertyWithBoolValue( nTag, [pBtn state] == NSOnState ); + } + else if( [pSender isMemberOfClass: [NSMatrix class]] ) + { + NSObject* pObj = [(NSMatrix*)pSender selectedCell]; + if( [pObj isMemberOfClass: [NSButtonCell class]] ) + { + NSButtonCell* pCell = (NSButtonCell*)pObj; + int nTag = [pCell tag]; + mpListener->changePropertyWithNamedValue( nTag ); + } + } + else + { + DBG_ERROR( "unsupported class" ); + } +} +-(void)dealloc +{ + delete mpListener; + [super dealloc]; +} +@end + +static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) +{ + NSArray* pSubViews = [pView subviews]; + unsigned int nViews = [pSubViews count]; + NSRect aUnion = { { 0, 0 }, { 0, 0 } }; + + // get the combined frame of all subviews + for( unsigned int n = 0; n < nViews; n++ ) + { + aUnion = NSUnionRect( aUnion, [[pSubViews objectAtIndex: n] frame] ); + } + + // move everything so it will fit + for( unsigned int n = 0; n < nViews; n++ ) + { + NSView* pCurSubView = [pSubViews objectAtIndex: n]; + NSRect aFrame = [pCurSubView frame]; + aFrame.origin.x -= aUnion.origin.x - 5; + aFrame.origin.y -= aUnion.origin.y - 5; + [pCurSubView setFrame: aFrame]; + } + + // resize the view itself + aUnion.size.height += 10; + aUnion.size.width += 10; + [pView setFrameSize: aUnion.size]; + + if( aUnion.size.width > rMaxSize.width ) + rMaxSize.width = aUnion.size.width; + if( aUnion.size.height > rMaxSize.height ) + rMaxSize.height = aUnion.size.height; +} + +@implementation AquaPrintAccessoryView ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener; +{ + ListenerProperties* pListenerProperties = new ListenerProperties( pListener ); + ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; + + NSView* pCurParent = 0; + long nCurY = 0; + long nCurX = 0; + NSRect aViewFrame = { { 0, 0 }, {400, 400 } }; + NSSize aMaxTabSize = { 0, 0 }; + NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aViewFrame]; + + const Sequence< PropertyValue >& rOptions( pListener->getUIOptions() ); + for( int i = 0; i < rOptions.getLength(); i++ ) + { + Sequence< beans::PropertyValue > aOptProp; + rOptions[i].Value >>= aOptProp; + + // extract ui element + bool bEnabled = true; + rtl::OUString aCtrlType; + rtl::OUString aText; + rtl::OUString aPropertyName; + Sequence< rtl::OUString > aChoices; + + for( int n = 0; n < aOptProp.getLength(); n++ ) + { + const beans::PropertyValue& rEntry( aOptProp[ n ] ); + if( rEntry.Name.equalsAscii( "Text" ) ) + { + rEntry.Value >>= aText; + } + else if( rEntry.Name.equalsAscii( "ControlType" ) ) + { + rEntry.Value >>= aCtrlType; + } + else if( rEntry.Name.equalsAscii( "Choices" ) ) + { + rEntry.Value >>= aChoices; + } + else if( rEntry.Name.equalsAscii( "Property" ) ) + { + PropertyValue aVal; + rEntry.Value >>= aVal; + aPropertyName = aVal.Name; + } + else if( rEntry.Name.equalsAscii( "Enabled" ) ) + { + sal_Bool bValue = sal_True; + rEntry.Value >>= bValue; + bEnabled = bValue; + } + } + + if( aCtrlType.equalsAscii( "Group" ) || + aCtrlType.equalsAscii( "Subgroup" ) || + aCtrlType.equalsAscii( "Radio" ) || + aCtrlType.equalsAscii( "List" ) || + aCtrlType.equalsAscii( "Bool" ) ) + { + // since our build target is MacOSX 10.4 we can have only one accessory view + // so we have a single accessory view that is tabbed for grouping + if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + { + // set size of current parent + if( pCurParent ) + adjustViewAndChildren( pCurParent, aMaxTabSize ); + + // new tab item + if( ! aText.getLength() ) + aText = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OOo" ) ); + NSString* pLabel = CreateNSString( aText ); + NSTabViewItem* pItem = [[NSTabViewItem alloc] initWithIdentifier: pLabel ]; + [pItem setLabel: pLabel]; + [pTabView addTabViewItem: pItem]; + pCurParent = [[NSView alloc] initWithFrame: aViewFrame]; + [pItem setView: pCurParent]; + [pLabel release]; + + // reset indent + nCurX = 0; + } + + if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) + { + NSString* pText = CreateNSString( aText ); + NSRect aTextRect = { { 0, 0 }, { 300, 15 } }; + NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setEditable: NO]; + [pTextView setSelectable: NO]; + [pTextView setDrawsBackground: NO]; + [pTextView setString: pText]; + [pTextView sizeToFit]; // FIXME: this does nothing + [pCurParent addSubview: pTextView]; + + aTextRect = [pTextView frame]; + // move to nCurY + aTextRect.origin.y = nCurY - aTextRect.size.height; + [pTextView setFrame: aTextRect]; + + // update nCurY + nCurY = aTextRect.origin.y - 5; + + // set indent + nCurX = 20; + + // cleanup + [pText release]; + } + else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) + { + NSString* pText = CreateNSString( aText ); + NSRect aCheckRect = { { nCurX, 0 }, { 0, 15 } }; + NSButton* pBtn = [[NSButton alloc] initWithFrame: aCheckRect]; + [pBtn setButtonType: NSSwitchButton]; + [pBtn setTitle: pText]; + sal_Bool bVal = sal_False; + PropertyValue* pVal = pListener->getValue( aPropertyName ); + if( pVal ) + pVal->Value >>= bVal; + [pBtn setState: bVal ? NSOnState : NSOffState]; + [pBtn setEnabled: (pListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL) ? YES : NO]; + [pBtn sizeToFit]; + [pCurParent addSubview: pBtn]; + + // connect target + [pBtn setTarget: pCtrlTarget]; + [pBtn setAction: @selector(triggered:)]; + int nTag = pListenerProperties->addNameTag( aPropertyName ); + [pBtn setTag: nTag]; + + aCheckRect = [pBtn frame]; + + // move to nCurY + aCheckRect.origin.y = nCurY - aCheckRect.size.height; + [pBtn setFrame: aCheckRect]; + + // update nCurY + nCurY = aCheckRect.origin.y - 5; + + // cleanup + [pText release]; + } + else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) + { + if( aText.getLength() ) + { + // add a label + NSString* pText = CreateNSString( aText ); + NSRect aTextRect = { { nCurX, 0 }, { 300, 15 } }; + NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setEditable: NO]; + [pTextView setSelectable: NO]; + [pTextView setDrawsBackground: NO]; + [pTextView setString: pText]; + [pTextView sizeToFit]; // FIXME: this does nothing + [pCurParent addSubview: pTextView]; + + // move to nCurY + aTextRect.origin.y = nCurY - aTextRect.size.height; + [pTextView setFrame: aTextRect]; + + // update nCurY + nCurY = aTextRect.origin.y - 5; + + // cleanup + [pText release]; + } + + // setup radio matrix + NSButtonCell* pProto = [[NSButtonCell alloc] init]; + + NSRect aRadioRect = { { nCurX + 20, 0 }, { 280 - nCurX, 5*aChoices.getLength() } }; + [pProto setTitle: @"RadioButtonGroup"]; + [pProto setButtonType: NSRadioButton]; + NSMatrix* pMatrix = [[NSMatrix alloc] initWithFrame: aRadioRect + mode: NSRadioModeMatrix + prototype: (NSCell*)pProto + numberOfRows: aChoices.getLength() + numberOfColumns: 1]; + // get currently selected value + rtl::OUString aSelectVal; + PropertyValue* pVal = pListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= aSelectVal; + // set individual titles + NSArray* pCells = [pMatrix cells]; + for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + { + NSCell* pCell = [pCells objectAtIndex: m]; + NSString* pTitle = CreateNSString( aChoices[m] ); + [pCell setTitle: pTitle]; + // connect target and action + [pCell setTarget: pCtrlTarget]; + [pCell setAction: @selector(triggered:)]; + int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, aChoices[ m ] ); + [pCell setTag: nTag]; + [pTitle release]; + // set current selection + if( aSelectVal == aChoices[m] ) + [pMatrix selectCellAtRow: m column: 0]; + } + [pMatrix sizeToFit]; + aRadioRect = [pMatrix frame]; + + // move it down, so it comes to the correct position + aRadioRect.origin.y = nCurY - aRadioRect.size.height; + [pMatrix setFrame: aRadioRect]; + [pCurParent addSubview: pMatrix]; + + // update nCurY + nCurY = aRadioRect.origin.y - 5; + + + [pProto release]; + } + else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) + { + NSString* pText = CreateNSString( aText ); + + // measure the text + NSFont* pFont = [NSFont labelFontOfSize: 0]; + NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont + forKey: NSFontAttributeName]; + + NSSize aTextSize = [pText sizeWithAttributes: pDict]; + // FIXME: the only thing reliable about sizeWithAttributes is + // that the size it outputs is way too small for our NSTextView + // that would not matter so much if NSTextView's fitToSize actually + // did something out of the box, alas it doesn't. This probably needs more + // fiddling with NSTextView's and NSTextContainer's parameters, however + // since this already almost cost me my sanity a Murphy factor of 1.5 + // will have to suffice for the time being. + aTextSize.width *= 1.5; + aTextSize.height += 3; + NSRect aTextRect = { { nCurX, 0 }, aTextSize }; + NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setEditable: NO]; + [pTextView setSelectable: NO]; + [pTextView setDrawsBackground: NO]; + [pTextView setString: pText]; + [pTextView setVerticallyResizable: NO]; + [pTextView setHorizontallyResizable: YES]; + [pTextView sizeToFit]; // FIXME: this actually does nothing + [pCurParent addSubview: pTextView]; + aTextRect = [pTextView frame]; + + + NSRect aBtnRect = { { nCurX + aTextRect.size.width, 0 }, { 0, 15 } }; + NSPopUpButton* pBtn = [[NSPopUpButton alloc] initWithFrame: aBtnRect pullsDown: NO]; + // iterate options + for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + { + NSString* pItemText = CreateNSString( aChoices[m] ); + [pBtn addItemWithTitle: pItemText]; + NSMenuItem* pItem = [pBtn itemWithTitle: pItemText]; + int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, aChoices[m] ); + [pItem setTag: nTag]; + [pItemText release]; + } + + PropertyValue* pVal = pListener->getValue( aPropertyName ); + rtl::OUString aSelectVal; + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= aSelectVal; + NSString* pSelectText = CreateNSString( aSelectVal ); + [pBtn setTitle: pSelectText]; + [pSelectText release]; + [pBtn setEnabled: (pListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL) ? YES : NO]; + + [pBtn sizeToFit]; + [pCurParent addSubview: pBtn]; + + // connect target and action + [pBtn setTarget: pCtrlTarget]; + [pBtn setAction: @selector(triggered:)]; + + // move to nCurY + aBtnRect = [pBtn frame]; + aBtnRect.origin.y = nCurY - aBtnRect.size.height; + [pBtn setFrame: aBtnRect]; + + // align label + aTextRect.origin.y = aBtnRect.origin.y + (aBtnRect.size.height - aTextRect.size.height)/2; + [pTextView setFrame: aTextRect]; + + // update nCurY + nCurY = aBtnRect.origin.y - 5; + + // cleanup + [pText release]; + } + } + else + { + DBG_ERROR( "Unsupported UI option" ); + } + } + adjustViewAndChildren( pCurParent, aMaxTabSize ); + + // find the minimum needed tab size + NSSize aTabCtrlSize = [pTabView minimumSize]; + aTabCtrlSize.height += aMaxTabSize.height + 10; + if( aTabCtrlSize.width < aMaxTabSize.width + 10 ) + aTabCtrlSize.width = aMaxTabSize.width + 10; + [pTabView setFrameSize: aTabCtrlSize]; + + // set the accessory view + #if 0 + NSPrintPanel* pPanel = [pOp printPanel]; + if( [pPanel respondsToSelector: @selector(addAccessoryController:)] ) + { + // 10.5 and upward case + AquaPrintViewController* pCtrl = [[AquaPrintViewController alloc] init]; + [pCtrl performSelector: @selector(setView:) withObject: pTabView]; + [pCtrl performSelector: @selector(setTitle:) withObject: @"Test OOOOO"]; + [pPanel performSelector: @selector(addAccessoryController:) withObject: pCtrl]; + [pPanel performSelector: @selector(setOptions:) withObject: (id)(0x20001)]; + } + else + #endif + [pOp setAccessoryView: pTabView]; + + return pCtrlTarget; +} + +@end diff --git a/vcl/aqua/source/gdi/makefile.mk b/vcl/aqua/source/gdi/makefile.mk index deb6832a5525..90b5e55b82db 100644 --- a/vcl/aqua/source/gdi/makefile.mk +++ b/vcl/aqua/source/gdi/makefile.mk @@ -62,6 +62,7 @@ SLOFILES= $(SLO)$/salmathutils.obj \ $(SLO)$/salvd.obj \ $(SLO)$/salprn.obj \ $(SLO)$/aquaprintview.obj \ + $(SLO)$/aquaprintaccessoryview.obj \ $(SLO)$/salbmp.obj .IF "$(ENABLE_CAIRO)" == "TRUE" diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 09227c549874..620fc2647482 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -496,15 +496,20 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( pPrintOperation ) { + NSObject* pReleaseAfterUse = nil; bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: bShowPanel ? YES : NO]; + if( bShowPanel ) + pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener]; + bSuccess = TRUE; mbJob = true; pInst->startedPrintJob(); [pPrintOperation runOperation]; pInst->endedPrintJob(); mbJob = false; + [pReleaseAfterUse release]; } mnCurPageRangeStart = mnCurPageRangeCount = 0; -- cgit -- cgit From 76209b6a59fd6fdd8f2301c889989d06515fbdae Mon Sep 17 00:00:00 2001 From: Andre Fischer Date: Mon, 16 Mar 2009 12:27:57 +0000 Subject: #i92516# Added handlers and propery map. --- vcl/source/window/printdlg.cxx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index f87ea73f6f4f..599f27f7ae45 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -347,8 +347,10 @@ void PrintDialog::setupOptionalUI() pVal->Value >>= bVal; pNewBox->Check( bVal ); pNewBox->Enable( maPListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); + pNewBox->SetToggleHdl( LINK( this, PrintDialog, UIOption_CheckHdl ) ); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); + maControlToPropertyMap[pNewBox] = aPropertyName; } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -386,8 +388,11 @@ void PrintDialog::setupOptionalUI() pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( 15, nCurY ), aFontMapMode ), aPixelSize ); pBtn->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pBtn->SetToggleHdl( LINK( this, PrintDialog, UIOption_RadioHdl ) ); pBtn->Show(); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pBtn ) ); + maControlToPropertyMap[pBtn] = aPropertyName; + nCurY += 12; } } @@ -444,9 +449,11 @@ void PrintDialog::setupOptionalUI() pList->SetPosSizePixel( aListPos, aPixelSize ); pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); pList->Show(); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); + maControlToPropertyMap[pList] = aPropertyName; nCurY += 16; if( bDoAlign ) -- cgit From e26c7a2da1f71d947332886157b0f6b381f20d0d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 16 Mar 2009 13:18:23 +0000 Subject: #i92516# UI property value for lists and radio button groups is now numerical index in value list --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/source/window/printdlg.cxx | 25 ++++++++++++++----------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 245d0bd9748c..0a953c5d25dc 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -132,6 +132,7 @@ namespace vcl std::list< Window* > maControls; std::map< Window*, rtl::OUString > maControlToPropertyMap; std::multimap< rtl::OUString, Window* > maPropertyToWindowMap; + std::map< Window*, sal_Int32 > maControlToNumValMap; void preparePreview(); void setPreviewText( sal_Int32 ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 599f27f7ae45..9c814da63a40 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -373,16 +373,16 @@ void PrintDialog::setupOptionalUI() } // iterate options - rtl::OUString aSelectVal; + sal_Int32 nSelectVal = 0; PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= aSelectVal; + pVal->Value >>= nSelectVal; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { RadioButton* pBtn = new RadioButton( pCurParent, m == 0 ? WB_GROUP : 0 ); maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); - pBtn->Check( aChoices[m] == aSelectVal ); + pBtn->Check( m == nSelectVal ); Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos, 12 ), aFontMapMode ) ); aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( 15, nCurY ), aFontMapMode ), @@ -392,6 +392,7 @@ void PrintDialog::setupOptionalUI() pBtn->Show(); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pBtn ) ); maControlToPropertyMap[pBtn] = aPropertyName; + maControlToNumValMap[pBtn] = m; nCurY += 12; } @@ -421,11 +422,11 @@ void PrintDialog::setupOptionalUI() nMaxTextWidth = nEntryWidth; } nMaxTextWidth += 30; - rtl::OUString aSelectVal; + sal_Int32 nSelectVal = 0; PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= aSelectVal; - pList->SelectEntry( aSelectVal ); + pVal->Value >>= nSelectVal; + pList->SelectEntryPos( nSelectVal ); aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); aPixelSize.Width() = nMaxTextWidth; @@ -701,10 +702,12 @@ IMPL_LINK( PrintDialog, UIOption_CheckHdl, CheckBox*, i_pBox ) IMPL_LINK( PrintDialog, UIOption_RadioHdl, RadioButton*, i_pBtn ) { PropertyValue* pVal = getValueForWindow( i_pBtn ); - if( pVal ) + std::map< Window*, sal_Int32 >::const_iterator it = maControlToNumValMap.find( i_pBtn ); + if( pVal && it != maControlToNumValMap.end() ) { - rtl::OUString aVal( i_pBtn->GetText() );; - pVal->Value <<= aVal; + + sal_Int32 nVal = it->second; + pVal->Value <<= nVal; // update preview and page settings preparePreview(); @@ -717,8 +720,8 @@ IMPL_LINK( PrintDialog, UIOption_SelectHdl, ListBox*, i_pBox ) PropertyValue* pVal = getValueForWindow( i_pBox ); if( pVal ) { - rtl::OUString aVal( i_pBox->GetSelectEntry() );; - pVal->Value <<= aVal; + sal_Int32 nVal( i_pBox->GetSelectEntryPos() ); + pVal->Value <<= nVal; // update preview and page settings preparePreview(); -- cgit From 3c85687a7431d6cd21e09c74169258d2e4e3f2ae Mon Sep 17 00:00:00 2001 From: Andre Fischer Date: Mon, 16 Mar 2009 13:51:45 +0000 Subject: #i92516# Fixed minor compilation problem. --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9c814da63a40..389e7965d416 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -426,7 +426,7 @@ void PrintDialog::setupOptionalUI() PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; - pList->SelectEntryPos( nSelectVal ); + pList->SelectEntryPos( static_cast(nSelectVal) ); aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); aPixelSize.Width() = nMaxTextWidth; -- cgit From 60608f2a8dbdb4fac768de164aba0ef8b1b1b0b5 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 16 Mar 2009 15:13:59 +0000 Subject: #i92516# add: control dependencies (round 1) --- vcl/inc/vcl/print.hxx | 1 + vcl/inc/vcl/prndlg.hxx | 1 + vcl/source/gdi/print3.cxx | 82 ++++++++++++++++++++++++++++++++++++++++-- vcl/source/window/printdlg.cxx | 66 ++++++++++++++++++++++++---------- 4 files changed, 129 insertions(+), 21 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 9249594abb87..5acb8176213a 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -456,6 +456,7 @@ public: /* get the PorpertyValue of a Property */ com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); + const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ) const; /* return the currently active UI options. These are the same passed to setUIOptions. */ diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 0a953c5d25dc..40bd28cdf5c3 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -138,6 +138,7 @@ namespace vcl void setPreviewText( sal_Int32 ); void updatePrinterText(); void checkControlDependencies(); + void checkOptionalControlDependencies(); void setupOptionalUI(); com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index bba5c5ad979f..4fd8d0581d3c 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -60,14 +60,25 @@ using namespace vcl; class vcl::ImplPrinterListenerData { public: + struct ControlDependency + { + rtl::OUString maDependsOnName; + sal_Int32 mnDependsOnEntry; + + ControlDependency() : mnDependsOnEntry( -1 ) {} + }; + + typedef std::hash_map< rtl::OUString, size_t, rtl::OUStringHash > PropertyToIndexMap; + typedef std::hash_map< rtl::OUString, ControlDependency, rtl::OUStringHash > ControlDependencyMap; boost::shared_ptr mpPrinter; MultiSelection maSelection; Sequence< PropertyValue > maUIOptions; std::vector< PropertyValue > maUIProperties; std::vector< bool > maUIPropertyEnabled; - std::hash_map< rtl::OUString, size_t, rtl::OUStringHash > maPropertyToIndex; + PropertyToIndexMap maPropertyToIndex; Link maOptionChangeHdl; + ControlDependencyMap maControlDependencies; }; PrinterListener::PrinterListener() @@ -448,6 +459,13 @@ com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl::OUSt return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; } +const com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl::OUString& i_rProperty ) const +{ + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + mpImplData->maPropertyToIndex.find( i_rProperty ); + return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; +} + void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rOptions ) { DBG_ASSERT( mpImplData->maUIOptions.getLength() == 0, "setUIOptions called twice !" ); @@ -463,6 +481,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO i_rOptions[i].Value >>= aOptProp; bool bIsEnabled = true; bool bHaveProperty = false; + vcl::ImplPrinterListenerData::ControlDependency aDep; for( int n = 0; n < aOptProp.getLength(); n++ ) { const beans::PropertyValue& rEntry( aOptProp[ n ] ); @@ -482,9 +501,21 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO rEntry.Value >>= bValue; bIsEnabled = bValue; } + else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) + { + rEntry.Value >>= aDep.maDependsOnName; + } + else if( rEntry.Name.equalsAscii( "DependsOnEntry" ) ) + { + rEntry.Value >>= aDep.mnDependsOnEntry; + } } if( bHaveProperty ) + { mpImplData->maUIPropertyEnabled.push_back( bIsEnabled ); + if( aDep.maDependsOnName.getLength() > 0 ) + mpImplData->maControlDependencies[ mpImplData->maUIProperties.back().Name ] = aDep; + } } } @@ -507,9 +538,56 @@ void PrinterListener::enableUIOption( const rtl::OUString& i_rProperty, bool i_b bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) const { + bool bEnabled = false; std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rProperty ); - return ((it != mpImplData->maPropertyToIndex.end()) ? mpImplData->maUIPropertyEnabled[it->second] : false); + if( it != mpImplData->maPropertyToIndex.end() ) + { + bEnabled = mpImplData->maUIPropertyEnabled[it->second]; + + if( bEnabled ) + { + // check control dependencies + vcl::ImplPrinterListenerData::ControlDependencyMap::const_iterator it = + mpImplData->maControlDependencies.find( i_rProperty ); + if( it != mpImplData->maControlDependencies.end() ) + { + // check if the dependency is enabled + // if the dependency is disabled, we are too + bEnabled = isUIOptionEnabled( it->second.maDependsOnName ); + + if( bEnabled ) + { + // does the dependency have the correct value ? + const com::sun::star::beans::PropertyValue* pVal = getValue( it->second.maDependsOnName ); + OSL_ENSURE( pVal, "unknown property in dependency" ); + if( pVal ) + { + sal_Int32 nDepVal; + sal_Bool bDepVal; + if( pVal->Value >>= nDepVal ) + { + bEnabled = (nDepVal == it->second.mnDependsOnEntry); + } + else if( pVal->Value >>= bDepVal ) + { + // could be a dependency on a checked boolean + // in this case the dependency is on a non zero for checked value + bEnabled = ( bDepVal && it->second.mnDependsOnEntry != 0) || + ( ! bDepVal && it->second.mnDependsOnEntry == 0); + } + else + { + // if the type does not match something is awry + OSL_ENSURE( 0, "strange type in control dependency" ); + bEnabled = false; + } + } + } + } + } + } + return bEnabled; } void PrinterListener::setOptionChangeHdl( const Link& i_rHdl ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 389e7965d416..afe5f699c634 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -249,7 +249,7 @@ MultiSelection PrintDialog::getPageSelection() void PrintDialog::setupOptionalUI() { Window* pCurParent = 0; - long nCurY = 0; + long nCurY = 0, nXPos = 5; USHORT nOptPageId = 9; MapMode aFontMapMode( MAP_APPFONT ); @@ -266,6 +266,7 @@ void PrintDialog::setupOptionalUI() rtl::OUString aText; rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; + bool bDependency = false; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -294,6 +295,10 @@ void PrintDialog::setupOptionalUI() rEntry.Value >>= bValue; bEnabled = bValue; } + else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) + { + bDependency = true; + } } if( aCtrlType.equalsAscii( "Group" ) || @@ -309,6 +314,7 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pNewGroup ); pCurParent = pNewGroup; nCurY = 5; + nXPos = 5; pNewGroup->SetText( aText ); maTabCtrl.InsertPage( ++nOptPageId, aText ); maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); @@ -316,6 +322,7 @@ void PrintDialog::setupOptionalUI() if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) { + nXPos = 5; FixedLine* pNewSub = new FixedLine( pCurParent ); maControls.push_front( pNewSub ); pNewSub->SetText( aText ); @@ -323,20 +330,24 @@ void PrintDialog::setupOptionalUI() Size aPixelSize( aTabSize ); aPixelSize.Width() /= 2; aPixelSize.Height() = pCurParent->GetTextHeight() + 4; - pNewSub->SetPosSizePixel( pNewSub->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + pNewSub->SetPosSizePixel( pNewSub->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), aPixelSize ); pNewSub->Show(); nCurY += 12; + nXPos += 5; } else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { + if( bDependency ) + nXPos += 5; + // add a check box CheckBox* pNewBox = new CheckBox( pCurParent ); maControls.push_front( pNewBox ); pNewBox->SetText( aText ); // FIXME: measure text - pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), pNewBox->LogicToPixel( Size( 100, 10 ), aFontMapMode ) ); nCurY += 12; @@ -351,11 +362,13 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); maControlToPropertyMap[pNewBox] = aPropertyName; + + if( bDependency ) + nXPos -= 5; } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { - long nXPos = 5; - + long nOldXPos = nXPos; if( aText.getLength() ) { // add a FixedText: @@ -368,7 +381,7 @@ void PrintDialog::setupOptionalUI() aPixelSize ); pHeading->Show(); - nXPos = 15; + nXPos += 10; nCurY += 12; } @@ -396,16 +409,20 @@ void PrintDialog::setupOptionalUI() nCurY += 12; } + nXPos = nOldXPos; } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) { + if( bDependency ) + nXPos += 5; + // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( 5, nCurY ), aFontMapMode ), + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); @@ -464,6 +481,9 @@ void PrintDialog::setupOptionalUI() aPos.Y() += (pList->GetSizePixel().Height() - aSize.Height())/2; pHeading->SetPosSizePixel( aPos, aSize ); } + + if( bDependency ) + nXPos -= 5; } } else @@ -497,6 +517,19 @@ void PrintDialog::checkControlDependencies() maPrinterPage.maSetupButton.Enable( maPListener->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ) ); } +void PrintDialog::checkOptionalControlDependencies() +{ + for( std::map< Window*, rtl::OUString >::iterator it = maControlToPropertyMap.begin(); + it != maControlToPropertyMap.end(); ++it ) + { + bool bShouldbeEnabled = maPListener->isUIOptionEnabled( it->second ); + bool bIsEnabled = it->first->IsEnabled(); + // Enable does not do a change check first, so can be less cheap than expected + if( bShouldbeEnabled != bIsEnabled ) + it->first->Enable( bShouldbeEnabled ); + } +} + void PrintDialog::updatePrinterText() { const QueueInfo* pInfo = Printer::GetQueueInfo( maPrinterPage.maPrinters.GetSelectEntry(), true ); @@ -654,18 +687,7 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, EMPTYARG ) IMPL_LINK( PrintDialog, UIOptionsChanged, void*, i_pOption ) { - PropertyValue* pVal = maPListener->getValue( *reinterpret_cast< rtl::OUString* >(i_pOption) ); - if( pVal ) - { - std::pair< std::multimap< rtl::OUString, Window* >::iterator, - std::multimap< rtl::OUString, Window* >::iterator > aWindows = - maPropertyToWindowMap.equal_range( pVal->Name ); - for( std::multimap< rtl::OUString, Window* >::const_iterator it = - aWindows.first; it != aWindows.second; ++it ) - { - it->second->Enable( maPListener->isUIOptionEnabled( pVal->Name ) ); - } - } + checkOptionalControlDependencies(); return 0; } @@ -693,6 +715,8 @@ IMPL_LINK( PrintDialog, UIOption_CheckHdl, CheckBox*, i_pBox ) sal_Bool bVal = i_pBox->IsChecked(); pVal->Value <<= bVal; + checkOptionalControlDependencies(); + // update preview and page settings preparePreview(); } @@ -709,6 +733,8 @@ IMPL_LINK( PrintDialog, UIOption_RadioHdl, RadioButton*, i_pBtn ) sal_Int32 nVal = it->second; pVal->Value <<= nVal; + checkOptionalControlDependencies(); + // update preview and page settings preparePreview(); } @@ -723,6 +749,8 @@ IMPL_LINK( PrintDialog, UIOption_SelectHdl, ListBox*, i_pBox ) sal_Int32 nVal( i_pBox->GetSelectEntryPos() ); pVal->Value <<= nVal; + checkOptionalControlDependencies(); + // update preview and page settings preparePreview(); } -- cgit From ccb652059ab56dd52dc72d91b5bc49cdbfe18d37 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 16 Mar 2009 15:22:03 +0000 Subject: #i92516# call handler only once for radio button change --- vcl/source/window/printdlg.cxx | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index afe5f699c634..ac08b8429991 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -725,18 +725,24 @@ IMPL_LINK( PrintDialog, UIOption_CheckHdl, CheckBox*, i_pBox ) IMPL_LINK( PrintDialog, UIOption_RadioHdl, RadioButton*, i_pBtn ) { - PropertyValue* pVal = getValueForWindow( i_pBtn ); - std::map< Window*, sal_Int32 >::const_iterator it = maControlToNumValMap.find( i_pBtn ); - if( pVal && it != maControlToNumValMap.end() ) + // this handler gets called for all radiobuttons that get unchecked, too + // however we only want one notificaction for the new value (that is for + // the button that gets checked) + if( i_pBtn->IsChecked() ) { + PropertyValue* pVal = getValueForWindow( i_pBtn ); + std::map< Window*, sal_Int32 >::const_iterator it = maControlToNumValMap.find( i_pBtn ); + if( pVal && it != maControlToNumValMap.end() ) + { - sal_Int32 nVal = it->second; - pVal->Value <<= nVal; + sal_Int32 nVal = it->second; + pVal->Value <<= nVal; - checkOptionalControlDependencies(); + checkOptionalControlDependencies(); - // update preview and page settings - preparePreview(); + // update preview and page settings + preparePreview(); + } } return 0; } -- cgit From 012730f704b81d31471afbe90b93915b8ce14a8d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 16 Mar 2009 17:48:45 +0000 Subject: #i92516# add range control --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/source/window/printdlg.cxx | 109 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 40bd28cdf5c3..426a9f87ed8c 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -152,6 +152,7 @@ namespace vcl DECL_LINK( UIOption_CheckHdl, CheckBox* ); DECL_LINK( UIOption_RadioHdl, RadioButton* ); DECL_LINK( UIOption_SelectHdl, ListBox* ); + DECL_LINK( UIOption_ModifyHdl, Edit* ); public: PrintDialog( Window*, const boost::shared_ptr< PrinterListener >& ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index ac08b8429991..24a861d4cc2f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -266,6 +266,7 @@ void PrintDialog::setupOptionalUI() rtl::OUString aText; rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; + sal_Int64 nMinValue = 0, nMaxValue = 0; bool bDependency = false; for( int n = 0; n < aOptProp.getLength(); n++ ) @@ -299,12 +300,21 @@ void PrintDialog::setupOptionalUI() { bDependency = true; } + else if( rEntry.Name.equalsAscii( "MinValue" ) ) + { + rEntry.Value >>= nMinValue; + } + else if( rEntry.Name.equalsAscii( "MaxValue" ) ) + { + rEntry.Value >>= nMaxValue; + } } if( aCtrlType.equalsAscii( "Group" ) || aCtrlType.equalsAscii( "Subgroup" ) || aCtrlType.equalsAscii( "Radio" ) || aCtrlType.equalsAscii( "List" ) || + aCtrlType.equalsAscii( "Range" ) || aCtrlType.equalsAscii( "Bool" ) ) { if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) @@ -482,6 +492,74 @@ void PrintDialog::setupOptionalUI() pHeading->SetPosSizePixel( aPos, aSize ); } + if( bDependency ) + nXPos -= 5; + } + else if( aCtrlType.equalsAscii( "Range" ) && pCurParent ) + { + if( bDependency ) + nXPos += 5; + + // add a FixedText: + FixedText* pHeading = new FixedText( pCurParent ); + maControls.push_front( pHeading ); + pHeading->SetText( aText ); + Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); + aPixelSize.Width() += pHeading->GetTextWidth( aText ); + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + aPixelSize ); + pHeading->Show(); + + NumericField* pField = new NumericField( pCurParent, WB_BORDER | WB_SPIN ); + maControls.push_front( pField ); + + // set min/max and current value + if( nMinValue != nMaxValue ) + { + pField->SetMin( nMinValue ); + pField->SetMax( nMaxValue ); + } + sal_Int64 nCurVal = 0; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= nCurVal; + pField->SetValue( nCurVal ); + + aPixelSize = Size( pField->LogicToPixel( Size( 80, 12 ), aFontMapMode ) ); + + Point aFieldPos; + bool bDoAlign = false; + if( aPixelSize.Width() < aTabSize.Width() - 10 ) + { + aFieldPos = pHeading->GetPosPixel(); + aFieldPos.X() += pHeading->GetSizePixel().Width() + 5; + + // align heading and list box + bDoAlign = true; + } + else + { + nCurY += 12; + aFieldPos = pCurParent->LogicToPixel( Point( 15, nCurY ), aFontMapMode ); + } + + pField->SetPosSizePixel( aFieldPos, aPixelSize ); + pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); + pField->Show(); + + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maControlToPropertyMap[pField] = aPropertyName; + nCurY += 16; + + if( bDoAlign ) + { + Point aPos = pHeading->GetPosPixel(); + Size aSize = pHeading->GetSizePixel(); + aPos.Y() += (pField->GetSizePixel().Height() - aSize.Height())/2; + pHeading->SetPosSizePixel( aPos, aSize ); + } + if( bDependency ) nXPos -= 5; } @@ -763,3 +841,34 @@ IMPL_LINK( PrintDialog, UIOption_SelectHdl, ListBox*, i_pBox ) return 0; } +IMPL_LINK( PrintDialog, UIOption_ModifyHdl, Edit*, i_pBox ) +{ + PropertyValue* pVal = getValueForWindow( i_pBox ); + if( pVal ) + { + NumericField* pNum = dynamic_cast(i_pBox); + MetricField* pMetric = dynamic_cast(i_pBox); + if( pNum ) + { + sal_Int64 nVal = pNum->GetValue(); + pVal->Value <<= nVal; + } + else if( pMetric ) + { + sal_Int64 nVal = pMetric->GetValue(); + pVal->Value <<= nVal; + } + else + { + rtl::OUString aVal( i_pBox->GetText() ); + pVal->Value <<= aVal; + } + + checkOptionalControlDependencies(); + + // update preview and page settings + preparePreview(); + } + return 0; +} + -- cgit From 38caca6fb87a3627747266a2af766f64c456a946 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 16 Mar 2009 18:11:54 +0000 Subject: #i92516# reorder jobsetup and printer controls for better usability --- vcl/inc/vcl/prndlg.hxx | 3 ++- vcl/source/src/print.src | 38 ++++++++++++++++++++++---------------- vcl/source/window/printdlg.cxx | 22 ++++++++++++++++------ 3 files changed, 40 insertions(+), 23 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 426a9f87ed8c..24695cfc20b4 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -80,7 +80,6 @@ namespace vcl FixedText maLocText; FixedText maComment; FixedText maCommentText; - CheckBox maToFileBox; PrinterTabPage( Window*, const ResId& ); virtual ~PrinterTabPage(); @@ -89,6 +88,8 @@ namespace vcl class JobTabPage : public TabPage { public: + ListBox maPrinters; + CheckBox maToFileBox; FixedLine maPrintRange; RadioButton maAllButton; RadioButton maPagesButton; diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index b85783b02ddd..61913b68a730 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -145,12 +145,6 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 50, 66 ); Size = MAP_APPFONT( 200, 10 ); }; - CheckBox SV_PRINT_PRT_TOFILE - { - Pos = MAP_APPFONT( 5, 80 ); - Size = MAP_APPFONT( 200, 12 ); - Text [en-US] = "Print to file"; - }; }; TabPage SV_PRINT_TAB_JOB @@ -158,53 +152,65 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "Job Setup"; Hide = TRUE; - FixedLine SV_PRINT_RANGE + ListBox SV_PRINT_PRINTERS { Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 200 ); + DropDown = TRUE; + }; + CheckBox SV_PRINT_PRT_TOFILE + { + Pos = MAP_APPFONT( 15, 20 ); + Size = MAP_APPFONT( 200, 12 ); + Text [en-US] = "Print to file"; + }; + FixedLine SV_PRINT_RANGE + { + Pos = MAP_APPFONT( 5, 30 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Print range"; }; RadioButton SV_PRINT_ALL { - Pos = MAP_APPFONT( 10, 15 ); + Pos = MAP_APPFONT( 10, 40 ); Size = MAP_APPFONT( 145, 15 ); Text [en-US] = "All pages"; Check = TRUE; }; RadioButton SV_PRINT_PAGERANGE { - Pos = MAP_APPFONT( 10, 30 ); + Pos = MAP_APPFONT( 10, 55 ); Size = MAP_APPFONT( 60, 15 ); Text [en-US] = "Pages"; }; Edit SV_PRINT_PAGERANGE_EDIT { - Pos = MAP_APPFONT( 70, 30 ); + Pos = MAP_APPFONT( 70, 55 ); Size = MAP_APPFONT( 80, 15 ); Border = TRUE; }; RadioButton SV_PRINT_SELECTION { - Pos = MAP_APPFONT( 10, 45 ); + Pos = MAP_APPFONT( 10, 70 ); Size = MAP_APPFONT( 145, 15 ); Text [en-US] = "Selection"; }; FixedLine SV_PRINT_COPIES { - Pos = MAP_APPFONT( 5, 70 ); + Pos = MAP_APPFONT( 5, 90 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Copies"; }; FixedText SV_PRINT_COPYCOUNT { - Pos = MAP_APPFONT( 10, 80 ); + Pos = MAP_APPFONT( 10, 100 ); Size = MAP_APPFONT( 80, 10 ); Text [en-US] = "Number of copies"; }; NumericField SV_PRINT_COPYCOUNT_FIELD { - Pos = MAP_APPFONT( 90, 80 ); + Pos = MAP_APPFONT( 90, 100 ); Size = MAP_APPFONT( 40, 10 ); Border = TRUE; Spin = TRUE; @@ -214,12 +220,12 @@ ModalDialog SV_DLG_PRINT }; FixedImage SV_PRINT_COLLATE_IMAGE { - Pos = MAP_APPFONT( 10, 100 ); + Pos = MAP_APPFONT( 10, 120 ); Size = MAP_PIXEL( 80, 30 ); }; CheckBox SV_PRINT_COLLATE { - Pos = MAP_APPFONT( 80, 100 ); + Pos = MAP_APPFONT( 80, 120 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 24a861d4cc2f..e078063dc57b 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -89,7 +89,6 @@ PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rRe , maLocText( this, VclResId( SV_PRINT_PRT_LOCATION_TXT ) ) , maComment( this, VclResId( SV_PRINT_PRT_COMMENT ) ) , maCommentText( this, VclResId( SV_PRINT_PRT_COMMENT_TXT ) ) - , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) { FreeResource(); } @@ -100,6 +99,8 @@ PrintDialog::PrinterTabPage::~PrinterTabPage() PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) + , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) + , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) , maPrintRange( this, VclResId( SV_PRINT_RANGE ) ) , maAllButton( this, VclResId( SV_PRINT_ALL ) ) , maPagesButton( this, VclResId( SV_PRINT_PAGERANGE ) ) @@ -140,10 +141,10 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) + { maPrinterPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); + maJobPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); + } else { // fall back to default printer maPrinterPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); + maJobPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); maPListener->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); } // update the text fields for the printer @@ -177,6 +183,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrGetSelectEntry() ); + maJobPage.maPrinters.SelectEntry( aNewPrinter ); + maPrinterPage.maPrinters.SelectEntry( aNewPrinter ); // set new printer - maPListener->setPrinter( boost::shared_ptr( new Printer( maPrinterPage.maPrinters.GetSelectEntry() ) ) ); + maPListener->setPrinter( boost::shared_ptr( new Printer( aNewPrinter ) ) ); // update text fields updatePrinterText(); } -- cgit From 5783a05227e2cd847680dc731c65c8f8e0587a15 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 17 Mar 2009 12:27:26 +0000 Subject: #i92516# make dialog resizeable --- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/src/print.src | 2 +- vcl/source/window/printdlg.cxx | 55 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 24695cfc20b4..a42b36dee61a 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -143,6 +143,8 @@ namespace vcl void setupOptionalUI(); com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; + virtual void Resize(); + DECL_LINK( ScrollHdl, ScrollBar* ); DECL_LINK( ScrollEndHdl, ScrollBar* ); DECL_LINK( SelectHdl, ListBox* ); diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 61913b68a730..cd214dbfd77c 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -34,7 +34,7 @@ ModalDialog SV_DLG_PRINT { Text [en-US] = "Printing"; Closeable = TRUE; - Sizeable = FALSE; + Sizeable = TRUE; Moveable = TRUE; SVLook = TRUE; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index e078063dc57b..1b8e044658a7 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -211,6 +211,9 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetOptionChangeHdl( LINK( this, PrintDialog, UIOptionsChanged ) ); + // set min size pixel to current size + SetMinOutputSizePixel( GetOutputSizePixel() ); + // setup dependencies checkControlDependencies(); } @@ -882,3 +885,55 @@ IMPL_LINK( PrintDialog, UIOption_ModifyHdl, Edit*, i_pBox ) return 0; } +void PrintDialog::Resize() +{ + Size aPixDiff( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); + Size aWindowSize( GetOutputSizePixel() ); + + // position buttons from lower end, right to left + Size aBtnSize( maCancelButton.GetSizePixel() ); + Rectangle aBtnRect( Point( aWindowSize.Width() - aPixDiff.Width() - aBtnSize.Width(), + aWindowSize.Height() - aPixDiff.Height() - aBtnSize.Height() ), + aBtnSize ); + maCancelButton.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + aBtnSize = maOKButton.GetSizePixel(); + aBtnRect = Rectangle( Point( aBtnRect.Left() - aPixDiff.Width() - aBtnSize.Width(), + aWindowSize.Height() - aPixDiff.Height() - aBtnSize.Height() ), + aBtnSize ); + maOKButton.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + aBtnSize = maButtonLine.GetSizePixel(); + + // position fixed line above buttons + aBtnRect = Rectangle( Point( 0, aBtnRect.Top() - aPixDiff.Width() - aBtnSize.Height()/2 ), + Size( aWindowSize.Width(), aBtnSize.Height() ) ); + maButtonLine.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + + // position tab control on upper right + aBtnSize = maTabCtrl.GetSizePixel(); + aBtnRect = Rectangle( Point( aWindowSize.Width() - aPixDiff.Width() - aBtnSize.Width(), + aPixDiff.Height() ), + Size( aBtnSize.Width(), maButtonLine.GetPosPixel().Y() - 2*aPixDiff.Height() ) ); + maTabCtrl.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + + // set size for preview + long nMaxX = maTabCtrl.GetPosPixel().X() - 2*aPixDiff.Width(); + long nMaxY = maButtonLine.GetPosPixel().Y() + - 2 * aPixDiff.Height() + - maPageText.GetSizePixel().Height() + - maPageScrollbar.GetSizePixel().Height(); + long nPreviewLength = std::min( nMaxX, nMaxY ); + maPreviewSpace = Rectangle( Point( aPixDiff.Width(), aPixDiff.Height() ), + Size( nPreviewLength, nPreviewLength ) ); + + // position text and scrollbar below preview + aBtnRect = Rectangle( Point( aPixDiff.Width(), 2*aPixDiff.Height() + nPreviewLength ), + Size( nPreviewLength, maPageScrollbar.GetSizePixel().Height() ) ); + maPageScrollbar.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + + aBtnRect.Top() = aBtnRect.Bottom() + aPixDiff.Height()/2; + aBtnRect.Bottom() = aBtnRect.Top() + maPageText.GetSizePixel().Height() - 1; + maPageText.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + + // and do the preview + preparePreview(); +} -- cgit From 26b3a7682ef493f20c59ae583345fcf6cc58f3d4 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 14:46:10 +0000 Subject: #i92516# add progress during printing --- vcl/aqua/source/gdi/salprn.cxx | 2 +- vcl/inc/vcl/print.hxx | 6 +-- vcl/inc/vcl/prndlg.hxx | 25 ++++++++++++ vcl/inc/vcl/svids.hrc | 4 ++ vcl/source/gdi/print3.cxx | 21 +++++++++++ vcl/source/src/print.src | 24 ++++++++++++ vcl/source/window/printdlg.cxx | 86 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 164 insertions(+), 4 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 7c24e5098f2d..959d421ae978 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -511,7 +511,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, NSObject* pReleaseAfterUse = nil; bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; - [pPrintOperation setShowsProgressPanel: bShowPanel ? YES : NO]; + [pPrintOperation setShowsProgressPanel: YES]; if( bShowPanel ) pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener]; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 5acb8176213a..5f53dd6e4a28 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -483,12 +483,12 @@ public: virtual void printPage( int i_nPage ) const = 0; // must be overloaded by the app virtual void jobFinished(); // optionally release resources bound to the job - void printFilteredPage( int i_nPage ); - - // implementation details, not usable outsid vcl + // implementation details, not usable outside vcl + void SAL_DLLPRIVATE printFilteredPage( int i_nPage ); void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); void SAL_DLLPRIVATE setPageSelection( const MultiSelection& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); + void SAL_DLLPRIVATE createProgressDialog(); }; } diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index a42b36dee61a..b832156891ed 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -166,6 +166,31 @@ namespace vcl int getCopyCount(); bool isCollate(); }; + + class PrintProgressDialog : public ModelessDialog + { + String maStr; + FixedText maText; + CancelButton maButton; + + bool mbCanceled; + int mnCur; + int mnMax; + Rectangle maProgressRect; + + DECL_LINK( ClickHdl, Button* ); + + void implCalcProgressRect(); + public: + PrintProgressDialog( Window* i_pParent, int i_nMax ); + ~PrintProgressDialog(); + + void isCanceled(); + void setProgress( int i_nCurrent, int i_nMax = -1 ); + void tick(); + + virtual void Paint( const Rectangle& ); + }; } diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index da34f04abd2c..ef4b021e1919 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -95,6 +95,10 @@ #define SV_PRINT_PRT_TOFILE 10 #define SV_PRINT_PRT_SETUP 11 +#define SV_DLG_PRINT_PROGRESS 2048 +#define SV_PRINT_PROGRESS_CANCEL 1 +#define SV_PRINT_PROGRESS_TEXT 2 + #define SV_PRINT_TAB_JOB 2 #define SV_PRINT_RANGE 1 #define SV_PRINT_ALL 2 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 4fd8d0581d3c..eb6a05e4e78e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -79,6 +79,11 @@ public: PropertyToIndexMap maPropertyToIndex; Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; + + vcl::PrintProgressDialog* mpProgress; + + ImplPrinterListenerData() : mpProgress( NULL ) {} + ~ImplPrinterListenerData() { delete mpProgress; } }; PrinterListener::PrinterListener() @@ -315,6 +320,7 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrgetPageSelection() ); + i_pListener->createProgressDialog(); for( long nPage = aSel.FirstSelected(); nPage != long(SFX_ENDOFSELECTION); nPage = aSel.NextSelected() ) { // remember MultiSelection is 1 based (due to user input) @@ -386,6 +392,13 @@ static void modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& void PrinterListener::printFilteredPage( int i_nPage ) { + // update progress if necessary + if( mpImplData->mpProgress ) + { + mpImplData->mpProgress->tick(); + Application::Reschedule( true ); + } + // get page parameters Sequence< PropertyValue > aPageParm( getPageParameters( i_nPage ) ); const MapMode aMapMode( MAP_100TH_MM ); @@ -595,3 +608,11 @@ void PrinterListener::setOptionChangeHdl( const Link& i_rHdl ) mpImplData->maOptionChangeHdl = i_rHdl; } +void PrinterListener::createProgressDialog() +{ + if( ! mpImplData->mpProgress ) + { + mpImplData->mpProgress = new PrintProgressDialog( NULL, mpImplData->maSelection.GetSelectCount() ); + mpImplData->mpProgress->Show(); + } +} diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index cd214dbfd77c..eebcdfd02298 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -251,3 +251,27 @@ ModalDialog SV_DLG_PRINT }; }; }; + +ModelessDialog SV_DLG_PRINT_PROGRESS +{ + Text [en-US] = "Printing"; + Closeable = FALSE; + Sizeable = FALSE; + Moveable = TRUE; + SVLook = TRUE; + + Size = MAP_APPFONT( 150, 100 ); + + CancelButton SV_PRINT_PROGRESS_CANCEL + { + Pos = MAP_APPFONT( 50, 80 ); + Size = MAP_APPFONT( 50, 15 ); + }; + FixedText SV_PRINT_PAGE_TXT + { + Pos = MAP_APPFONT( 5,10 ); + Size = MAP_APPFONT( 140, 10 ); + Text [ en-US ] = "Page %p of %n"; + Center = TRUE; + }; +}; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1b8e044658a7..b7ef34578964 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -38,6 +38,7 @@ #include "vcl/svids.hrc" #include "vcl/wall.hxx" #include "vcl/jobset.h" +#include "vcl/status.hxx" #include "rtl/ustrbuf.hxx" @@ -937,3 +938,88 @@ void PrintDialog::Resize() // and do the preview preparePreview(); } + +// ----------------------------------------------------------------------------- +// +// PrintProgressDialog +// +// ----------------------------------------------------------------------------- + +PrintProgressDialog::PrintProgressDialog( Window* i_pParent, int i_nMax ) : + ModelessDialog( i_pParent, VclResId( SV_DLG_PRINT_PROGRESS ) ), + maText( this, VclResId( SV_PRINT_PROGRESS_TEXT ) ), + maButton( this, VclResId( SV_PRINT_PROGRESS_CANCEL ) ), + mbCanceled( false ), + mnCur( 0 ), + mnMax( i_nMax ) +{ + maStr = maText.GetText(); + + maButton.SetClickHdl( LINK( this, PrintProgressDialog, ClickHdl ) ); + +} + +PrintProgressDialog::~PrintProgressDialog() +{ +} + +IMPL_LINK( PrintProgressDialog, ClickHdl, Button*, pButton ) +{ + if( pButton == &maButton ) + mbCanceled = true; + + return 0; +} + +void PrintProgressDialog::implCalcProgressRect() +{ + long nProgressHeight = 15; + if( IsNativeControlSupported( CTRL_PROGRESS, PART_ENTIRE_CONTROL ) ) + { + ImplControlValue aValue; + Region aControlRegion( Rectangle( Point(), Size( 100, nProgressHeight ) ) ); + Region aNativeControlRegion, aNativeContentRegion; + if( GetNativeControlRegion( CTRL_PROGRESS, PART_ENTIRE_CONTROL, aControlRegion, + CTRL_STATE_ENABLED, aValue, rtl::OUString(), + aNativeControlRegion, aNativeContentRegion ) ) + { + nProgressHeight = aNativeControlRegion.GetBoundRect().GetHeight(); + } + } + maProgressRect = Rectangle( Point( 10, maText.GetPosPixel().Y() + maText.GetSizePixel().Height() + 8 ), + Size( GetSizePixel().Width() - 20, nProgressHeight ) ); +} + +void PrintProgressDialog::setProgress( int i_nCurrent, int i_nMax ) +{ + mnCur = i_nCurrent; + if( i_nMax != -1 ) + mnMax = i_nMax; + + rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, mnCur+1 ) ); + aNewText = searchAndReplace( aNewText, "%n", 2, mnMax ); + maText.SetText( aNewText ); + + // update progress + Invalidate(); +} + +void PrintProgressDialog::tick() +{ + if( mnCur < mnMax ) + setProgress( ++mnCur ); +} + +void PrintProgressDialog::Paint( const Rectangle& i_rRect ) +{ + DrawProgress( this, maProgressRect.TopLeft(), + 0, + maProgressRect.GetWidth(), + maProgressRect.GetHeight(), + static_cast(0), + static_cast(mnCur), + static_cast(mnMax), + maProgressRect + ); + +} -- cgit From f234c2134928e11c9e08e4c97fd4e725e4675320 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 14:52:24 +0000 Subject: fix some warnings --- vcl/source/gdi/print3.cxx | 6 +++--- vcl/source/window/printdlg.cxx | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index eb6a05e4e78e..dd5de1b70482 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -552,11 +552,11 @@ void PrinterListener::enableUIOption( const rtl::OUString& i_rProperty, bool i_b bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) const { bool bEnabled = false; - std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator prop_it = mpImplData->maPropertyToIndex.find( i_rProperty ); - if( it != mpImplData->maPropertyToIndex.end() ) + if( prop_it != mpImplData->maPropertyToIndex.end() ) { - bEnabled = mpImplData->maUIPropertyEnabled[it->second]; + bEnabled = mpImplData->maUIPropertyEnabled[prop_it->second]; if( bEnabled ) { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index b7ef34578964..a70e205dc9da 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -777,7 +777,7 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, EMPTYARG ) return 0; } -IMPL_LINK( PrintDialog, UIOptionsChanged, void*, i_pOption ) +IMPL_LINK( PrintDialog, UIOptionsChanged, void*, EMPTYARG ) { checkOptionalControlDependencies(); return 0; @@ -1010,7 +1010,7 @@ void PrintProgressDialog::tick() setProgress( ++mnCur ); } -void PrintProgressDialog::Paint( const Rectangle& i_rRect ) +void PrintProgressDialog::Paint( const Rectangle& ) { DrawProgress( this, maProgressRect.TopLeft(), 0, -- cgit From 293e5da2a08ee302ead25400eea0b6f95d35c36e Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 16:16:06 +0000 Subject: #i92516# add progress during printing --- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/src/print.src | 8 +++---- vcl/source/window/printdlg.cxx | 53 ++++++++++++++++++++++++++++++++---------- 3 files changed, 47 insertions(+), 16 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index b832156891ed..11ec85c37174 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -176,7 +176,9 @@ namespace vcl bool mbCanceled; int mnCur; int mnMax; + long mnProgressHeight; Rectangle maProgressRect; + bool mbNativeProgress; DECL_LINK( ClickHdl, Button* ); diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index eebcdfd02298..e8543515d68c 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -260,17 +260,17 @@ ModelessDialog SV_DLG_PRINT_PROGRESS Moveable = TRUE; SVLook = TRUE; - Size = MAP_APPFONT( 150, 100 ); + Size = MAP_APPFONT( 120, 70 ); CancelButton SV_PRINT_PROGRESS_CANCEL { - Pos = MAP_APPFONT( 50, 80 ); + Pos = MAP_APPFONT( 35, 50 ); Size = MAP_APPFONT( 50, 15 ); }; - FixedText SV_PRINT_PAGE_TXT + FixedText SV_PRINT_PROGRESS_TEXT { Pos = MAP_APPFONT( 5,10 ); - Size = MAP_APPFONT( 140, 10 ); + Size = MAP_APPFONT( 110, 10 ); Text [ en-US ] = "Page %p of %n"; Center = TRUE; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index a70e205dc9da..3d543715532a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -39,6 +39,7 @@ #include "vcl/wall.hxx" #include "vcl/jobset.h" #include "vcl/status.hxx" +#include "vcl/decoview.hxx" #include "rtl/ustrbuf.hxx" @@ -951,7 +952,9 @@ PrintProgressDialog::PrintProgressDialog( Window* i_pParent, int i_nMax ) : maButton( this, VclResId( SV_PRINT_PROGRESS_CANCEL ) ), mbCanceled( false ), mnCur( 0 ), - mnMax( i_nMax ) + mnMax( i_nMax ), + mnProgressHeight( 15 ), + mbNativeProgress( false ) { maStr = maText.GetText(); @@ -973,35 +976,38 @@ IMPL_LINK( PrintProgressDialog, ClickHdl, Button*, pButton ) void PrintProgressDialog::implCalcProgressRect() { - long nProgressHeight = 15; if( IsNativeControlSupported( CTRL_PROGRESS, PART_ENTIRE_CONTROL ) ) { ImplControlValue aValue; - Region aControlRegion( Rectangle( Point(), Size( 100, nProgressHeight ) ) ); + Region aControlRegion( Rectangle( Point(), Size( 100, mnProgressHeight ) ) ); Region aNativeControlRegion, aNativeContentRegion; if( GetNativeControlRegion( CTRL_PROGRESS, PART_ENTIRE_CONTROL, aControlRegion, CTRL_STATE_ENABLED, aValue, rtl::OUString(), aNativeControlRegion, aNativeContentRegion ) ) { - nProgressHeight = aNativeControlRegion.GetBoundRect().GetHeight(); + mnProgressHeight = aNativeControlRegion.GetBoundRect().GetHeight(); } + mbNativeProgress = true; } maProgressRect = Rectangle( Point( 10, maText.GetPosPixel().Y() + maText.GetSizePixel().Height() + 8 ), - Size( GetSizePixel().Width() - 20, nProgressHeight ) ); + Size( GetSizePixel().Width() - 20, mnProgressHeight ) ); } void PrintProgressDialog::setProgress( int i_nCurrent, int i_nMax ) { + if( maProgressRect.IsEmpty() ) + implCalcProgressRect(); + mnCur = i_nCurrent; if( i_nMax != -1 ) mnMax = i_nMax; - rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, mnCur+1 ) ); + rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, mnCur ) ); aNewText = searchAndReplace( aNewText, "%n", 2, mnMax ); maText.SetText( aNewText ); // update progress - Invalidate(); + Invalidate( INVALIDATE_UPDATE | INVALIDATE_CHILDREN ); } void PrintProgressDialog::tick() @@ -1012,14 +1018,37 @@ void PrintProgressDialog::tick() void PrintProgressDialog::Paint( const Rectangle& ) { + Push( PUSH_LINECOLOR | PUSH_FILLCOLOR ); + const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); + Color aPrgsColor = rStyleSettings.GetHighlightColor(); + if ( aPrgsColor == rStyleSettings.GetFaceColor() ) + aPrgsColor = rStyleSettings.GetDarkShadowColor(); + SetLineColor(); + SetFillColor( aPrgsColor ); + + const int nOffset = 3; + const long nWidth = 3*mnProgressHeight/2; + const long nFullWidth = nWidth + nOffset; + const long nMaxCount = maProgressRect.GetWidth() / nFullWidth; DrawProgress( this, maProgressRect.TopLeft(), - 0, - maProgressRect.GetWidth(), - maProgressRect.GetHeight(), + nOffset, + nWidth, + mnProgressHeight, static_cast(0), - static_cast(mnCur), - static_cast(mnMax), + static_cast(10000*mnCur/mnMax), + static_cast(10000/nMaxCount), maProgressRect ); + Pop(); + if( ! mbNativeProgress ) + { + DecorationView aDecoView( this ); + Rectangle aFrameRect( maProgressRect ); + aFrameRect.Left() -= nOffset; + aFrameRect.Right() += nOffset; + aFrameRect.Top() -= nOffset; + aFrameRect.Bottom() += nOffset; + aDecoView.DrawFrame( aFrameRect ); + } } -- cgit From bc2ad9920bb0d88a9058a57364335938cfee99c7 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 17:58:15 +0000 Subject: #i92516# filter transparencies, react on user cancel --- vcl/inc/vcl/prndlg.hxx | 2 +- vcl/source/gdi/print3.cxx | 68 ++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 11ec85c37174..cba6b59e81f5 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -187,7 +187,7 @@ namespace vcl PrintProgressDialog( Window* i_pParent, int i_nMax ); ~PrintProgressDialog(); - void isCanceled(); + bool isCanceled() const { return mbCanceled; } void setProgress( int i_nCurrent, int i_nMax = -1 ); void tick(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index dd5de1b70482..887fa2ce39dd 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -395,6 +395,9 @@ void PrinterListener::printFilteredPage( int i_nPage ) // update progress if necessary if( mpImplData->mpProgress ) { + // do nothing if printing is canceled + if( mpImplData->mpProgress->isCanceled() ) + return; mpImplData->mpProgress->tick(); Application::Reschedule( true ); } @@ -411,16 +414,65 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->EnableOutput( FALSE ); - GDIMetaFile aMtf; - aMtf.Record( mpImplData->mpPrinter.get() ); + GDIMetaFile aPageFile; + aPageFile.Record( mpImplData->mpPrinter.get() ); printPage( i_nPage ); - aMtf.Stop(); - aMtf.WindStart(); + aPageFile.Stop(); + aPageFile.WindStart(); mpImplData->mpPrinter->Pop(); - // FIXME: do transparency filtering here when vcl92 is integrated + ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); + sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); + sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); + + const PrinterOptions& rPrinterOptions = mpImplData->mpPrinter->GetPrinterOptions(); + + static const sal_Int32 OPTIMAL_BMP_RESOLUTION = 300; + static const sal_Int32 NORMAL_BMP_RESOLUTION = 200; + + + if( rPrinterOptions.IsReduceBitmaps() ) + { + // calculate maximum resolution for bitmap graphics + if( PRINTER_BITMAP_OPTIMAL == rPrinterOptions.GetReducedBitmapMode() ) + { + nMaxBmpDPIX = std::min( sal_Int32(OPTIMAL_BMP_RESOLUTION), nMaxBmpDPIX ); + nMaxBmpDPIY = std::min( sal_Int32(OPTIMAL_BMP_RESOLUTION), nMaxBmpDPIY ); + } + else if( PRINTER_BITMAP_NORMAL == rPrinterOptions.GetReducedBitmapMode() ) + { + nMaxBmpDPIX = std::min( sal_Int32(NORMAL_BMP_RESOLUTION), nMaxBmpDPIX ); + nMaxBmpDPIY = std::min( sal_Int32(NORMAL_BMP_RESOLUTION), nMaxBmpDPIY ); + } + else + { + nMaxBmpDPIX = std::min( sal_Int32(rPrinterOptions.GetReducedBitmapResolution()), nMaxBmpDPIX ); + nMaxBmpDPIY = std::min( sal_Int32(rPrinterOptions.GetReducedBitmapResolution()), nMaxBmpDPIY ); + } + } + + // convert to greysacles + if( rPrinterOptions.IsConvertToGreyscales() ) + { + mpImplData->mpPrinter->SetDrawMode( mpImplData->mpPrinter->GetDrawMode() | + ( DRAWMODE_GRAYLINE | DRAWMODE_GRAYFILL | DRAWMODE_GRAYTEXT | + DRAWMODE_GRAYBITMAP | DRAWMODE_GRAYGRADIENT ) ); + } + + // disable transparency output + if( rPrinterOptions.IsReduceTransparency() && ( PRINTER_TRANSPARENCY_NONE == rPrinterOptions.GetReducedTransparencyMode() ) ) + { + mpImplData->mpPrinter->SetDrawMode( mpImplData->mpPrinter->GetDrawMode() | DRAWMODE_NOTRANSPARENCY ); + } + + GDIMetaFile aCleanedFile; + mpImplData->mpPrinter->RemoveTransparenciesFromMetaFile( aPageFile, aCleanedFile, nMaxBmpDPIX, nMaxBmpDPIY, + rPrinterOptions.IsReduceTransparency(), + rPrinterOptions.GetReducedTransparencyMode() == PRINTER_TRANSPARENCY_AUTO, + rPrinterOptions.IsReduceBitmaps() && rPrinterOptions.IsReducedBitmapIncludesTransparency() + ); mpImplData->mpPrinter->EnableOutput( TRUE ); @@ -429,11 +481,13 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->Push(); mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); - aMtf.WindStart(); - aMtf.Play( mpImplData->mpPrinter.get() ); + aCleanedFile.WindStart(); + aCleanedFile.Play( mpImplData->mpPrinter.get() ); mpImplData->mpPrinter->Pop(); mpImplData->mpPrinter->EndPage(); + + mpImplData->mpPrinter->SetDrawMode( nRestoreDrawMode ); } void PrinterListener::jobFinished() -- cgit From 66aed8209ab069db511c8007f7bb3ce99a77814b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 18:04:53 +0000 Subject: #i92516# less flicker --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 3d543715532a..17e6bcd15668 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1007,7 +1007,7 @@ void PrintProgressDialog::setProgress( int i_nCurrent, int i_nMax ) maText.SetText( aNewText ); // update progress - Invalidate( INVALIDATE_UPDATE | INVALIDATE_CHILDREN ); + Invalidate( maProgressRect, INVALIDATE_UPDATE ); } void PrintProgressDialog::tick() -- cgit From c5046bc3c7966022c3688e930f0a8937e9cc563b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 18 Mar 2009 18:05:51 +0000 Subject: #i92516# avoid warning --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 17e6bcd15668..739e9c036794 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1026,7 +1026,7 @@ void PrintProgressDialog::Paint( const Rectangle& ) SetLineColor(); SetFillColor( aPrgsColor ); - const int nOffset = 3; + const long nOffset = 3; const long nWidth = 3*mnProgressHeight/2; const long nFullWidth = nWidth + nOffset; const long nMaxCount = maProgressRect.GetWidth() / nFullWidth; -- cgit From 59637e019af5e391557f4a897c64d5bb0744f662 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 21 Mar 2009 14:18:07 +0000 Subject: solve a warning --- vcl/source/gdi/print3.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 887fa2ce39dd..88a4606dfd1a 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -630,8 +630,8 @@ bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) cons OSL_ENSURE( pVal, "unknown property in dependency" ); if( pVal ) { - sal_Int32 nDepVal; - sal_Bool bDepVal; + sal_Int32 nDepVal = 0; + sal_Bool bDepVal = sal_False; if( pVal->Value >>= nDepVal ) { bEnabled = (nDepVal == it->second.mnDependsOnEntry); -- cgit From 26be0416191c63110e51077f70c1df99ddb7525b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 24 Mar 2009 13:59:11 +0000 Subject: #i92516# page selection needs to be handled by application --- vcl/inc/vcl/print.hxx | 4 +--- vcl/inc/vcl/prndlg.hxx | 3 --- vcl/source/gdi/print3.cxx | 43 ++++++++++++++++++++---------------------- vcl/source/window/printdlg.cxx | 28 +++++++++++++-------------- 4 files changed, 35 insertions(+), 43 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index cf491dc1b4f6..66a17a14bc81 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -445,8 +445,6 @@ public: virtual ~PrinterListener(); const boost::shared_ptr& getPrinter() const; - const MultiSelection& getPageSelection() const; - /* for implementations: get current job properties as changed by e.g. print dialog this gets the current set of properties initially told to Printer::PrintJob @@ -489,9 +487,9 @@ public: // implementation details, not usable outside vcl void SAL_DLLPRIVATE printFilteredPage( int i_nPage ); void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); - void SAL_DLLPRIVATE setPageSelection( const MultiSelection& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); void SAL_DLLPRIVATE createProgressDialog(); + void SAL_DLLPRIVATE setPrintSelection( const rtl::OUString& ); }; } diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index cba6b59e81f5..3802818a3bc2 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -46,8 +46,6 @@ #include "vcl/tabctrl.hxx" #include "vcl/tabpage.hxx" -#include "tools/multisel.hxx" - #include #include @@ -162,7 +160,6 @@ namespace vcl virtual ~PrintDialog(); bool isPrintToFile(); - MultiSelection getPageSelection(); int getCopyCount(); bool isCollate(); }; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 88a4606dfd1a..6400320e0d3e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -39,7 +39,6 @@ #include "vcl/svids.hrc" #include "tools/urlobj.hxx" -#include "tools/multisel.hxx" #include "com/sun/star/ui/dialogs/XFilePicker.hpp" #include "com/sun/star/ui/dialogs/XFilterManager.hpp" @@ -72,17 +71,20 @@ public: typedef std::hash_map< rtl::OUString, ControlDependency, rtl::OUStringHash > ControlDependencyMap; boost::shared_ptr mpPrinter; - MultiSelection maSelection; Sequence< PropertyValue > maUIOptions; std::vector< PropertyValue > maUIProperties; std::vector< bool > maUIPropertyEnabled; PropertyToIndexMap maPropertyToIndex; Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; + rtl::OUString maSelectionString; vcl::PrintProgressDialog* mpProgress; - ImplPrinterListenerData() : mpProgress( NULL ) {} + ImplPrinterListenerData() : + maSelectionString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), + mpProgress( NULL ) + {} ~ImplPrinterListenerData() { delete mpProgress; } }; @@ -189,12 +191,6 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene boost::shared_ptr pPrinter( new Printer( i_rInitSetup.GetPrinterName() ) ); pListener->setPrinter( pPrinter ); - // setup page range selection - MultiSelection aSel; - int nPages = i_pListener->getPageCount(); - aSel.SetTotalRange( Range( 1, nPages ) ); - aSel.SelectAll(); - // check if the printer brings up its own dialog // in that case leave the work to that dialog if( ! pListener->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) ) @@ -212,7 +208,6 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->getPrinter()->EnablePrintFile( TRUE ); pListener->getPrinter()->SetPrintFile( aFile ); } - aSel = aDlg.getPageSelection(); pListener->getPrinter()->SetCopyCount( static_cast(aDlg.getCopyCount()), aDlg.isCollate() ); } catch( std::bad_alloc& ) @@ -220,7 +215,6 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene } } - pListener->setPageSelection( aSel ); pListener->getPrinter()->StartJob( String( RTL_CONSTASCII_USTRINGPARAM( "FIXME: no job name" ) ), pListener ); @@ -319,12 +313,12 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrgetPageSelection() ); i_pListener->createProgressDialog(); - for( long nPage = aSel.FirstSelected(); nPage != long(SFX_ENDOFSELECTION); nPage = aSel.NextSelected() ) + int nPages = i_pListener->getPageCount(); + for( int nPage = 0; nPage < nPages; nPage++ ) { // remember MultiSelection is 1 based (due to user input) - i_pListener->printFilteredPage( static_cast(nPage-1) ); + i_pListener->printFilteredPage( nPage ); } EndJob(); } @@ -356,19 +350,14 @@ const boost::shared_ptr& PrinterListener::getPrinter() const return mpImplData->mpPrinter; } -const MultiSelection& PrinterListener::getPageSelection() const -{ - return mpImplData->maSelection; -} - void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; } -void PrinterListener::setPageSelection( const MultiSelection& i_rSel ) +void PrinterListener::setPrintSelection( const rtl::OUString& i_rSel ) { - mpImplData->maSelection = i_rSel; + mpImplData->maSelectionString = i_rSel; } static void modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) @@ -497,7 +486,7 @@ void PrinterListener::jobFinished() Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const { std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; - size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size(); + size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 1; for( int i = 0; i < i_rMergeList.getLength(); i++ ) aMergeSet.insert( i_rMergeList[i].Name ); @@ -510,6 +499,14 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro if( aMergeSet.find( mpImplData->maUIProperties[i].Name ) == aMergeSet.end() ) aResult[nCur++] = mpImplData->maUIProperties[i]; } + // append page selection + if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintSelection" ) ) ) == aMergeSet.end() ) + { + PropertyValue aVal; + aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintSelection" ) ); + aVal.Value <<= mpImplData->maSelectionString; + aResult[nCur++] = aVal; + } aResult.realloc( nCur ); return aResult; } @@ -666,7 +663,7 @@ void PrinterListener::createProgressDialog() { if( ! mpImplData->mpProgress ) { - mpImplData->mpProgress = new PrintProgressDialog( NULL, mpImplData->maSelection.GetSelectCount() ); + mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCount() ); mpImplData->mpProgress->Show(); } } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 739e9c036794..f64d07a0f03f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -244,20 +244,6 @@ bool PrintDialog::isCollate() return maJobPage.maCopyCountField.GetValue() > 1 ? maJobPage.maCollateBox.IsChecked() : FALSE; } -MultiSelection PrintDialog::getPageSelection() -{ - if( maJobPage.maPagesButton.IsChecked() ) - return MultiSelection( maJobPage.maPagesEdit.GetText() ); - else if( maJobPage.maAllButton.IsChecked() ) - { - MultiSelection aSel( Range( 1, maPListener->getPageCount() ) ); - aSel.SelectAll(); - return aSel; - } - DBG_ERROR( "NYI: Selection" ); - return MultiSelection(); -} - void PrintDialog::setupOptionalUI() { Window* pCurParent = 0; @@ -769,6 +755,20 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maPListener->getPrinter()->Setup( this ); } checkControlDependencies(); + if( ( pButton == &maJobPage.maAllButton || + pButton == &maJobPage.maPagesButton || + pButton == &maJobPage.maSelectionButton ) + && ((CheckBox*)pButton)->IsChecked() ) + { + if( pButton == &maJobPage.maAllButton ) + maPListener->setPrintSelection( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ) ); + else if( pButton == &maJobPage.maPagesButton ) + maPListener->setPrintSelection( maJobPage.maPagesEdit.GetText() ); + else + maPListener->setPrintSelection( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "selection" ) ) ); + + preparePreview(); + } return 0; } -- cgit From f55d6646b5ad5051ca9a8c2dd97c2309bbed1782 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 24 Mar 2009 14:21:10 +0000 Subject: #i92516# paper orientation, free resource of progress dialog --- vcl/source/gdi/print.cxx | 2 ++ vcl/source/window/printdlg.cxx | 2 ++ 2 files changed, 4 insertions(+) diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index e8a1f5b32213..f3a89f6b6b23 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -1031,6 +1031,7 @@ void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup ) { pSetupData->mePaperFormat = ImplGetPaperFormat( rPaperInfo.m_nPaperWidth*100, rPaperInfo.m_nPaperHeight*100 ); + pSetupData->meOrientation = ORIENTATION_PORTRAIT; break; } } @@ -1053,6 +1054,7 @@ void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup ) { pSetupData->mePaperFormat = ImplGetPaperFormat( rPaperInfo.m_nPaperWidth*100, rPaperInfo.m_nPaperHeight*100 ); + pSetupData->meOrientation = ORIENTATION_LANDSCAPE; break; } } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index f64d07a0f03f..996b1d59d438 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -956,6 +956,8 @@ PrintProgressDialog::PrintProgressDialog( Window* i_pParent, int i_nMax ) : mnProgressHeight( 15 ), mbNativeProgress( false ) { + FreeResource(); + maStr = maText.GetText(); maButton.SetClickHdl( LINK( this, PrintProgressDialog, ClickHdl ) ); -- cgit From e9851ccef51bbecc4a7e3bc0ccc78e4a448de88b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 24 Mar 2009 17:51:00 +0000 Subject: #i91478# change to latest property changes --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 74 +++++++++++++++++++++------ vcl/aqua/source/gdi/salprn.cxx | 3 +- 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index b7aa9f660dbd..8c695e2ed0c4 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -118,7 +118,8 @@ class ListenerProperties { vcl::PrinterListener* mpListener; std::map< int, rtl::OUString > maTagToPropertyName; - std::map< int, rtl::OUString > maTagToValueName; + std::map< int, sal_Int32 > maTagToValueInt; + std::vector< NSObject* > maViews; int mnNextTag; public: ListenerProperties( vcl::PrinterListener* i_pListener ) @@ -128,6 +129,9 @@ class ListenerProperties void updatePrintJob() { // TODO: refresh page count etc from mpListener + + // page range may have changed depending on options + /*sal_Int32 nPages = */mpListener->getPageCount(); } int addNameTag( const rtl::OUString& i_rPropertyName ) @@ -137,19 +141,24 @@ class ListenerProperties return nNewTag; } - int addNameAndValueTag( const rtl::OUString& i_rPropertyName, const rtl::OUString& i_rValue ) + int addNameAndValueTag( const rtl::OUString& i_rPropertyName, sal_Int32 i_nValue ) { int nNewTag = mnNextTag++; maTagToPropertyName[ nNewTag ] = i_rPropertyName; - maTagToValueName[ nNewTag ] = i_rValue; + maTagToValueInt[ nNewTag ] = i_nValue; return nNewTag; } - void changePropertyWithNamedValue( int i_nTag ) + void addObservedControl( NSObject* i_pView ) + { + maViews.push_back( i_pView ); + } + + void changePropertyWithIntValue( int i_nTag ) { std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); - std::map< int, rtl::OUString >::const_iterator value_it = maTagToValueName.find( i_nTag ); - if( name_it != maTagToPropertyName.end() && value_it != maTagToValueName.end() ) + std::map< int, sal_Int32 >::const_iterator value_it = maTagToValueInt.find( i_nTag ); + if( name_it != maTagToPropertyName.end() && value_it != maTagToValueInt.end() ) { PropertyValue* pVal = mpListener->getValue( name_it->second ); if( pVal ) @@ -163,7 +172,7 @@ class ListenerProperties void changePropertyWithBoolValue( int i_nTag, sal_Bool i_bValue ) { std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); - if( name_it != maTagToPropertyName.end() ) + if( name_it != maTagToPropertyName.end() ) { PropertyValue* pVal = mpListener->getValue( name_it->second ); if( pVal ) @@ -173,6 +182,34 @@ class ListenerProperties } } } + + void updateEnableState() + { + for( std::vector< NSObject* >::iterator it = maViews.begin(); it != maViews.end(); ++it ) + { + NSObject* pObj = *it; + NSControl* pCtrl = nil; + NSCell* pCell = nil; + if( [pObj isKindOfClass: [NSControl class]] ) + pCtrl = (NSControl*)pObj; + else if( [pObj isKindOfClass: [NSCell class]] ) + pCell = (NSCell*)pObj; + + int nTag = pCtrl ? [pCtrl tag] : + pCell ? [pCell tag] : + -1; + + std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( nTag ); + if( name_it != maTagToPropertyName.end() ) + { + MacOSBOOL bEnabled = mpListener->isUIOptionEnabled( name_it->second ) ? YES : NO; + if( pCtrl ) + [pCtrl setEnabled: bEnabled]; + else if( pCell ) + [pCell setEnabled: bEnabled]; + } + } + } }; @interface ControlTarget : NSObject @@ -202,7 +239,7 @@ class ListenerProperties if( pSelected ) { int nTag = [pSelected tag]; - mpListener->changePropertyWithNamedValue( nTag ); + mpListener->changePropertyWithIntValue( nTag ); } } else if( [pSender isMemberOfClass: [NSButton class]] ) @@ -218,13 +255,14 @@ class ListenerProperties { NSButtonCell* pCell = (NSButtonCell*)pObj; int nTag = [pCell tag]; - mpListener->changePropertyWithNamedValue( nTag ); + mpListener->changePropertyWithIntValue( nTag ); } } else { DBG_ERROR( "unsupported class" ); } + mpListener->updateEnableState(); } -(void)dealloc { @@ -396,6 +434,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pBtn setTarget: pCtrlTarget]; [pBtn setAction: @selector(triggered:)]; int nTag = pListenerProperties->addNameTag( aPropertyName ); + pListenerProperties->addObservedControl( pBtn ); [pBtn setTag: nTag]; aCheckRect = [pBtn frame]; @@ -462,7 +501,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // connect target and action [pCell setTarget: pCtrlTarget]; [pCell setAction: @selector(triggered:)]; - int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, aChoices[ m ] ); + int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, m ); + pListenerProperties->addObservedControl( pCell ); [pCell setTag: nTag]; [pTitle release]; // set current selection @@ -517,25 +557,29 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSRect aBtnRect = { { nCurX + aTextRect.size.width, 0 }, { 0, 15 } }; NSPopUpButton* pBtn = [[NSPopUpButton alloc] initWithFrame: aBtnRect pullsDown: NO]; + // iterate options for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { NSString* pItemText = CreateNSString( aChoices[m] ); [pBtn addItemWithTitle: pItemText]; NSMenuItem* pItem = [pBtn itemWithTitle: pItemText]; - int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, aChoices[m] ); + int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, m ); [pItem setTag: nTag]; [pItemText release]; } PropertyValue* pVal = pListener->getValue( aPropertyName ); - rtl::OUString aSelectVal; + sal_Int32 aSelectVal = 0; if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aSelectVal; - NSString* pSelectText = CreateNSString( aSelectVal ); - [pBtn setTitle: pSelectText]; - [pSelectText release]; + [pBtn selectItemAtIndex: aSelectVal]; [pBtn setEnabled: (pListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL) ? YES : NO]; + + // add the button to observed controls for enabled state changes + // also add a tag just for this purpose + pListenerProperties->addObservedControl( pBtn ); + [pBtn setTag: pListenerProperties->addNameTag( aPropertyName )]; [pBtn sizeToFit]; [pCurParent addSubview: pBtn]; diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 959d421ae978..e11f3a6d86ba 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -496,8 +496,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, [pPath release]; } - // FIXME copies - // [pPrintDict setObject: [[NSNumber numberWithInt: (int)pQPrinter->GetCopyCount()] autorelease] forKey: NSPrintCopies]; + [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rListener.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; -- cgit From e0d8f18a7d0e462706be41c2995c36f582adb883 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 26 Mar 2009 16:42:26 +0000 Subject: #i92516# print ranges, accessory view --- vcl/aqua/inc/aquaprintview.h | 2 +- vcl/aqua/inc/salprn.h | 8 +- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 144 ++++++++++--------------- vcl/aqua/source/gdi/salprn.cxx | 147 +++++++++++++++++++------- 4 files changed, 164 insertions(+), 137 deletions(-) diff --git a/vcl/aqua/inc/aquaprintview.h b/vcl/aqua/inc/aquaprintview.h index 294a6492869d..15b0fd3751ce 100755 --- a/vcl/aqua/inc/aquaprintview.h +++ b/vcl/aqua/inc/aquaprintview.h @@ -55,7 +55,7 @@ namespace vcl { class PrinterListener; } @interface AquaPrintAccessoryView : NSObject { } -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withRestartCondition: (bool*)pbRestart; @end diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index 8bfa8ac98cae..a2f4a6f80166 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -73,8 +73,8 @@ class AquaSalInfoPrinter : public SalInfoPrinter int mnStartPageOffsetX; int mnStartPageOffsetY; - ULONG mnCurPageRangeStart; - ULONG mnCurPageRangeCount; + sal_Int32 mnCurPageRangeStart; + sal_Int32 mnCurPageRangeCount; public: AquaSalInfoPrinter( const SalPrinterQueueInfo& pInfo ); @@ -117,8 +117,8 @@ class AquaSalInfoPrinter : public SalInfoPrinter NSPrintInfo* getPrintInfo() const { return mpPrintInfo; } void setStartPageOffset( int nOffsetX, int nOffsetY ) { mnStartPageOffsetX = nOffsetX; mnStartPageOffsetY = nOffsetY; } - ULONG getCurPageRangeStart() const { return mnCurPageRangeStart; } - ULONG getCurPageRangeCount() const { return mnCurPageRangeCount; } + sal_Int32 getCurPageRangeStart() const { return mnCurPageRangeStart; } + sal_Int32 getCurPageRangeCount() const { return mnCurPageRangeCount; } private: AquaSalInfoPrinter( const AquaSalInfoPrinter& ); diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 8c695e2ed0c4..9f1b7ef64edf 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -42,78 +42,12 @@ using namespace com::sun::star; using namespace com::sun::star::beans; using namespace com::sun::star::uno; -#if 0 -/* below is some dark magic to inherit an NSViewController if running - on MacOS 10.5. However this is futile since as long as our base line is 10.4 - can use the deprecated method NSPrintOperation:setAccessoryView anyway. - The problem here is that as long as we're linked for 10.4, the print panel - will never show a preview and our accessory view at the same time. This is awful, - but since it was dictated by Apple that IT MUST BE SO it cannot be bad - - Anyway the code below (the load method) is really ugly, so perhaps it's better this way. +/* Note: the accesory view as implemented here is already deprecated in Leopard. Unfortunately + as long as our baseline is Tiger we cannot gain the advantages over multiple accessory views + as well havs haing accessory views AND a preview (as long as you are linked vs. 10.4 libraries + the preview insists on not being present. This is unfortunate. */ -#import - -APPKIT_EXTERN NSString *NSPrintPanelAccessorySummaryItemNameKey; -APPKIT_EXTERN NSString *NSPrintPanelAccessorySummaryItemDescriptionKey; - -#include "osl/module.h" - -@interface AquaPrintViewController : NSObject -{ - NSArray* pAry; -} -+(void)load; --(id)init; --(void)dealloc; --(NSArray *)localizedSummaryItems; --(NSSet*)keyPathsForValuesAffectingPreview; -@end - -@implementation AquaPrintViewController -+(void)load -{ - struct objc_class *pClass = (struct objc_class *)[self class]; - Class superclass = NSClassFromString(@"NSViewController"); - - if(superclass != NULL) - { - pClass->super_class = superclass; - pClass->instance_size += superclass->instance_size; - } -} - --(id)init -{ - if( (self = [super performSelector: @selector(initWithNibName:bundle:) withObject: nil withObject: nil]) ) - { - NSObject* pKeys[] = { NSPrintPanelAccessorySummaryItemNameKey, NSPrintPanelAccessorySummaryItemDescriptionKey }; - NSObject* pVals[] = { @"the Name", @"the summary value" }; - NSDictionary* pDict = [NSDictionary dictionaryWithObjects: pVals forKeys: pKeys count: 2]; - pAry = [NSArray arrayWithObject: pDict]; - } - return self; -} - --(void)dealloc -{ - [pAry release]; - [super dealloc]; -} - --(NSArray *)localizedSummaryItems -{ - return pAry; -} --(NSSet*)keyPathsForValuesAffectingPreview -{ - return [NSSet set]; -} -@end - -#endif - class ListenerProperties { vcl::PrinterListener* mpListener; @@ -121,17 +55,55 @@ class ListenerProperties std::map< int, sal_Int32 > maTagToValueInt; std::vector< NSObject* > maViews; int mnNextTag; + sal_Int32 mnLastPageCount; + bool* mpNeedRestart; + NSPrintOperation* mpOp; + public: - ListenerProperties( vcl::PrinterListener* i_pListener ) - : mpListener( i_pListener ), mnNextTag( 0 ) - {} + ListenerProperties( vcl::PrinterListener* i_pListener, NSPrintOperation* i_pOp, bool* i_pNeedRestart ) + : mpListener( i_pListener ), + mnNextTag( 0 ), + mnLastPageCount( i_pListener->getPageCount() ), + mpNeedRestart( i_pNeedRestart ), + mpOp( i_pOp ) + { + *mpNeedRestart = false; + } void updatePrintJob() { // TODO: refresh page count etc from mpListener // page range may have changed depending on options - /*sal_Int32 nPages = */mpListener->getPageCount(); + sal_Int32 nPages = mpListener->getPageCount(); + #if OSL_DEBUG_LEVEL > 1 + if( nPages != mnLastPageCount ) + fprintf( stderr, "trouble: number of pages changed from %ld to %ld !\n", mnLastPageCount, nPages ); + #endif + *mpNeedRestart = (nPages != mnLastPageCount); + mnLastPageCount = nPages; + if( *mpNeedRestart ) + { + // Warning: bad hack ahead + // Apple does not give as a chance of changing the page count, + // and they don't let us cancel the dialog either + // hack: send a cancel message to the window displaying our views. + // this is ugly. + for( std::vector< NSObject* >::iterator it = maViews.begin(); it != maViews.end(); ++it ) + { + if( [*it isKindOfClass: [NSView class]] ) + { + NSView* pView = (NSView*)*it; + NSWindow* pWindow = [pView window]; + if( pWindow ) + { + [pWindow cancelOperation: nil]; + break; + } + } + } + [[mpOp printInfo] setJobDisposition: NSPrintCancelJob]; + } } int addNameTag( const rtl::OUString& i_rPropertyName ) @@ -305,9 +277,13 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) } @implementation AquaPrintAccessoryView -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withRestartCondition: (bool*)pbRestart; { - ListenerProperties* pListenerProperties = new ListenerProperties( pListener ); + const Sequence< PropertyValue >& rOptions( pListener->getUIOptions() ); + if( rOptions.getLength() == 0 ) + return nil; + + ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pbRestart ); ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; NSView* pCurParent = 0; @@ -317,7 +293,6 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSSize aMaxTabSize = { 0, 0 }; NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aViewFrame]; - const Sequence< PropertyValue >& rOptions( pListener->getUIOptions() ); for( int i = 0; i < rOptions.getLength(); i++ ) { Sequence< beans::PropertyValue > aOptProp; @@ -619,20 +594,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pTabView setFrameSize: aTabCtrlSize]; // set the accessory view - #if 0 - NSPrintPanel* pPanel = [pOp printPanel]; - if( [pPanel respondsToSelector: @selector(addAccessoryController:)] ) - { - // 10.5 and upward case - AquaPrintViewController* pCtrl = [[AquaPrintViewController alloc] init]; - [pCtrl performSelector: @selector(setView:) withObject: pTabView]; - [pCtrl performSelector: @selector(setTitle:) withObject: @"Test OOOOO"]; - [pPanel performSelector: @selector(addAccessoryController:) withObject: pCtrl]; - [pPanel performSelector: @selector(setOptions:) withObject: (id)(0x20001)]; - } - else - #endif - [pOp setAccessoryView: pTabView]; + [pOp setAccessoryView: pTabView]; return pCtrlTarget; } diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index e11f3a6d86ba..e70f359bbe85 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -47,11 +47,13 @@ #include "com/sun/star/lang/XMultiServiceFactory.hpp" #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/beans/PropertyValue.hpp" +#include "com/sun/star/awt/Size.hpp" #include using namespace rtl; using namespace vcl; +using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; @@ -459,6 +461,24 @@ void AquaSalInfoPrinter::GetPageInfo( const ImplJobSetup*, } } +static Size getPageSize( vcl::PrinterListener& i_rListener, sal_Int32 i_nPage ) +{ + Size aPageSize; + Sequence< PropertyValue > aPageParms( i_rListener.getPageParameters( i_nPage ) ); + for( sal_Int32 nProperty = 0, nPropertyCount = aPageParms.getLength(); nProperty < nPropertyCount; ++nProperty ) + { + if( aPageParms[ nProperty ].Name.equalsAscii( "PageSize" ) ) + { + awt::Size aSize; + aPageParms[ nProperty].Value >>= aSize; + aPageSize.Width() = aSize.Width; + aPageSize.Height() = aSize.Height; + break; + } + } + return aPageSize; +} + BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, const String& i_rAppName, ImplJobSetup* i_pSetupData, @@ -469,59 +489,104 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, return FALSE; BOOL bSuccess = FALSE; - - // FIXME: make paper ranges work again - mnCurPageRangeStart = 1; - mnCurPageRangeCount = i_rListener.getPageCount(); - AquaSalInstance* pInst = GetSalData()->mpFirstInstance; - - mnStartPageOffsetX = mnStartPageOffsetY = 0; + bool bNeedRestart = true; + sal_Int32 nAllPages = 1; // update job data if( i_pSetupData ) SetData( ~0, i_pSetupData ); - // create view - NSView* pPrintView = [[AquaPrintView alloc] initWithListener: &i_rListener withInfoPrinter: this]; + do + { + if( bNeedRestart ) + { + mnCurPageRangeStart = 1; + mnCurPageRangeCount = 1; + nAllPages = i_rListener.getPageCount(); + } - NSMutableDictionary* pPrintDict = [mpPrintInfo dictionary]; + bNeedRestart = false; + mnCurPageRangeCount = 1; + Size aCurSize( getPageSize( i_rListener, mnCurPageRangeStart ) ); + Size aNextSize( aCurSize ); - // set filename - if( i_pFileName ) - { - [mpPrintInfo setJobDisposition: NSPrintSaveJob]; - NSString* pPath = CreateNSString( *i_pFileName ); - [pPrintDict setObject: pPath forKey: NSPrintSavePath]; - [pPath release]; - } + // print pages up to a different size + while( mnCurPageRangeCount + mnCurPageRangeStart < nAllPages ) + { + aNextSize = getPageSize( i_rListener, mnCurPageRangeStart + mnCurPageRangeCount ); + if( aCurSize == aNextSize // same page size + || + (aCurSize.Width() == aNextSize.Height() && aCurSize.Height() == aNextSize.Width()) // same size, but different orientation + ) + { + mnCurPageRangeCount++; + } + else + break; + } - [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rListener.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; - [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; - [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; - [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; + // now for the current run + mnStartPageOffsetX = mnStartPageOffsetY = 0; + // setup the paper size and orientation + if( aCurSize.Width() > aCurSize.Height() ) + { + mePageOrientation = ORIENTATION_LANDSCAPE; + long nTmp = aCurSize.Width(); + aCurSize.Width() = aCurSize.Height(); + aCurSize.Height() = nTmp; + } + else + mePageOrientation = ORIENTATION_PORTRAIT; + NSSize aPaperSize = { TenMuToPt(aCurSize.Width()), TenMuToPt(aCurSize.Height()) }; + [mpPrintInfo setPaperSize: aPaperSize]; - // create print operation - NSPrintOperation* pPrintOperation = [NSPrintOperation printOperationWithView: pPrintView printInfo: mpPrintInfo]; + // create view + NSView* pPrintView = [[AquaPrintView alloc] initWithListener: &i_rListener withInfoPrinter: this]; - if( pPrintOperation ) - { - NSObject* pReleaseAfterUse = nil; - bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); - [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; - [pPrintOperation setShowsProgressPanel: YES]; - if( bShowPanel ) - pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener]; - - bSuccess = TRUE; - mbJob = true; - pInst->startedPrintJob(); - [pPrintOperation runOperation]; - pInst->endedPrintJob(); - mbJob = false; - [pReleaseAfterUse release]; - } + NSMutableDictionary* pPrintDict = [mpPrintInfo dictionary]; + + // set filename + if( i_pFileName ) + { + [mpPrintInfo setJobDisposition: NSPrintSaveJob]; + NSString* pPath = CreateNSString( *i_pFileName ); + [pPrintDict setObject: pPath forKey: NSPrintSavePath]; + [pPath release]; + } + + [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rListener.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; + [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; + [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; + [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; + + + // create print operation + NSPrintOperation* pPrintOperation = [NSPrintOperation printOperationWithView: pPrintView printInfo: mpPrintInfo]; + + if( pPrintOperation ) + { + NSObject* pReleaseAfterUse = nil; + bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); + [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; + [pPrintOperation setShowsProgressPanel: YES]; + if( bShowPanel && mnCurPageRangeStart == 1 ) // only the first range of pages gets the accesory view + pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withRestartCondition: &bNeedRestart]; + + bSuccess = TRUE; + mbJob = true; + pInst->startedPrintJob(); + [pPrintOperation runOperation]; + pInst->endedPrintJob(); + mbJob = false; + if( pReleaseAfterUse ) + [pReleaseAfterUse release]; + } + + mnCurPageRangeStart += mnCurPageRangeCount; + mnCurPageRangeCount = 1; + } while( bNeedRestart && mnCurPageRangeCount < nAllPages ); mnCurPageRangeStart = mnCurPageRangeCount = 0; -- cgit From 1c3b1f0273aed225fa3fcc49e35f7c21a7f48d01 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 26 Mar 2009 16:48:52 +0000 Subject: #i92516# selection notification --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 996b1d59d438..2d3f35e90150 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -758,7 +758,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) if( ( pButton == &maJobPage.maAllButton || pButton == &maJobPage.maPagesButton || pButton == &maJobPage.maSelectionButton ) - && ((CheckBox*)pButton)->IsChecked() ) + && ((RadioButton*)pButton)->IsChecked() ) { if( pButton == &maJobPage.maAllButton ) maPListener->setPrintSelection( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ) ); -- cgit From a8466c6d9bdc60423ad990199ebe0ec0ab82048f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 26 Mar 2009 18:00:43 +0000 Subject: #i92516# handle page count 0 --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/inc/vcl/svids.hrc | 1 + vcl/source/src/print.src | 4 ++++ vcl/source/window/printdlg.cxx | 25 ++++++++++++++++++++----- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 3802818a3bc2..8bd4ab56141c 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -124,6 +124,7 @@ namespace vcl boost::shared_ptr< PrinterListener > maPListener; rtl::OUString maPageStr; + rtl::OUString maNoPageStr; sal_Int32 mnCurPage; sal_Int32 mnCachedPages; Rectangle maPreviewSpace; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index ef4b021e1919..b2ceb89ec4cf 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -115,6 +115,7 @@ #define SV_PRINT_NOCOLLATE_IMG 13 #define SV_PRINT_COLLATE_HC_IMG 14 #define SV_PRINT_NOCOLLATE_HC_IMG 15 +#define SV_PRINT_NOPAGES 16 #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index e8543515d68c..26454e35ec3d 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -83,6 +83,10 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 0, 165 ); Size = MAP_APPFONT( 350, 8 ); }; + String SV_PRINT_NOPAGES + { + Text [en-US] = "No pages"; + }; TabPage SV_PRINT_TAB_PRINTER { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 2d3f35e90150..8f247b2a471e 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -137,6 +137,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr= nPages ) mnCurPage = nPages-1; + if( mnCurPage < 0 ) + mnCurPage = 0; setPreviewText( mnCurPage ); - maPageScrollbar.SetRange( Range( 0, nPages-1 ) ); + maPageScrollbar.SetRange( Range( 0, nPages ) ); maPageScrollbar.SetThumbPos( mnCurPage ); + maPageScrollbar.SetVisibleSize( 1 ); boost::shared_ptr aPrt( maPListener->getPrinter() ); @@ -772,9 +782,14 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) return 0; } -IMPL_LINK( PrintDialog, ModifyHdl, Edit*, EMPTYARG ) +IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { checkControlDependencies(); + if( pEdit == &maJobPage.maPagesEdit && maJobPage.maPagesButton.IsChecked() ) + { + maPListener->setPrintSelection( maJobPage.maPagesEdit.GetText() ); + preparePreview(); + } return 0; } -- cgit From 227c5f207931e2025e85fc751e4b13cc86bb5a98 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 26 Mar 2009 18:54:45 +0000 Subject: #i92516# sizing issues --- vcl/source/window/printdlg.cxx | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 8f247b2a471e..2587d8ea6348 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -249,11 +249,11 @@ bool PrintDialog::isCollate() void PrintDialog::setupOptionalUI() { Window* pCurParent = 0; - long nCurY = 0, nXPos = 5; + long nCurY = 0, nXPos = 5, nMaxY = 0; USHORT nOptPageId = 9; MapMode aFontMapMode( MAP_APPFONT ); - Size aTabSize = maTabCtrl.GetSizePixel(); + Size aTabSize = maTabCtrl.GetTabPageSizePixel(); const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -319,6 +319,9 @@ void PrintDialog::setupOptionalUI() { if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) { + if( nCurY > nMaxY ) + nMaxY = nCurY; + // add new tab page TabPage* pNewGroup = new TabPage( &maTabCtrl ); maControls.push_front( pNewGroup ); @@ -448,7 +451,7 @@ void PrintDialog::setupOptionalUI() if( nEntryWidth > nMaxTextWidth ) nMaxTextWidth = nEntryWidth; } - nMaxTextWidth += 30; + nMaxTextWidth += 50; sal_Int32 nSelectVal = 0; PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) @@ -569,6 +572,18 @@ void PrintDialog::setupOptionalUI() DBG_ERROR( "Unsupported UI option" ); } } + + if( nCurY > nMaxY ) + nMaxY = nCurY; + + // resize dialog if necessary + Size aMaxSize( LogicToPixel( Size( nMaxY, nMaxY ), aFontMapMode ) ); + if( aMaxSize.Height() > aTabSize.Height() ) + { + Size aCurSize( GetSizePixel() ); + aCurSize.Height() += aMaxSize.Height() - aTabSize.Height(); + SetSizePixel( aCurSize ); + } } void PrintDialog::checkControlDependencies() -- cgit From 839d1453b4318bf1b8819f67e78b6f801d1041b0 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 26 Mar 2009 19:13:43 +0000 Subject: #i92516# dependency indenting --- vcl/source/window/printdlg.cxx | 56 ++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 2587d8ea6348..01828874daa1 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -267,7 +267,7 @@ void PrintDialog::setupOptionalUI() rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; sal_Int64 nMinValue = 0, nMaxValue = 0; - bool bDependency = false; + long nDependencyIndent = 0; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -298,7 +298,28 @@ void PrintDialog::setupOptionalUI() } else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) { - bDependency = true; + rtl::OUString aDepName; + rEntry.Value >>= aDepName; + std::map< rtl::OUString, Window* >::iterator it( maPropertyToWindowMap.find( aDepName ) ); + if( it != maPropertyToWindowMap.end() ) + { + Window* pWin = it->second; + // still on the same page ? + if( pWin->GetParent() == pCurParent ) + { + // is it a labeled window ? + if( dynamic_cast< ListBox* >(pWin) || + dynamic_cast< NumericField* >(pWin) ) + { + Window* pLabelWin = pWin->GetLabeledBy(); + if( dynamic_cast(pLabelWin) ) // sanity check + pWin = pLabelWin; + } + long nDependencyXPos = PixelToLogic( pWin->GetPosPixel(), aFontMapMode ).X(); + if( (nDependencyXPos + 5) > nXPos ) + nDependencyIndent = nDependencyXPos + 5 - nXPos; + } + } } else if( rEntry.Name.equalsAscii( "MinValue" ) ) { @@ -351,16 +372,13 @@ void PrintDialog::setupOptionalUI() } else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { - if( bDependency ) - nXPos += 5; - // add a check box CheckBox* pNewBox = new CheckBox( pCurParent ); maControls.push_front( pNewBox ); pNewBox->SetText( aText ); // FIXME: measure text - pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), pNewBox->LogicToPixel( Size( 100, 10 ), aFontMapMode ) ); nCurY += 12; @@ -376,8 +394,6 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); maControlToPropertyMap[pNewBox] = aPropertyName; - if( bDependency ) - nXPos -= 5; } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -390,7 +406,7 @@ void PrintDialog::setupOptionalUI() pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); @@ -409,7 +425,7 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); pBtn->Check( m == nSelectVal ); - Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos, 12 ), aFontMapMode ) ); + Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos + nDependencyIndent, 12 ), aFontMapMode ) ); aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( 15, nCurY ), aFontMapMode ), aPixelSize ); @@ -426,16 +442,13 @@ void PrintDialog::setupOptionalUI() } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) { - if( bDependency ) - nXPos += 5; - // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); @@ -475,7 +488,7 @@ void PrintDialog::setupOptionalUI() else { nCurY += 12; - aListPos = pCurParent->LogicToPixel( Point( 15, nCurY ), aFontMapMode ); + aListPos = pCurParent->LogicToPixel( Point( 15 + nDependencyIndent, nCurY ), aFontMapMode ); } pList->SetPosSizePixel( aListPos, aPixelSize ); @@ -494,22 +507,16 @@ void PrintDialog::setupOptionalUI() aPos.Y() += (pList->GetSizePixel().Height() - aSize.Height())/2; pHeading->SetPosSizePixel( aPos, aSize ); } - - if( bDependency ) - nXPos -= 5; } else if( aCtrlType.equalsAscii( "Range" ) && pCurParent ) { - if( bDependency ) - nXPos += 5; - // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); @@ -543,7 +550,7 @@ void PrintDialog::setupOptionalUI() else { nCurY += 12; - aFieldPos = pCurParent->LogicToPixel( Point( 15, nCurY ), aFontMapMode ); + aFieldPos = pCurParent->LogicToPixel( Point( 15 + nDependencyIndent, nCurY ), aFontMapMode ); } pField->SetPosSizePixel( aFieldPos, aPixelSize ); @@ -562,9 +569,6 @@ void PrintDialog::setupOptionalUI() aPos.Y() += (pField->GetSizePixel().Height() - aSize.Height())/2; pHeading->SetPosSizePixel( aPos, aSize ); } - - if( bDependency ) - nXPos -= 5; } } else -- cgit From ae603438b2a8de0c363270b162b52ca17a2d4988 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 27 Mar 2009 12:57:53 +0000 Subject: unify page metafiles --- vcl/inc/vcl/print.hxx | 3 ++ vcl/source/gdi/print3.cxx | 102 +++++++++++++++++++++++++++++++++-------- vcl/source/window/printdlg.cxx | 28 +---------- 3 files changed, 87 insertions(+), 46 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 66a17a14bc81..8ea864f3b6a5 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -485,6 +485,9 @@ public: virtual void jobFinished(); // optionally release resources bound to the job // implementation details, not usable outside vcl + int SAL_DLLPRIVATE getFilteredPageCount(); + Size SAL_DLLPRIVATE getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf ); + Size SAL_DLLPRIVATE getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ); void SAL_DLLPRIVATE printFilteredPage( int i_nPage ); void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 6400320e0d3e..e7761a8103df 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -79,10 +79,16 @@ public: ControlDependencyMap maControlDependencies; rtl::OUString maSelectionString; + int mnMultiPageRows; + int mnMultiPageColumns; + Size maMultiPageSize; + vcl::PrintProgressDialog* mpProgress; ImplPrinterListenerData() : maSelectionString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), + mnMultiPageRows( 1 ), + mnMultiPageColumns( 1 ), mpProgress( NULL ) {} ~ImplPrinterListenerData() { delete mpProgress; } @@ -353,6 +359,8 @@ const boost::shared_ptr& PrinterListener::getPrinter() const void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; + Size aPaperSize( i_rPrinter->PixelToLogic( i_rPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + mpImplData->maMultiPageSize = aPaperSize; } void PrinterListener::setPrintSelection( const rtl::OUString& i_rSel ) @@ -360,13 +368,13 @@ void PrinterListener::setPrintSelection( const rtl::OUString& i_rSel ) mpImplData->maSelectionString = i_rSel; } -static void modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) +static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) { + Size aPageSize = pPrinter->GetPaperSize(); for( sal_Int32 nProperty = 0, nPropertyCount = i_rProps.getLength(); nProperty < nPropertyCount; ++nProperty ) { if( i_rProps[ nProperty ].Name.equalsAscii( "PageSize" ) ) { - Size aPageSize; awt::Size aSize; i_rProps[ nProperty].Value >>= aSize; aPageSize.Width() = aSize.Width; @@ -377,41 +385,97 @@ static void modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& pPrinter->SetPaperSizeUser( aPageSize ); } } + return aPageSize; } -void PrinterListener::printFilteredPage( int i_nPage ) +Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) { - // update progress if necessary - if( mpImplData->mpProgress ) - { - // do nothing if printing is canceled - if( mpImplData->mpProgress->isCanceled() ) - return; - mpImplData->mpProgress->tick(); - Application::Reschedule( true ); - } + o_rMtf.Clear(); // get page parameters - Sequence< PropertyValue > aPageParm( getPageParameters( i_nPage ) ); + Sequence< PropertyValue > aPageParm( getPageParameters( i_nUnfilteredPage ) ); const MapMode aMapMode( MAP_100TH_MM ); mpImplData->mpPrinter->Push(); mpImplData->mpPrinter->SetMapMode( aMapMode ); // modify job setup if necessary - modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); + Size aPageSize = modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); + + o_rMtf.SetPrefSize( aPageSize ); + o_rMtf.SetPrefMapMode( aMapMode ); mpImplData->mpPrinter->EnableOutput( FALSE ); - GDIMetaFile aPageFile; - aPageFile.Record( mpImplData->mpPrinter.get() ); + o_rMtf.Record( mpImplData->mpPrinter.get() ); - printPage( i_nPage ); + printPage( i_nUnfilteredPage ); - aPageFile.Stop(); - aPageFile.WindStart(); + o_rMtf.Stop(); + o_rMtf.WindStart(); mpImplData->mpPrinter->Pop(); + return aPageSize; +} + +Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ) +{ + // FIXME: work in progress + int nSubPages = mpImplData->mnMultiPageRows * mpImplData->mnMultiPageColumns; + if( nSubPages < 1 ) + nSubPages = 1; + + if( nSubPages == 1 ) + return getPageFile( i_nFilteredPage, o_rMtf ); + + Size aPaperSize( mpImplData->maMultiPageSize ); + long nAdvX = aPaperSize.Width() / mpImplData->mnMultiPageColumns; + long nAdvY = aPaperSize.Height() / mpImplData->mnMultiPageRows; + Size aSubPageSize( nAdvX, nAdvY ); + + GDIMetaFile aPageFile; + aPageFile.SetPrefSize( aPaperSize ); + aPageFile.SetPrefMapMode( MapMode( MAP_100TH_MM ) ); + + int nDocPages = getPageCount(); + for( int nPage = i_nFilteredPage * nSubPages; + nPage < (i_nFilteredPage+1)*nSubPages && nPage < nDocPages; + nPage++ ) + { + GDIMetaFile aSubPageFile; + Size aPageSize = getPageFile( nPage, aSubPageFile ); + // scale the metafile down to a sub page size and move it + double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); + double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); + aSubPageFile.Scale( fScaleX, fScaleY ); + //aSubPageFile.Move( nAdvX * (nPage % mpImplData->mn + } + return aPaperSize; +} + +int PrinterListener::getFilteredPageCount() +{ + int nDiv = mpImplData->mnMultiPageRows * mpImplData->mnMultiPageColumns; + if( nDiv < 1 ) + nDiv = 1; + return (getPageCount() + (nDiv-1)) / nDiv; +} + +void PrinterListener::printFilteredPage( int i_nPage ) +{ + // update progress if necessary + if( mpImplData->mpProgress ) + { + // do nothing if printing is canceled + if( mpImplData->mpProgress->isCanceled() ) + return; + mpImplData->mpProgress->tick(); + Application::Reschedule( true ); + } + + GDIMetaFile aPageFile; + getPageFile( i_nPage, aPageFile ); + ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 01828874daa1..4e807f374bca 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -688,34 +688,8 @@ void PrintDialog::preparePreview() const MapMode aMapMode( MAP_100TH_MM ); - aPrt->Push(); - aPrt->SetMapMode( aMapMode ); - - Size aPageSize( aPrt->GetPaperSize() ); - Sequence< PropertyValue > aPageParms( maPListener->getPageParameters( mnCurPage ) ); - for( sal_Int32 nProperty = 0, nPropertyCount = aPageParms.getLength(); nProperty < nPropertyCount; ++nProperty ) - { - if( aPageParms[ nProperty ].Name.equalsIgnoreAsciiCaseAscii( "PageSize" ) ) - { - awt::Size aSize; - aPageParms[ nProperty ].Value >>= aSize; - aPageSize.Width() = aSize.Width; - aPageSize.Height() = aSize.Height; - } - } - - aPrt->EnableOutput( FALSE ); - GDIMetaFile aMtf; - aMtf.SetPrefSize( aPageSize ); - aMtf.SetPrefMapMode( aMapMode ); - aMtf.Record( &(*aPrt) ); - - maPListener->printPage( mnCurPage ); - - aMtf.Stop(); - aMtf.WindStart(); - aPrt->Pop(); + Size aPageSize = maPListener->getPageFile( mnCurPage, aMtf ); Size aPreviewSize; Point aPreviewPos = maPreviewSpace.TopLeft(); -- cgit From 71332919f5a9829758b1f150119c71c0fd5447ec Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 27 Mar 2009 23:46:53 +0000 Subject: n-up printing preparations --- vcl/source/gdi/print3.cxx | 97 ++++++++++++++++++++++++++++++++---------- vcl/source/window/printdlg.cxx | 4 +- 2 files changed, 77 insertions(+), 24 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e7761a8103df..5356c74327ed 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -37,6 +37,7 @@ #include "vcl/salinst.hxx" #include "vcl/salprn.hxx" #include "vcl/svids.hrc" +#include "vcl/metaact.hxx" #include "tools/urlobj.hxx" @@ -288,7 +289,7 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrmaGDIData.mbPrinterPullModel ) { mbJobActive = TRUE; - // sallayer does all necesseary page printing + // sallayer does all necessary page printing if( mpPrinter->StartJob( pPrintFile, Application::GetDisplayName(), maJobSetup.ImplGetConstData(), @@ -320,7 +321,7 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrcreateProgressDialog(); - int nPages = i_pListener->getPageCount(); + int nPages = i_pListener->getFilteredPageCount(); for( int nPage = 0; nPage < nPages; nPage++ ) { // remember MultiSelection is 1 based (due to user input) @@ -390,6 +391,16 @@ static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) { + // update progress if necessary + if( mpImplData->mpProgress ) + { + // do nothing if printing is canceled + if( mpImplData->mpProgress->isCanceled() ) + return Size(); + mpImplData->mpProgress->tick(); + Application::Reschedule( true ); + } + o_rMtf.Clear(); // get page parameters @@ -418,9 +429,29 @@ Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) return aPageSize; } +static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rRect, GDIMetaFile& i_rSubPage ) +{ + // save gstate + o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION ) ); + + // draw a border + o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); + o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); + o_rMtf.AddAction( new MetaRectAction( i_rRect ) ); + + // clip to page rect + o_rMtf.AddAction( new MetaISectRectClipRegionAction( i_rRect ) ); + + // append the subpage + i_rSubPage.WindStart(); + i_rSubPage.Play( o_rMtf ); + + // restore gstate + o_rMtf.AddAction( new MetaPopAction() ); +} + Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ) { - // FIXME: work in progress int nSubPages = mpImplData->mnMultiPageRows * mpImplData->mnMultiPageColumns; if( nSubPages < 1 ) nSubPages = 1; @@ -429,27 +460,52 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r return getPageFile( i_nFilteredPage, o_rMtf ); Size aPaperSize( mpImplData->maMultiPageSize ); + + // determine offsets long nAdvX = aPaperSize.Width() / mpImplData->mnMultiPageColumns; long nAdvY = aPaperSize.Height() / mpImplData->mnMultiPageRows; - Size aSubPageSize( nAdvX, nAdvY ); - GDIMetaFile aPageFile; - aPageFile.SetPrefSize( aPaperSize ); - aPageFile.SetPrefMapMode( MapMode( MAP_100TH_MM ) ); + // determine size of a "cell" subpage, leave a little space around pages + Size aSubPageSize( nAdvX - 300, nAdvY - 300 ); + + o_rMtf.Clear(); + o_rMtf.SetPrefSize( aPaperSize ); + o_rMtf.SetPrefMapMode( MapMode( MAP_100TH_MM ) ); int nDocPages = getPageCount(); - for( int nPage = i_nFilteredPage * nSubPages; + for( int nPage = i_nFilteredPage * nSubPages, nSubP = 0; nPage < (i_nFilteredPage+1)*nSubPages && nPage < nDocPages; - nPage++ ) + nPage++, nSubP++ ) { - GDIMetaFile aSubPageFile; - Size aPageSize = getPageFile( nPage, aSubPageFile ); - // scale the metafile down to a sub page size and move it - double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); - double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); - aSubPageFile.Scale( fScaleX, fScaleY ); - //aSubPageFile.Move( nAdvX * (nPage % mpImplData->mn + GDIMetaFile aPageFile; + Size aPageSize = getPageFile( nPage, aPageFile ); + if( aPageSize.Width() && aPageSize.Height() ) + { + // scale the metafile down to a sub page size + double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); + double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); + double fScale = std::min( fScaleX, fScaleY ); + aPageFile.Scale( fScale, fScale ); + aPageFile.WindStart(); + + // move the subpage so it is centered in its "cell" + long nOffX = (nAdvX - long(double(aPageSize.Width()) * fScale)) / 2; + long nOffY = (nAdvY - long(double(aPageSize.Height()) * fScale)) / 2; + long nX = nOffX + nAdvX * (nSubP % mpImplData->mnMultiPageColumns); + long nY = nOffY + nAdvY * (nSubP / mpImplData->mnMultiPageColumns); + aPageFile.Move( nX, nY ); + aPageFile.WindStart(); + // calculate border rectangle + Rectangle aSubPageRect( Point( nX - 50, nY - 50 ), + Size( long(double(aPageSize.Width())*fScale) + 100, + long(double(aPageSize.Height())*fScale) + 100 ) ); + + // append subpage to page + appendSubPage( o_rMtf, aSubPageRect, aPageFile ); + } } + o_rMtf.WindStart(); + return aPaperSize; } @@ -463,19 +519,16 @@ int PrinterListener::getFilteredPageCount() void PrinterListener::printFilteredPage( int i_nPage ) { - // update progress if necessary + GDIMetaFile aPageFile; + getFilteredPageFile( i_nPage, aPageFile ); + if( mpImplData->mpProgress ) { // do nothing if printing is canceled if( mpImplData->mpProgress->isCanceled() ) return; - mpImplData->mpProgress->tick(); - Application::Reschedule( true ); } - GDIMetaFile aPageFile; - getPageFile( i_nPage, aPageFile ); - ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 4e807f374bca..eb1a0b2e0a2c 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -670,7 +670,7 @@ void PrintDialog::setPreviewText( sal_Int32 nSetPage ) void PrintDialog::preparePreview() { // page range may have changed depending on options - sal_Int32 nPages = maPListener->getPageCount(); + sal_Int32 nPages = maPListener->getFilteredPageCount(); mnCachedPages = nPages; if( mnCurPage >= nPages ) @@ -689,7 +689,7 @@ void PrintDialog::preparePreview() const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; - Size aPageSize = maPListener->getPageFile( mnCurPage, aMtf ); + Size aPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); Size aPreviewSize; Point aPreviewPos = maPreviewSpace.TopLeft(); -- cgit From d6a769554e5d7e263f4b388784d467776bc9b548 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 28 Mar 2009 08:51:45 +0000 Subject: remove warning --- vcl/source/window/splitwin.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/splitwin.cxx b/vcl/source/window/splitwin.cxx index a7a21fb840ad..1e66849db73a 100644 --- a/vcl/source/window/splitwin.cxx +++ b/vcl/source/window/splitwin.cxx @@ -1879,7 +1879,7 @@ void SplitWindow::ImplDrawButtonRect( const Rectangle& rRect, long nSize ) DrawPixel( Point( i+1, nCenter-2+1 ), rStyleSettings.GetShadowColor() ); } i++; - if ( (i < nEx1) || (i > nEx2 ) && (i < nRight-3) ) + if ( (i < nEx1) || ((i > nEx2 ) && (i < nRight-3)) ) { DrawPixel( Point( i, nCenter+2 ), rStyleSettings.GetLightColor() ); DrawPixel( Point( i+1, nCenter+2+1 ), rStyleSettings.GetShadowColor() ); @@ -1909,7 +1909,7 @@ void SplitWindow::ImplDrawButtonRect( const Rectangle& rRect, long nSize ) DrawPixel( Point( nCenter-2+1, i+1 ), rStyleSettings.GetShadowColor() ); } i++; - if ( (i < nEx1) || (i > nEx2 ) && (i < nBottom-3) ) + if ( (i < nEx1) || ((i > nEx2 ) && (i < nBottom-3)) ) { DrawPixel( Point( nCenter+2, i ), rStyleSettings.GetLightColor() ); DrawPixel( Point( nCenter+2+1, i+1 ), rStyleSettings.GetShadowColor() ); -- cgit From d314f09fd3477c9850493e4156bf96cfeb014aad Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 28 Mar 2009 08:52:14 +0000 Subject: N-Up printing --- vcl/inc/vcl/print.hxx | 1 + vcl/inc/vcl/prndlg.hxx | 11 ++++++ vcl/inc/vcl/svids.hrc | 7 ++++ vcl/source/gdi/print3.cxx | 14 +++++++- vcl/source/src/print.src | 79 ++++++++++++++++++++++++++++++++++-------- vcl/source/window/printdlg.cxx | 45 ++++++++++++++++++++++++ 6 files changed, 142 insertions(+), 15 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 8ea864f3b6a5..727c08545cf4 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -493,6 +493,7 @@ public: void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); void SAL_DLLPRIVATE createProgressDialog(); void SAL_DLLPRIVATE setPrintSelection( const rtl::OUString& ); + void SAL_DLLPRIVATE setMultipage( int nRows, int nColumns, const Size& rPaperSize ); }; } diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 8bd4ab56141c..c44bda8a2711 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -78,6 +78,13 @@ namespace vcl FixedText maLocText; FixedText maComment; FixedText maCommentText; + FixedLine maNupLine; + FixedText maNupRowsTxt; + NumericField maNupRowsEdt; + FixedText maNupColTxt; + NumericField maNupColEdt; + RadioButton maNupPortrait; + RadioButton maNupLandscape; PrinterTabPage( Window*, const ResId& ); virtual ~PrinterTabPage(); @@ -134,6 +141,10 @@ namespace vcl std::multimap< rtl::OUString, Window* > maPropertyToWindowMap; std::map< Window*, sal_Int32 > maControlToNumValMap; + Size maNupPortraitSize; + Size maNupLandscapeSize; + + void updateNup(); void preparePreview(); void setPreviewText( sal_Int32 ); void updatePrinterText(); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index b2ceb89ec4cf..1c5f5d598faf 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -94,6 +94,13 @@ #define SV_PRINT_PRT_COMMENT_TXT 9 #define SV_PRINT_PRT_TOFILE 10 #define SV_PRINT_PRT_SETUP 11 +#define SV_PRINT_PRT_NUP 12 +#define SV_PRINT_PRT_NUP_ROWS_TXT 13 +#define SV_PRINT_PRT_NUP_ROWS_EDT 14 +#define SV_PRINT_PRT_NUP_COLUMNS_TXT 15 +#define SV_PRINT_PRT_NUP_COLUMNS_EDT 16 +#define SV_PRINT_PRT_NUP_PORTRAIT 17 +#define SV_PRINT_PRT_NUP_LANDSCAPE 18 #define SV_DLG_PRINT_PROGRESS 2048 #define SV_PRINT_PROGRESS_CANCEL 1 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 5356c74327ed..bf7c02dc775e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -324,7 +324,6 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrgetFilteredPageCount(); for( int nPage = 0; nPage < nPages; nPage++ ) { - // remember MultiSelection is 1 based (due to user input) i_pListener->printFilteredPage( nPage ); } EndJob(); @@ -440,6 +439,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rRect, GDIMet o_rMtf.AddAction( new MetaRectAction( i_rRect ) ); // clip to page rect + // FIXME: clipping does not seem to work reliably with this o_rMtf.AddAction( new MetaISectRectClipRegionAction( i_rRect ) ); // append the subpage @@ -582,6 +582,11 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->EnableOutput( TRUE ); + // in N-Up printing set the correct page size + // FIXME: setting paper landscape/portrait does not work here reliably ? + if( mpImplData->mnMultiPageRows != 1 || mpImplData->mnMultiPageColumns != 1 ) + mpImplData->mpPrinter->SetPaperSizeUser( mpImplData->maMultiPageSize ); + // actually print the page mpImplData->mpPrinter->StartPage(); @@ -784,3 +789,10 @@ void PrinterListener::createProgressDialog() mpImplData->mpProgress->Show(); } } + +void PrinterListener::setMultipage( int i_nRows, int i_nColumns, const Size& rPaperSize ) +{ + mpImplData->mnMultiPageRows = i_nRows; + mpImplData->mnMultiPageColumns = i_nColumns; + mpImplData->maMultiPageSize = rPaperSize; +} \ No newline at end of file diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 26454e35ec3d..04d9c1e02b5e 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -45,6 +45,7 @@ ModalDialog SV_DLG_PRINT DefButton = TRUE; Pos = MAP_APPFONT( 240, 175 ); Size = MAP_APPFONT( 50, 15 ); + Text [en-US] = "~Print"; }; CancelButton SV_PRINT_CANCEL { @@ -76,7 +77,7 @@ ModalDialog SV_DLG_PRINT TabControl SV_PRINT_TABCTRL { Pos = MAP_APPFONT( 140, 5 ); - Size = MAP_APPFONT( 205, 155 ); + Size = MAP_APPFONT( 205, 160 ); }; FixedLine SV_PRINT_BUTTONLINE { @@ -149,6 +150,56 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 50, 66 ); Size = MAP_APPFONT( 200, 10 ); }; + FixedLine SV_PRINT_PRT_NUP + { + Pos = MAP_APPFONT( 5, 80 ); + Size = MAP_APPFONT( 150, 10 ); + Text [en-US] = "N-Up printing"; + }; + FixedText SV_PRINT_PRT_NUP_ROWS_TXT + { + Pos = MAP_APPFONT( 10, 95 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Rows"; + }; + NumericField SV_PRINT_PRT_NUP_ROWS_EDT + { + Pos = MAP_APPFONT( 55, 95 ); + Size = MAP_APPFONT( 40, 12 ); + Border = TRUE; + Spin = TRUE; + Minimum = 1; + Maximum = 32; + Value = 1; + }; + FixedText SV_PRINT_PRT_NUP_COLUMNS_TXT + { + Pos = MAP_APPFONT( 10, 110 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "C~olumns"; + }; + NumericField SV_PRINT_PRT_NUP_COLUMNS_EDT + { + Pos = MAP_APPFONT( 55, 110 ); + Size = MAP_APPFONT( 40, 12 ); + Border = TRUE; + Spin = TRUE; + Minimum = 1; + Maximum = 32; + Value = 1; + }; + RadioButton SV_PRINT_PRT_NUP_PORTRAIT + { + Pos = MAP_APPFONT( 10, 125 ); + Size = MAP_APPFONT( 90, 10 ); + Text [en-US] = "Po~rtrait"; + }; + RadioButton SV_PRINT_PRT_NUP_LANDSCAPE + { + Pos = MAP_APPFONT( 10, 135 ); + Size = MAP_APPFONT( 90, 10 ); + Text [en-US] = "~Landscape"; + }; }; TabPage SV_PRINT_TAB_JOB @@ -164,58 +215,58 @@ ModalDialog SV_DLG_PRINT }; CheckBox SV_PRINT_PRT_TOFILE { - Pos = MAP_APPFONT( 15, 20 ); + Pos = MAP_APPFONT( 10, 20 ); Size = MAP_APPFONT( 200, 12 ); Text [en-US] = "Print to file"; }; FixedLine SV_PRINT_RANGE { - Pos = MAP_APPFONT( 5, 30 ); + Pos = MAP_APPFONT( 5, 35 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Print range"; }; RadioButton SV_PRINT_ALL { - Pos = MAP_APPFONT( 10, 40 ); + Pos = MAP_APPFONT( 10, 45 ); Size = MAP_APPFONT( 145, 15 ); Text [en-US] = "All pages"; Check = TRUE; }; RadioButton SV_PRINT_PAGERANGE { - Pos = MAP_APPFONT( 10, 55 ); + Pos = MAP_APPFONT( 10, 60 ); Size = MAP_APPFONT( 60, 15 ); Text [en-US] = "Pages"; }; Edit SV_PRINT_PAGERANGE_EDIT { - Pos = MAP_APPFONT( 70, 55 ); - Size = MAP_APPFONT( 80, 15 ); + Pos = MAP_APPFONT( 70, 60 ); + Size = MAP_APPFONT( 80, 12 ); Border = TRUE; }; RadioButton SV_PRINT_SELECTION { - Pos = MAP_APPFONT( 10, 70 ); + Pos = MAP_APPFONT( 10, 75 ); Size = MAP_APPFONT( 145, 15 ); Text [en-US] = "Selection"; }; FixedLine SV_PRINT_COPIES { - Pos = MAP_APPFONT( 5, 90 ); + Pos = MAP_APPFONT( 5, 95 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Copies"; }; FixedText SV_PRINT_COPYCOUNT { - Pos = MAP_APPFONT( 10, 100 ); + Pos = MAP_APPFONT( 10, 105 ); Size = MAP_APPFONT( 80, 10 ); Text [en-US] = "Number of copies"; }; NumericField SV_PRINT_COPYCOUNT_FIELD { - Pos = MAP_APPFONT( 90, 100 ); - Size = MAP_APPFONT( 40, 10 ); + Pos = MAP_APPFONT( 90, 105 ); + Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; Minimum = 1; @@ -224,12 +275,12 @@ ModalDialog SV_DLG_PRINT }; FixedImage SV_PRINT_COLLATE_IMAGE { - Pos = MAP_APPFONT( 10, 120 ); + Pos = MAP_APPFONT( 10, 125 ); Size = MAP_PIXEL( 80, 30 ); }; CheckBox SV_PRINT_COLLATE { - Pos = MAP_APPFONT( 80, 120 ); + Pos = MAP_APPFONT( 80, 125 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index eb1a0b2e0a2c..bc6e22d2283a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -91,6 +91,13 @@ PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rRe , maLocText( this, VclResId( SV_PRINT_PRT_LOCATION_TXT ) ) , maComment( this, VclResId( SV_PRINT_PRT_COMMENT ) ) , maCommentText( this, VclResId( SV_PRINT_PRT_COMMENT_TXT ) ) + , maNupLine( this, VclResId( SV_PRINT_PRT_NUP ) ) + , maNupRowsTxt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_TXT ) ) + , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) + , maNupColTxt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_TXT ) ) + , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_EDT ) ) + , maNupPortrait( this, VclResId( SV_PRINT_PRT_NUP_PORTRAIT ) ) + , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) { FreeResource(); } @@ -198,16 +205,36 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPrinter()->PixelToLogic( + maPListener->getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + if( maPListener->getPrinter()->GetOrientation() == ORIENTATION_LANDSCAPE ) + { + maNupLandscapeSize = aNupSize; + maNupPortraitSize = Size( aNupSize.Height(), aNupSize.Width() ); + maPrinterPage.maNupLandscape.Check(); + } + else + { + maNupPortraitSize = aNupSize; + maNupLandscapeSize = Size( aNupSize.Height(), aNupSize.Width() ); + maPrinterPage.maNupPortrait.Check(); + } + // setup click handler on the various buttons maJobPage.maCollateBox.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maJobPage.maAllButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maJobPage.maSelectionButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maJobPage.maPagesButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maPrinterPage.maSetupButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maPrinterPage.maNupPortrait.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maPrinterPage.maNupLandscape.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); // setup modify hdl maJobPage.maCopyCountField.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); maJobPage.maPagesEdit.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); + maPrinterPage.maNupRowsEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); + maPrinterPage.maNupColEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); // setup optional UI options set by application setupOptionalUI(); @@ -712,6 +739,18 @@ void PrintDialog::preparePreview() maPreviewWindow.setPreview( aMtf ); } +void PrintDialog::updateNup() +{ + int nRows = maPrinterPage.maNupRowsEdt.GetValue(); + int nCols = maPrinterPage.maNupColEdt.GetValue(); + + maPListener->setMultipage( nRows, nCols, + maPrinterPage.maNupPortrait.IsChecked() + ? maNupPortraitSize : maNupLandscapeSize ); + + preparePreview(); +} + IMPL_LINK( PrintDialog, ScrollHdl, ScrollBar*, pScrBar ) { if( pScrBar == &maPageScrollbar ) @@ -772,6 +811,8 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) preparePreview(); } + if( pButton == &maPrinterPage.maNupPortrait || pButton == &maPrinterPage.maNupLandscape ) + updateNup(); return 0; } @@ -783,6 +824,10 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) maPListener->setPrintSelection( maJobPage.maPagesEdit.GetText() ); preparePreview(); } + else if( pEdit == &maPrinterPage.maNupRowsEdt || pEdit == &maPrinterPage.maNupColEdt ) + { + updateNup(); + } return 0; } -- cgit From 8ef0b97b08054eaf07b1f684f41ef91f47a76772 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 31 Mar 2009 21:04:59 +0000 Subject: add: clip metafiles on rectangles --- vcl/inc/vcl/gdimtf.hxx | 1 + vcl/source/gdi/gdimtf.cxx | 34 ++++++++++++++++++++++++++++++++++ vcl/source/gdi/print3.cxx | 32 ++++++++++++++++++++------------ 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/vcl/inc/vcl/gdimtf.hxx b/vcl/inc/vcl/gdimtf.hxx index 62439d4d4613..48b39d290872 100644 --- a/vcl/inc/vcl/gdimtf.hxx +++ b/vcl/inc/vcl/gdimtf.hxx @@ -164,6 +164,7 @@ public: void Scale( double fScaleX, double fScaleY ); void Scale( const Fraction& rScaleX, const Fraction& rScaleY ); void Rotate( long nAngle10 ); + void Clip( const Rectangle& ); void Adjust( short nLuminancePercent = 0, short nContrastPercent = 0, short nChannelRPercent = 0, short nChannelGPercent = 0, diff --git a/vcl/source/gdi/gdimtf.cxx b/vcl/source/gdi/gdimtf.cxx index 3a29e6d56095..e0ea8976b75f 100644 --- a/vcl/source/gdi/gdimtf.cxx +++ b/vcl/source/gdi/gdimtf.cxx @@ -876,6 +876,40 @@ void GDIMetaFile::Scale( const Fraction& rScaleX, const Fraction& rScaleY ) // ------------------------------------------------------------------------ +void GDIMetaFile::Clip( const Rectangle& i_rClipRect ) +{ + Rectangle aCurRect( i_rClipRect ); + VirtualDevice aMapVDev; + + aMapVDev.EnableOutput( FALSE ); + aMapVDev.SetMapMode( GetPrefMapMode() ); + + for( MetaAction* pAct = (MetaAction*) First(); pAct; pAct = (MetaAction*) Next() ) + { + const long nType = pAct->GetType(); + + if( ( META_MAPMODE_ACTION == nType ) || + ( META_PUSH_ACTION == nType ) || + ( META_POP_ACTION == nType ) ) + { + pAct->Execute( &aMapVDev ); + aCurRect = aMapVDev.LogicToLogic( i_rClipRect, GetPrefMapMode(), aMapVDev.GetMapMode() ); + } + else if( nType == META_CLIPREGION_ACTION ) + { + MetaClipRegionAction* pOldAct = (MetaClipRegionAction*)pAct; + Region aNewReg( aCurRect ); + if( pOldAct->IsClipping() ) + aNewReg.Intersect( pOldAct->GetRegion() ); + MetaClipRegionAction* pNewAct = new MetaClipRegionAction( aNewReg, TRUE ); + Replace( pNewAct, GetCurPos() ); + pOldAct->Delete(); + } + } +} + +// ------------------------------------------------------------------------ + Point GDIMetaFile::ImplGetRotatedPoint( const Point& rPt, const Point& rRotatePt, const Size& rOffset, double fSin, double fCos ) { diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index bf7c02dc775e..c898e861d9f0 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -428,23 +428,31 @@ Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) return aPageSize; } -static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rRect, GDIMetaFile& i_rSubPage ) +static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GDIMetaFile& io_rSubPage ) { + // intersect all clipregion actions with our clip rect + io_rSubPage.WindStart(); + io_rSubPage.Clip( i_rClipRect ); + // save gstate o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION ) ); // draw a border + Rectangle aBorderRect( i_rClipRect ); + aBorderRect.Left() -= 100; + aBorderRect.Top() -= 100; + aBorderRect.Right() += 100; + aBorderRect.Bottom() += 100; o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); - o_rMtf.AddAction( new MetaRectAction( i_rRect ) ); + o_rMtf.AddAction( new MetaRectAction( aBorderRect ) ); // clip to page rect - // FIXME: clipping does not seem to work reliably with this - o_rMtf.AddAction( new MetaISectRectClipRegionAction( i_rRect ) ); + o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); // append the subpage - i_rSubPage.WindStart(); - i_rSubPage.Play( o_rMtf ); + io_rSubPage.WindStart(); + io_rSubPage.Play( o_rMtf ); // restore gstate o_rMtf.AddAction( new MetaPopAction() ); @@ -466,7 +474,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r long nAdvY = aPaperSize.Height() / mpImplData->mnMultiPageRows; // determine size of a "cell" subpage, leave a little space around pages - Size aSubPageSize( nAdvX - 300, nAdvY - 300 ); + Size aSubPageSize( nAdvX - 500, nAdvY - 500 ); o_rMtf.Clear(); o_rMtf.SetPrefSize( aPaperSize ); @@ -496,9 +504,9 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r aPageFile.Move( nX, nY ); aPageFile.WindStart(); // calculate border rectangle - Rectangle aSubPageRect( Point( nX - 50, nY - 50 ), - Size( long(double(aPageSize.Width())*fScale) + 100, - long(double(aPageSize.Height())*fScale) + 100 ) ); + Rectangle aSubPageRect( Point( nX, nY ), + Size( long(double(aPageSize.Width())*fScale), + long(double(aPageSize.Height())*fScale) ) ); // append subpage to page appendSubPage( o_rMtf, aSubPageRect, aPageFile ); @@ -529,6 +537,7 @@ void PrinterListener::printFilteredPage( int i_nPage ) return; } + bool bMultiPageOutput = mpImplData->mnMultiPageRows != 1 || mpImplData->mnMultiPageColumns != 1; ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); @@ -583,8 +592,7 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->EnableOutput( TRUE ); // in N-Up printing set the correct page size - // FIXME: setting paper landscape/portrait does not work here reliably ? - if( mpImplData->mnMultiPageRows != 1 || mpImplData->mnMultiPageColumns != 1 ) + if( bMultiPageOutput ) mpImplData->mpPrinter->SetPaperSizeUser( mpImplData->maMultiPageSize ); // actually print the page -- cgit From d589b3562db69a644490300fe0949c5a3dafbc75 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 31 Mar 2009 21:16:00 +0000 Subject: remove warnings --- vcl/source/control/ilstbox.cxx | 2 +- vcl/source/gdi/sallayout.cxx | 4 ++-- vcl/source/window/decoview.cxx | 6 +++--- vcl/source/window/dialog.cxx | 2 +- vcl/source/window/winproc.cxx | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/vcl/source/control/ilstbox.cxx b/vcl/source/control/ilstbox.cxx index c717e491d7b2..a25ddbb68e8b 100644 --- a/vcl/source/control/ilstbox.cxx +++ b/vcl/source/control/ilstbox.cxx @@ -1124,7 +1124,7 @@ BOOL ImplListBoxWindow::SelectEntries( USHORT nSelect, LB_EVENT_TYPE eLET, BOOL mpEntryList->SetSelectionAnchor( nSelect ); } // MultiListBox nur mit CTRL/SHIFT oder nicht im SimpleMode - else if( ( !mbSimpleMode /* && !bShift */ ) || ( mbSimpleMode && ( bCtrl || bShift ) || mbStackMode ) ) + else if( ( !mbSimpleMode /* && !bShift */ ) || ( (mbSimpleMode && ( bCtrl || bShift )) || mbStackMode ) ) { // Space fuer Selektionswechsel if( !bShift && ( ( eLET == LET_KEYSPACE ) || ( eLET == LET_MBDOWN ) ) ) diff --git a/vcl/source/gdi/sallayout.cxx b/vcl/source/gdi/sallayout.cxx index 0358b25ca153..89a47a9f4077 100755 --- a/vcl/source/gdi/sallayout.cxx +++ b/vcl/source/gdi/sallayout.cxx @@ -1292,10 +1292,10 @@ void GenericSalLayout::ApplyAsianKerning( const sal_Unicode* pStr, int nLength ) { // ignore code ranges that are not affected by asian punctuation compression const sal_Unicode cHere = pStr[n]; - if( (0x3000 != (cHere & 0xFF00)) && (0x2010 != (cHere & 0xFFF0)) || (0xFF00 != (cHere & 0xFF00)) ) + if( ((0x3000 != (cHere & 0xFF00)) && (0x2010 != (cHere & 0xFFF0))) || (0xFF00 != (cHere & 0xFF00)) ) continue; const sal_Unicode cNext = pStr[n+1]; - if( (0x3000 != (cNext & 0xFF00)) && (0x2010 != (cNext & 0xFFF0)) || (0xFF00 != (cNext & 0xFF00)) ) + if( ((0x3000 != (cNext & 0xFF00)) && (0x2010 != (cNext & 0xFFF0))) || (0xFF00 != (cNext & 0xFF00)) ) continue; // calculate compression values diff --git a/vcl/source/window/decoview.cxx b/vcl/source/window/decoview.cxx index 90934b382a88..4dd2bca2d6fa 100644 --- a/vcl/source/window/decoview.cxx +++ b/vcl/source/window/decoview.cxx @@ -944,8 +944,8 @@ static void ImplDrawFrame( OutputDevice* pDev, Rectangle& rRect, Color aColor = bRound ? rStyleSettings.GetShadowColor() : pDev->GetSettings().GetStyleSettings().GetMonoColor(); // when the MonoColor wasn't set, check face color - if ( ( ( bRound && aColor.IsDark() ) || ( aColor == Color( COL_BLACK ) ) && - ( pDev->GetSettings().GetStyleSettings().GetFaceColor().IsDark() ) ) ) + if ( ( ( bRound && aColor.IsDark() ) || ( aColor == Color( COL_BLACK ) && + ( pDev->GetSettings().GetStyleSettings().GetFaceColor().IsDark() ) ) ) ) aColor = Color( COL_WHITE ); ImplDrawDPILineRect( pDev, rRect, &aColor, bRound ); } @@ -1183,7 +1183,7 @@ static void ImplDrawButton( OutputDevice* pDev, Rectangle& rRect, aFillRect.Right(), aFillRect.Top() ) ); aFillRect.Top()++; } - if ( ((nStyle & BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT) == (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) && + if ( ((nStyle & (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) == (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) && !(nStyle & (BUTTON_DRAW_PRESSED | BUTTON_DRAW_CHECKED | BUTTON_DRAW_HIGHLIGHT)) ) { pDev->SetFillColor( rStyleSettings.GetDarkShadowColor() ); diff --git a/vcl/source/window/dialog.cxx b/vcl/source/window/dialog.cxx index c949a59cb222..1fc2b9be703a 100644 --- a/vcl/source/window/dialog.cxx +++ b/vcl/source/window/dialog.cxx @@ -347,7 +347,7 @@ void Dialog::ImplInit( Window* pParent, WinBits nStyle ) { mpWindowImpl->mbFrame = TRUE; mpWindowImpl->mbOverlapWin = TRUE; - SystemWindow::ImplInit( pParent, nStyle & (WB_MOVEABLE | WB_SIZEABLE | WB_ROLLABLE | WB_CLOSEABLE | WB_STANDALONE) | WB_CLOSEABLE, NULL ); + SystemWindow::ImplInit( pParent, (nStyle & (WB_MOVEABLE | WB_SIZEABLE | WB_ROLLABLE | WB_CLOSEABLE | WB_STANDALONE)) | WB_CLOSEABLE, NULL ); // Now set all style bits mpWindowImpl->mnStyle = nStyle; } diff --git a/vcl/source/window/winproc.cxx b/vcl/source/window/winproc.cxx index a8be05bf4909..d41a861717e9 100644 --- a/vcl/source/window/winproc.cxx +++ b/vcl/source/window/winproc.cxx @@ -1622,7 +1622,7 @@ void ImplHandleResize( Window* pWindow, long nNewWidth, long nNewHeight ) ImplDestroyHelpWindow( true ); } - if ( (nNewWidth > 0) && (nNewHeight > 0) || + if ( ((nNewWidth > 0) && (nNewHeight > 0)) || pWindow->ImplGetWindow()->ImplGetWindowImpl()->mbAllResize ) { if ( (nNewWidth != pWindow->GetOutputWidthPixel()) || (nNewHeight != pWindow->GetOutputHeightPixel()) ) -- cgit From 4313da356abe8254095a3c9a8f05eab695e2477c Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 1 Apr 2009 09:13:22 +0000 Subject: add missing newline at EOF --- vcl/source/gdi/print3.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index c898e861d9f0..f90ee6422045 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -803,4 +803,4 @@ void PrinterListener::setMultipage( int i_nRows, int i_nColumns, const Size& rPa mpImplData->mnMultiPageRows = i_nRows; mpImplData->mnMultiPageColumns = i_nColumns; mpImplData->maMultiPageSize = rPaperSize; -} \ No newline at end of file +} -- cgit From 05edec8ff965d8e0c6001a7d22fce42a5d28f9a5 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 1 Apr 2009 11:58:28 +0000 Subject: #i92516# add: quick job --- vcl/source/gdi/print3.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index f90ee6422045..fd0008cd0dba 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -200,7 +200,9 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene // check if the printer brings up its own dialog // in that case leave the work to that dialog - if( ! pListener->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) ) + const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); + bool bIsQuick = rQuick.Len() && rQuick.EqualsIgnoreCaseAscii( "true" ); + if( ! pListener->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && ! bIsQuick ) { try { -- cgit From 77c37222ad9d430b0d0f98e1432dec36d9650b00 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 1 Apr 2009 15:47:34 +0000 Subject: rearrange buttons --- vcl/source/src/print.src | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 04d9c1e02b5e..b8d21e45fb84 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -190,13 +190,13 @@ ModalDialog SV_DLG_PRINT }; RadioButton SV_PRINT_PRT_NUP_PORTRAIT { - Pos = MAP_APPFONT( 10, 125 ); + Pos = MAP_APPFONT( 110, 95 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "Po~rtrait"; }; RadioButton SV_PRINT_PRT_NUP_LANDSCAPE { - Pos = MAP_APPFONT( 10, 135 ); + Pos = MAP_APPFONT( 110, 105 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "~Landscape"; }; -- cgit From 0f97c091b9fb04b076e1de890e9eee9e7ad27d37 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 1 Apr 2009 18:19:50 +0000 Subject: select correct paper size in n-up printing, minor fixes --- vcl/source/gdi/print3.cxx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index fd0008cd0dba..1b2cef469da6 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -437,7 +437,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD io_rSubPage.Clip( i_rClipRect ); // save gstate - o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION ) ); + o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION | PUSH_MAPMODE ) ); // draw a border Rectangle aBorderRect( i_rClipRect ); @@ -481,6 +481,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r o_rMtf.Clear(); o_rMtf.SetPrefSize( aPaperSize ); o_rMtf.SetPrefMapMode( MapMode( MAP_100TH_MM ) ); + o_rMtf.AddAction( new MetaMapModeAction( MapMode( MAP_100TH_MM ) ) ); int nDocPages = getPageCount(); for( int nPage = i_nFilteredPage * nSubPages, nSubP = 0; @@ -530,7 +531,7 @@ int PrinterListener::getFilteredPageCount() void PrinterListener::printFilteredPage( int i_nPage ) { GDIMetaFile aPageFile; - getFilteredPageFile( i_nPage, aPageFile ); + Size aPageSize = getFilteredPageFile( i_nPage, aPageFile ); if( mpImplData->mpProgress ) { @@ -594,14 +595,14 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->EnableOutput( TRUE ); // in N-Up printing set the correct page size + mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); if( bMultiPageOutput ) - mpImplData->mpPrinter->SetPaperSizeUser( mpImplData->maMultiPageSize ); + mpImplData->mpPrinter->SetPaperSizeUser( aPageSize = mpImplData->maMultiPageSize ); // actually print the page mpImplData->mpPrinter->StartPage(); mpImplData->mpPrinter->Push(); - mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); aCleanedFile.WindStart(); aCleanedFile.Play( mpImplData->mpPrinter.get() ); mpImplData->mpPrinter->Pop(); -- cgit From bfb084f517f7c6f09e4d11684421b155b2c6b15d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 3 Apr 2009 11:33:25 +0000 Subject: #i92516# keep initialized printer for job if present --- vcl/source/gdi/print3.cxx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 1b2cef469da6..2ba9a143c4e1 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -195,8 +195,12 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene { // setup printer boost::shared_ptr pListener( i_pListener ); - boost::shared_ptr pPrinter( new Printer( i_rInitSetup.GetPrinterName() ) ); - pListener->setPrinter( pPrinter ); + // if no specific printer is already set, create one + if( ! pListener->getPrinter() ) + { + boost::shared_ptr pPrinter( new Printer( i_rInitSetup.GetPrinterName() ) ); + pListener->setPrinter( pPrinter ); + } // check if the printer brings up its own dialog // in that case leave the work to that dialog -- cgit From ea16cf1deb6f2abb0d3595356364cf179e508883 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 15 Apr 2009 19:11:23 +0000 Subject: #i92516# vcl helper for new print ui options --- vcl/inc/vcl/print.hxx | 97 +++++++++++++++++++++- vcl/source/gdi/print3.cxx | 203 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 299 insertions(+), 1 deletion(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 727c08545cf4..93b635756e95 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -44,6 +44,8 @@ #include "com/sun/star/beans/PropertyValue.hpp" #include +#include +#include struct SalPrinterInfoQueue; class SalInfoPrinter; @@ -454,7 +456,7 @@ public: com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getJobProperties( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rMergeList ) const; - /* get the PorpertyValue of a Property + /* get the PropertyValue of a Property */ com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ) const; @@ -496,6 +498,99 @@ public: void SAL_DLLPRIVATE setMultipage( int nRows, int nColumns, const Size& rPaperSize ); }; +class VCL_DLLPUBLIC PrinterOptionsHelper +{ + protected: + std::hash_map< rtl::OUString, com::sun::star::uno::Any, rtl::OUStringHash > m_aPropertyMap; + com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > m_aUIProperties; + + public: + PrinterOptionsHelper() {} // create without ui properties + PrinterOptionsHelper( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rUIProperties ) + : m_aUIProperties( i_rUIProperties ) + {} + ~PrinterOptionsHelper() + {} + + /* process a new set of properties + * merges changed properties and returns "true" if any occured + * if the optional output set is not NULL then the names of the changed properties are returned + **/ + bool processProperties( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rNewProp, + std::set< rtl::OUString >* o_pChangeProp = NULL ); + /* append to a sequence of property values the ui property sequence passed at creation + * as the "ExtraPrintUIOptions" property. if that sequence was empty, no "ExtraPrintUIOptions" property + * will be appended. + **/ + void appendPrintUIOptions( com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& io_rProps ) const; + + // returns an empty Any for not existing properties + com::sun::star::uno::Any getValue( const rtl::OUString& i_rPropertyName ) const; + + sal_Bool getBoolValue( const rtl::OUString& i_rPropertyName, sal_Bool i_bDefault = sal_False ) const; + // convenience for fixed strings + sal_Bool getBoolValue( const char* i_pPropName, sal_Bool i_bDefault = sal_False ) const + { return getBoolValue( rtl::OUString::createFromAscii( i_pPropName ), i_bDefault ); } + + sal_Int32 getIntValue( const rtl::OUString& i_rPropertyName, sal_Int32 i_nDefault = 0 ) const; + // convenience for fixed strings + sal_Int32 getIntValue( const char* i_pPropName, sal_Int32 i_nDefault = 0 ) const + { return getIntValue( rtl::OUString::createFromAscii( i_pPropName ), i_nDefault ); } + + rtl::OUString getStringValue( const rtl::OUString& i_rPropertyName, const rtl::OUString& i_rDefault = rtl::OUString() ) const; + // convenience for fixed strings + rtl::OUString getStringValue( const char* i_pPropName, const rtl::OUString& i_rDefault = rtl::OUString() ) const + { return getStringValue( rtl::OUString::createFromAscii( i_pPropName ), i_rDefault ); } + + // helper functions for user to create a single control + + // general control + static com::sun::star::uno::Any getUIControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rType, + const com::sun::star::beans::PropertyValue* i_pVal = NULL, + const com::sun::star::uno::Sequence< rtl::OUString >* i_pChoices = NULL, + const rtl::OUString* i_pDependsOnName = NULL, + sal_Int32 i_nDependsOnEntry = -1, + sal_Int32 i_nMinValue = -1, sal_Int32 i_nMaxValue = -2 + ); + // create a group (e.g. a TabPage); following controls will be grouped in it until the next + // group begins + static com::sun::star::uno::Any getGroupControlOpt( const rtl::OUString& i_rTitle ); + + // create a subgroup (e.g. a FixedLine); following controls will be grouped in it until the next + // subgroup or group begins + static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle ); + + // create a bool option (usually a checkbox) + static com::sun::star::uno::Any getBoolControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + sal_Bool i_bValue, + const rtl::OUString* i_pDependsOnName = NULL, + sal_Int32 i_nDependsOnEntry = -1 + ); + + // create a set of choices (either a radio button group or a list box) + static com::sun::star::uno::Any getChoiceControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + const com::sun::star::uno::Sequence< rtl::OUString >& i_rChoices, + sal_Int32 i_nValue, + const rtl::OUString& i_rType = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Radio" ) ), + const rtl::OUString* i_pDependsOnName = NULL, + sal_Int32 i_nDependsOnEntry = -1 + ); + + // create an integer range (e.g. a spin field) + // note: max value < min value means do not apply min/max values + static com::sun::star::uno::Any getRangeControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + sal_Int32 i_nValue, + sal_Int32 i_nMinValue = -1, + sal_Int32 i_nMaxValue = -2, + const rtl::OUString* i_pDependsOnName = NULL, + sal_Int32 i_nDependsOnEntry = -1 + ); +}; + } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 2ba9a143c4e1..63e27b5b3a5f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -811,3 +811,206 @@ void PrinterListener::setMultipage( int i_nRows, int i_nColumns, const Size& rPa mpImplData->mnMultiPageColumns = i_nColumns; mpImplData->maMultiPageSize = rPaperSize; } + +/* + * PrinterOptionsHelper +**/ +Any PrinterOptionsHelper::getValue( const rtl::OUString& i_rPropertyName ) const +{ + Any aRet; + std::hash_map< rtl::OUString, Any, rtl::OUStringHash >::const_iterator it = + m_aPropertyMap.find( i_rPropertyName ); + if( it != m_aPropertyMap.end() ) + aRet = it->second; + return aRet; +} + +sal_Bool PrinterOptionsHelper::getBoolValue( const rtl::OUString& i_rPropertyName, sal_Bool i_bDefault ) const +{ + sal_Bool bRet = sal_False; + Any aVal( getValue( i_rPropertyName ) ); + return (aVal >>= bRet) ? bRet : i_bDefault; +} + +sal_Int32 PrinterOptionsHelper::getIntValue( const rtl::OUString& i_rPropertyName, sal_Int32 i_nDefault ) const +{ + sal_Int32 nRet = 0; + Any aVal( getValue( i_rPropertyName ) ); + return (aVal >>= nRet) ? nRet : i_nDefault; +} + +rtl::OUString PrinterOptionsHelper::getStringValue( const rtl::OUString& i_rPropertyName, const rtl::OUString& i_rDefault ) const +{ + rtl::OUString aRet; + Any aVal( getValue( i_rPropertyName ) ); + return (aVal >>= aRet) ? aRet : i_rDefault; +} + +bool PrinterOptionsHelper::processProperties( const Sequence< PropertyValue >& i_rNewProp, + std::set< rtl::OUString >* o_pChangeProp ) +{ + bool bChanged = false; + + // clear the changed set + if( o_pChangeProp ) + o_pChangeProp->clear(); + + sal_Int32 nElements = i_rNewProp.getLength(); + const PropertyValue* pVals = i_rNewProp.getConstArray(); + for( sal_Int32 i = 0; i < nElements; i++ ) + { + bool bElementChanged = false; + std::hash_map< rtl::OUString, Any, rtl::OUStringHash >::iterator it = + m_aPropertyMap.find( pVals[ i ].Name ); + if( it != m_aPropertyMap.end() ) + { + if( it->second != pVals[ i ].Value ) + bElementChanged = true; + } + else + bElementChanged = true; + + if( bElementChanged ) + { + if( o_pChangeProp ) + o_pChangeProp->insert( pVals[ i ].Name ); + m_aPropertyMap[ pVals[i].Name ] = pVals[i].Value; + bChanged = true; + } + } + return bChanged; +} + +void PrinterOptionsHelper::appendPrintUIOptions( uno::Sequence< beans::PropertyValue >& io_rProps ) const +{ + if( m_aUIProperties.getLength() > 0 ) + { + sal_Int32 nIndex = io_rProps.getLength(); + io_rProps.realloc( nIndex+1 ); + PropertyValue aVal; + aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ExtraPrintUIOptions" ) ); + aVal.Value = makeAny( m_aUIProperties ); + io_rProps[ nIndex ] = aVal; + } +} + +Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rType, + const PropertyValue* i_pVal, + const Sequence< rtl::OUString >* i_pChoices, + const rtl::OUString* i_pDependsOnName, + sal_Int32 i_nDependsOnEntry, + sal_Int32 i_nMinValue, + sal_Int32 i_nMaxValue + ) +{ + sal_Int32 nElements = + 1 // ControlType + + (i_rTitle.getLength() ? 1 : 0) // Text + + (i_pVal ? 1 : 0) // Property + + (i_pChoices ? 1 : 0) // Choices + + (i_pDependsOnName ? (i_nDependsOnEntry != -1 ? 2 : 1) : 0) // dependencies + + (i_nMaxValue >= i_nMinValue ? 2 : 0) // min/max + ; + + Sequence< PropertyValue > aCtrl( nElements ); + sal_Int32 nUsed = 0; + if( i_rTitle.getLength() ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ) ); + aCtrl[nUsed++].Value = makeAny( i_rTitle ); + } + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ControlType" ) ); + aCtrl[nUsed++].Value = makeAny( i_rType ); + if( i_pVal ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Property" ) ); + aCtrl[nUsed++].Value = makeAny( *i_pVal ); + } + if( i_pChoices ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Choices" ) ); + aCtrl[nUsed++].Value = makeAny( *i_pChoices ); + } + if( i_pDependsOnName ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnName" ) ); + aCtrl[nUsed++].Value = makeAny( *i_pDependsOnName ); + if( i_nDependsOnEntry != -1 ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnEntry" ) ); + aCtrl[nUsed++].Value = makeAny( i_nDependsOnEntry ); + } + } + if( i_nMaxValue >= i_nMinValue ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MinValue" ) ); + aCtrl[nUsed++].Value = makeAny( i_nMinValue ); + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxValue" ) ); + aCtrl[nUsed++].Value = makeAny( i_nMaxValue ); + } + + DBG_ASSERT( nUsed == nElements, "nUsed != nElements, probable heap corruption" ); + + return makeAny( aCtrl ); +} + +Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle ) +{ + return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Group" ) ) ); +} + +Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle ) +{ + return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ) ); +} + +Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + sal_Bool i_bValue, + const rtl::OUString* i_pDependsOnName, + sal_Int32 i_nDependsOnEntry + ) +{ + PropertyValue aVal; + aVal.Name = i_rProperty; + aVal.Value = makeAny( i_bValue ); + return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, NULL, i_pDependsOnName, i_nDependsOnEntry ); +} + +Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + const Sequence< rtl::OUString >& i_rChoices, + sal_Int32 i_nValue, + const rtl::OUString& i_rType, + const rtl::OUString* i_pDependsOnName, + sal_Int32 i_nDependsOnEntry + ) +{ + PropertyValue aVal; + aVal.Name = i_rProperty; + aVal.Value = makeAny( i_nValue ); + return getUIControlOpt( i_rTitle, i_rType, &aVal, &i_rChoices, i_pDependsOnName, i_nDependsOnEntry ); +} + +Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rProperty, + sal_Int32 i_nValue, + sal_Int32 i_nMinValue, + sal_Int32 i_nMaxValue, + const rtl::OUString* i_pDependsOnName, + sal_Int32 i_nDependsOnEntry + ) +{ + PropertyValue aVal; + aVal.Name = i_rProperty; + aVal.Value = makeAny( i_nValue ); + return getUIControlOpt( i_rTitle, + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Range" ) ), + &aVal, + NULL, + i_pDependsOnName, + i_nDependsOnEntry, + i_nMinValue, + i_nMaxValue ); +} -- cgit From a8b3bdded3b8a0fa7cfd12e52b9d60ce3658019e Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 16 Apr 2009 05:47:42 +0000 Subject: #i92516# adjust positions --- vcl/source/src/print.src | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index b8d21e45fb84..05fa6e1d9ccc 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -38,18 +38,18 @@ ModalDialog SV_DLG_PRINT Moveable = TRUE; SVLook = TRUE; - Size = MAP_APPFONT( 350, 195 ); + Size = MAP_APPFONT( 350, 205 ); OKButton SV_PRINT_OK { DefButton = TRUE; - Pos = MAP_APPFONT( 240, 175 ); + Pos = MAP_APPFONT( 240, 185 ); Size = MAP_APPFONT( 50, 15 ); Text [en-US] = "~Print"; }; CancelButton SV_PRINT_CANCEL { - Pos = MAP_APPFONT( 295, 175 ); + Pos = MAP_APPFONT( 295, 185 ); Size = MAP_APPFONT( 50, 15 ); }; @@ -77,11 +77,11 @@ ModalDialog SV_DLG_PRINT TabControl SV_PRINT_TABCTRL { Pos = MAP_APPFONT( 140, 5 ); - Size = MAP_APPFONT( 205, 160 ); + Size = MAP_APPFONT( 205, 165 ); }; FixedLine SV_PRINT_BUTTONLINE { - Pos = MAP_APPFONT( 0, 165 ); + Pos = MAP_APPFONT( 0, 175 ); Size = MAP_APPFONT( 350, 8 ); }; String SV_PRINT_NOPAGES -- cgit From 198632aa538edc6804909fe7330fc122b769398b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 20 Apr 2009 16:57:13 +0000 Subject: CWS-TOOLING: rebase CWS printerpullpages to trunk@270723 (milestone: DEV300:m46) --- basegfx/inc/basegfx/polygon/b3dpolygontools.hxx | 14 + basegfx/source/polygon/b3dpolygontools.cxx | 62 + comphelper/source/misc/storagehelper.cxx | 2 +- i18nutil/inc/i18nutil/casefolding.hxx | 24 +- i18nutil/source/utility/casefolding.cxx | 12 +- padmin/prj/build.lst | 2 +- padmin/source/prtsetup.cxx | 17 - padmin/source/prtsetup.hxx | 2 - svtools/source/edit/editsyntaxhighlighter.cxx | 5 +- svtools/source/edit/svmedit.cxx | 2 +- toolkit/workben/layout/editor.cxx | 1 + toolkit/workben/layout/makefile.mk | 2 +- tools/bootstrp/rscdep.cxx | 10 +- vcl/aqua/inc/saldata.hxx | 3 +- vcl/aqua/source/app/saldata.cxx | 5 +- vcl/aqua/source/app/salinst.cxx | 7 +- vcl/aqua/source/gdi/salatslayout.cxx | 55 +- vcl/aqua/source/gdi/salatsuifontutils.cxx | 177 +- vcl/aqua/source/gdi/salgdi.cxx | 20 +- vcl/aqua/source/window/salframeview.mm | 2 +- vcl/aqua/source/window/salmenu.cxx | 2 +- vcl/aqua/source/window/salobj.cxx | 7 +- vcl/inc/list.h | 3 +- vcl/inc/sft.h | 641 ----- vcl/inc/sft.hxx | 626 +++++ vcl/inc/vcl/svdata.hxx | 1 + vcl/os2/source/gdi/salgdi3.cxx | 7 +- vcl/prj/build.lst | 2 +- vcl/source/app/svdata.cxx | 14 + vcl/source/fontsubset/crc32.c | 89 - vcl/source/fontsubset/crc32.h | 46 - vcl/source/fontsubset/gsub.cxx | 12 +- vcl/source/fontsubset/gsub.h | 18 +- vcl/source/fontsubset/list.c | 9 +- vcl/source/fontsubset/makefile.mk | 4 - vcl/source/fontsubset/sft.c | 3334 ----------------------- vcl/source/fontsubset/sft.cxx | 3312 ++++++++++++++++++++++ vcl/source/fontsubset/ttcr.c | 1669 ------------ vcl/source/fontsubset/ttcr.cxx | 1669 ++++++++++++ vcl/source/fontsubset/ttcr.h | 280 -- vcl/source/fontsubset/ttcr.hxx | 261 ++ vcl/source/fontsubset/u2big5.inc | 5 +- vcl/source/fontsubset/u2johab.inc | 5 +- vcl/source/fontsubset/u2prc.inc | 5 +- vcl/source/fontsubset/u2shiftjis.inc | 5 +- vcl/source/fontsubset/u2wansung.inc | 5 +- vcl/source/fontsubset/xlat.c | 187 -- vcl/source/fontsubset/xlat.cxx | 188 ++ vcl/source/fontsubset/xlat.h | 68 - vcl/source/fontsubset/xlat.hxx | 54 + vcl/source/gdi/font.cxx | 4 +- vcl/source/gdi/pdfwriter_impl.cxx | 43 +- vcl/source/gdi/sallayout.cxx | 2 +- vcl/source/helper/smartid.cxx | 2 +- vcl/source/window/decoview.cxx | 13 +- vcl/source/window/menu.cxx | 200 +- vcl/source/window/winproc.cxx | 18 +- vcl/unx/gtk/a11y/atktext.cxx | 8 +- vcl/unx/gtk/app/gtkinst.cxx | 16 +- vcl/unx/gtk/window/gtkframe.cxx | 17 +- vcl/unx/inc/saldata.hxx | 2 - vcl/unx/source/app/saldata.cxx | 13 - vcl/unx/source/fontmanager/fontmanager.cxx | 5 +- vcl/unx/source/gdi/salgdi.cxx | 5 + vcl/unx/source/plugadapt/salplug.cxx | 16 +- vcl/unx/source/printergfx/glyphset.cxx | 5 +- vcl/util/makefile.mk | 2 - vcl/win/source/gdi/salgdi3.cxx | 5 +- vcl/win/source/gdi/winlayout.cxx | 20 +- 69 files changed, 6644 insertions(+), 6704 deletions(-) delete mode 100644 vcl/inc/sft.h create mode 100644 vcl/inc/sft.hxx delete mode 100644 vcl/source/fontsubset/crc32.c delete mode 100644 vcl/source/fontsubset/crc32.h delete mode 100644 vcl/source/fontsubset/sft.c create mode 100644 vcl/source/fontsubset/sft.cxx delete mode 100644 vcl/source/fontsubset/ttcr.c create mode 100644 vcl/source/fontsubset/ttcr.cxx delete mode 100644 vcl/source/fontsubset/ttcr.h create mode 100644 vcl/source/fontsubset/ttcr.hxx delete mode 100644 vcl/source/fontsubset/xlat.c create mode 100644 vcl/source/fontsubset/xlat.cxx delete mode 100644 vcl/source/fontsubset/xlat.h create mode 100644 vcl/source/fontsubset/xlat.hxx diff --git a/basegfx/inc/basegfx/polygon/b3dpolygontools.hxx b/basegfx/inc/basegfx/polygon/b3dpolygontools.hxx index 7b451970c565..a29204eadc3f 100644 --- a/basegfx/inc/basegfx/polygon/b3dpolygontools.hxx +++ b/basegfx/inc/basegfx/polygon/b3dpolygontools.hxx @@ -174,6 +174,20 @@ namespace basegfx bool equal(const B3DPolygon& rCandidateA, const B3DPolygon& rCandidateB, const double& rfSmallValue); bool equal(const B3DPolygon& rCandidateA, const B3DPolygon& rCandidateB); + /** snap some polygon coordinates to discrete coordinates + + This method allows to snap some polygon points to discrete (integer) values + which equals e.g. a snap to discrete coordinates. It will snap points of + horizontal and vertical edges + + @param rCandidate + The source polygon + + @return + The modified version of the source polygon + */ + B3DPolygon snapPointsOfHorizontalOrVerticalEdges(const B3DPolygon& rCandidate); + } // end of namespace tools } // end of namespace basegfx diff --git a/basegfx/source/polygon/b3dpolygontools.cxx b/basegfx/source/polygon/b3dpolygontools.cxx index 3ea163a85e89..ea303886dd88 100644 --- a/basegfx/source/polygon/b3dpolygontools.cxx +++ b/basegfx/source/polygon/b3dpolygontools.cxx @@ -39,6 +39,7 @@ #include #include #include +#include #include ////////////////////////////////////////////////////////////////////////////// @@ -1101,6 +1102,67 @@ namespace basegfx return equal(rCandidateA, rCandidateB, fSmallValue); } + // snap points of horizontal or vertical edges to discrete values + B3DPolygon snapPointsOfHorizontalOrVerticalEdges(const B3DPolygon& rCandidate) + { + const sal_uInt32 nPointCount(rCandidate.count()); + + if(nPointCount > 1) + { + // Start by copying the source polygon to get a writeable copy. The closed state is + // copied by aRetval's initialisation, too, so no need to copy it in this method + B3DPolygon aRetval(rCandidate); + + // prepare geometry data. Get rounded from original + B3ITuple aPrevTuple(basegfx::fround(rCandidate.getB3DPoint(nPointCount - 1))); + B3DPoint aCurrPoint(rCandidate.getB3DPoint(0)); + B3ITuple aCurrTuple(basegfx::fround(aCurrPoint)); + + // loop over all points. This will also snap the implicit closing edge + // even when not closed, but that's no problem here + for(sal_uInt32 a(0); a < nPointCount; a++) + { + // get next point. Get rounded from original + const bool bLastRun(a + 1 == nPointCount); + const sal_uInt32 nNextIndex(bLastRun ? 0 : a + 1); + const B3DPoint aNextPoint(rCandidate.getB3DPoint(nNextIndex)); + const B3ITuple aNextTuple(basegfx::fround(aNextPoint)); + + // get the states + const bool bPrevVertical(aPrevTuple.getX() == aCurrTuple.getX()); + const bool bNextVertical(aNextTuple.getX() == aCurrTuple.getX()); + const bool bPrevHorizontal(aPrevTuple.getY() == aCurrTuple.getY()); + const bool bNextHorizontal(aNextTuple.getY() == aCurrTuple.getY()); + const bool bSnapX(bPrevVertical || bNextVertical); + const bool bSnapY(bPrevHorizontal || bNextHorizontal); + + if(bSnapX || bSnapY) + { + const B3DPoint aSnappedPoint( + bSnapX ? aCurrTuple.getX() : aCurrPoint.getX(), + bSnapY ? aCurrTuple.getY() : aCurrPoint.getY(), + aCurrPoint.getZ()); + + aRetval.setB3DPoint(a, aSnappedPoint); + } + + // prepare next point + if(!bLastRun) + { + aPrevTuple = aCurrTuple; + aCurrPoint = aNextPoint; + aCurrTuple = aNextTuple; + } + } + + return aRetval; + } + else + { + return rCandidate; + } + } + } // end of namespace tools } // end of namespace basegfx diff --git a/comphelper/source/misc/storagehelper.cxx b/comphelper/source/misc/storagehelper.cxx index 7d63ed7a43f5..d2284409bdce 100644 --- a/comphelper/source/misc/storagehelper.cxx +++ b/comphelper/source/misc/storagehelper.cxx @@ -427,7 +427,7 @@ sal_Bool OStorageHelper::IsValidZipEntryFileName( return sal_False; break; default: - if ( pChar[i] < 32 || pChar[i] >= 0xD800 && pChar[i] <= 0xDFFF ) + if ( pChar[i] < 32 || (pChar[i] >= 0xD800 && pChar[i] <= 0xDFFF) ) return sal_False; } } diff --git a/i18nutil/inc/i18nutil/casefolding.hxx b/i18nutil/inc/i18nutil/casefolding.hxx index 2c993d43f75d..bc67f4fce47e 100644 --- a/i18nutil/inc/i18nutil/casefolding.hxx +++ b/i18nutil/inc/i18nutil/casefolding.hxx @@ -37,20 +37,20 @@ namespace com { namespace sun { namespace star { namespace i18n { -#define MappingTypeLowerToUpper 1 << 0 // Upper to Lower mapping -#define MappingTypeUpperToLower 1 << 1 // Lower to Upper mapping -#define MappingTypeToUpper 1 << 2 // to Upper mapping -#define MappingTypeToLower 1 << 3 // to Lower mapping -#define MappingTypeToTitle 1 << 4 // to Title mapping -#define MappingTypeSimpleFolding 1 << 5 // Simple Case Folding -#define MappingTypeFullFolding 1 << 6 // Full Case Folding -#define MappingTypeMask MappingTypeLowerToUpper|MappingTypeUpperToLower|\ +#define MappingTypeLowerToUpper (1 << 0) // Upper to Lower mapping +#define MappingTypeUpperToLower (1 << 1) // Lower to Upper mapping +#define MappingTypeToUpper (1 << 2) // to Upper mapping +#define MappingTypeToLower (1 << 3) // to Lower mapping +#define MappingTypeToTitle (1 << 4) // to Title mapping +#define MappingTypeSimpleFolding (1 << 5) // Simple Case Folding +#define MappingTypeFullFolding (1 << 6) // Full Case Folding +#define MappingTypeMask (MappingTypeLowerToUpper|MappingTypeUpperToLower|\ MappingTypeToUpper|MappingTypeToLower|MappingTypeToTitle|\ - MappingTypeSimpleFolding|MappingTypeFullFolding + MappingTypeSimpleFolding|MappingTypeFullFolding) -#define ValueTypeNotValue 1 << 7 // Value field is an address +#define ValueTypeNotValue (1 << 7) // Value field is an address -#define CasedLetter MappingTypeMask // for final sigmar +#define CasedLetter (MappingTypeMask) // for final sigmar struct Value { @@ -68,7 +68,7 @@ struct Mapping struct MappingElement { - MappingElement() {element.nmap = current = 0;}; + MappingElement() {element.nmap = current = 0;} Mapping element; sal_Int8 current; }; diff --git a/i18nutil/source/utility/casefolding.cxx b/i18nutil/source/utility/casefolding.cxx index 8a679b8afbe5..7a74609b0342 100644 --- a/i18nutil/source/utility/casefolding.cxx +++ b/i18nutil/source/utility/casefolding.cxx @@ -51,13 +51,13 @@ static Mapping mapping_0130[] = {{0, 1, {0x0069, 0, 0}},{0, 1, {0x0130, 0, 0}}}; #define langIs(lang) (aLocale.Language.compareToAscii(lang) == 0) // only check simple case, there is more complicated case need to be checked. -#define type_i(ch) (ch == 0x0069 || ch == 0x006a) +#define type_i(ch) ((ch) == 0x0069 || (ch) == 0x006a) -#define cased_letter(ch) (CaseMappingIndex[ch>>8] >= 0 && (CaseMappingValue[(CaseMappingIndex[ch>>8] << 8) + (ch&0xff)].type & CasedLetter)) +#define cased_letter(ch) (CaseMappingIndex[(ch)>>8] >= 0 && (CaseMappingValue[(CaseMappingIndex[(ch)>>8] << 8) + ((ch)&0xff)].type & CasedLetter)) // for Lithuanian, condition to make explicit dot above when lowercasing capital I's and J's // whenever there are more accents above. -#define accent_above(ch) (ch >= 0x0300 && ch <= 0x0314 || ch >= 0x033D && ch <= 0x0344 || ch == 0x0346 || ch >= 0x034A && ch <= 0x034C) +#define accent_above(ch) (((ch) >= 0x0300 && (ch) <= 0x0314) || ((ch) >= 0x033D && (ch) <= 0x0344) || (ch) == 0x0346 || ((ch) >= 0x034A && (ch) <= 0x034C)) Mapping& casefolding::getConditionalValue(const sal_Unicode* str, sal_Int32 pos, sal_Int32 len, Locale& aLocale, sal_uInt8 nMappingType) throw (RuntimeException) { @@ -68,8 +68,8 @@ Mapping& casefolding::getConditionalValue(const sal_Unicode* str, sal_Int32 pos, return !(pos < len && cased_letter(str[pos+1])) && (pos > 0 && cased_letter(str[pos-1])) ? mapping_03a3[0] : mapping_03a3[1]; case 0x0307: - return ((nMappingType == MappingTypeLowerToUpper && langIs("lt") || - nMappingType == MappingTypeUpperToLower && (langIs("tr") || langIs("az"))) && + return (((nMappingType == MappingTypeLowerToUpper && langIs("lt")) || + (nMappingType == MappingTypeUpperToLower && (langIs("tr") || langIs("az")))) && (pos > 0 && type_i(str[pos-1]))) ? // after_i mapping_0307[0] : mapping_0307[1]; case 0x0130: @@ -147,7 +147,7 @@ sal_Unicode casefolding::getNextChar(const sal_Unicode *str, sal_Int32& idx, sal } if (moduleLoaded & TransliterationModules_IGNORE_KANA) { - if (0x3040 <= c && c <= 0x3094 || 0x309d <= c && c <= 0x309f) + if ((0x3040 <= c && c <= 0x3094) || (0x309d <= c && c <= 0x309f)) c += 0x60; } diff --git a/padmin/prj/build.lst b/padmin/prj/build.lst index 9aaab83cf7de..765675d73137 100644 --- a/padmin/prj/build.lst +++ b/padmin/prj/build.lst @@ -1,3 +1,3 @@ -pd padmin : vcl svtools NULL +pd padmin : psprint vcl svtools NULL pd padmin usr1 - all pd_mkout NULL pd padmin\source nmake - all pd_source NULL diff --git a/padmin/source/prtsetup.cxx b/padmin/source/prtsetup.cxx index 1a6894789bb5..6cf4f8b257b1 100644 --- a/padmin/source/prtsetup.cxx +++ b/padmin/source/prtsetup.cxx @@ -148,23 +148,6 @@ RTSDialog::~RTSDialog() // -------------------------------------------------------------------------- -String RTSDialog::getPaperSize() -{ - String aRet; - if( m_aJobData.m_pParser ) - { - const PPDKey* pKey = m_aJobData.m_pParser->getKey( String::CreateFromAscii( "PageSize" ) ); - if( pKey ) - { - const PPDValue* pValue = m_aJobData.m_aContext.getValue( pKey ); - aRet = pValue->m_aOption; - } - } - return aRet; -} - -// -------------------------------------------------------------------------- - IMPL_LINK( RTSDialog, ActivatePage, TabControl*, pTabCtrl ) { if( pTabCtrl != &m_aTabControl ) diff --git a/padmin/source/prtsetup.hxx b/padmin/source/prtsetup.hxx index 56e68336dfd8..8487daa158da 100644 --- a/padmin/source/prtsetup.hxx +++ b/padmin/source/prtsetup.hxx @@ -86,8 +86,6 @@ class RTSDialog : public TabDialog // helper functions void insertAllPPDValues( ListBox&, const ::psp::PPDKey* ); - - String getPaperSize(); public: RTSDialog( const ::psp::PrinterInfo& rJobData, const String& rPrinter, bool bAllPages, Window* pParent = NULL ); ~RTSDialog(); diff --git a/svtools/source/edit/editsyntaxhighlighter.cxx b/svtools/source/edit/editsyntaxhighlighter.cxx index 334b19ccd98d..74d72e32155c 100644 --- a/svtools/source/edit/editsyntaxhighlighter.cxx +++ b/svtools/source/edit/editsyntaxhighlighter.cxx @@ -108,8 +108,11 @@ void MultiLineEditSyntaxHighlight::DoBracketHilight(USHORT aKey) { for (long aPara =nStartPara; aPara>=0;--aPara) { + if ( aStartPos == 0 ) + continue; + String aLine( GetTextEngine()->GetText( aPara ) ); - for (USHORT i = ((unsigned long)aPara==nStartPara) ? aStartPos-1 : (USHORT)(GetTextEngine()->GetTextLen()-1); i>0; --i) + for (USHORT i = ((unsigned long)aPara==nStartPara) ? aStartPos-1 : (USHORT)(aLine.Len()-1); i>0; --i) { if (aLine.GetChar(i)==aChar) { diff --git a/svtools/source/edit/svmedit.cxx b/svtools/source/edit/svmedit.cxx index 42026382385f..279af7c83cef 100644 --- a/svtools/source/edit/svmedit.cxx +++ b/svtools/source/edit/svmedit.cxx @@ -218,7 +218,7 @@ void ImpSvMEdit::ImpUpdateSrollBarVis( WinBits nWinStyle ) bNeedVScroll = true; } - const BOOL bNeedScrollBox = bNeedVScroll || bNeedHScroll; + const BOOL bNeedScrollBox = bNeedVScroll && bNeedHScroll; BOOL bScrollbarsChanged = false; if ( bHaveVScroll != bNeedVScroll ) diff --git a/toolkit/workben/layout/editor.cxx b/toolkit/workben/layout/editor.cxx index c8e44a9c9180..0ef31560b69f 100644 --- a/toolkit/workben/layout/editor.cxx +++ b/toolkit/workben/layout/editor.cxx @@ -34,6 +34,7 @@ #undef NDEBUG #include #include +#include #include #include diff --git a/toolkit/workben/layout/makefile.mk b/toolkit/workben/layout/makefile.mk index 8612992303d8..a7f1a8dfcb97 100644 --- a/toolkit/workben/layout/makefile.mk +++ b/toolkit/workben/layout/makefile.mk @@ -89,7 +89,7 @@ XML_FILES=\ wordcount.xml\ zoom.xml\ -TRALAY=tralay +TRALAY=$(AUGMENT_LIBRARY_PATH) tralay XML_LANGS=$(alllangiso) #ALL_XMLS=$(foreach,i,$(XML_LANGS) $(foreach,j,$(XML_FILES) $i/$j)) diff --git a/tools/bootstrp/rscdep.cxx b/tools/bootstrp/rscdep.cxx index 7c394dcdaee8..d4411058a6fb 100644 --- a/tools/bootstrp/rscdep.cxx +++ b/tools/bootstrp/rscdep.cxx @@ -96,7 +96,9 @@ main( int argc, char **argv ) String aSrsBaseName; BOOL bSource = FALSE; ByteString aRespArg; - String aDelim = String(DirEntry::GetAccessDelimiter()); +// who needs anything but '/' ? +// String aDelim = String(DirEntry::GetAccessDelimiter()); + String aDelim = '/'; RscHrcDep *pDep = new RscHrcDep; @@ -256,6 +258,7 @@ main( int argc, char **argv ) printf("further arguments : "); #endif aString = ByteString( pSrsFileName ); + aString.SearchAndReplaceAll('\\', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); aString += ByteString(" : " ); while ( optind < argc ) @@ -289,12 +292,7 @@ main( int argc, char **argv ) for ( ULONG j=0; jGetObject(j); -#ifdef UNX pStr->SearchAndReplaceAll('\\', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); -#endif -#ifdef WNT - pStr->SearchAndReplaceAll('/', ByteString( aDelim, RTL_TEXTENCODING_ASCII_US )); -#endif if ( j != (nCount-1) ) *pStr += ByteString( "\\" ); aOutStream.WriteLine( *pStr ); diff --git a/vcl/aqua/inc/saldata.hxx b/vcl/aqua/inc/saldata.hxx index 931369982f03..dc629b9a3b8c 100644 --- a/vcl/aqua/inc/saldata.hxx +++ b/vcl/aqua/inc/saldata.hxx @@ -107,9 +107,10 @@ struct SalData bool mbIsScrollbarDoubleMax; // TODO: support DoubleMin and DoubleBoth too SInt32 mnSystemVersion; // Store System Version MainController* mpMainController; // Apple Remote - bool mbIsTestTool; NSObject* mpDockIconClickHandler; + long mnDPIX; // #i100617# read DPI only once per office life + long mnDPIY; // #i100617# read DPI only once per office life SalData(); ~SalData(); diff --git a/vcl/aqua/source/app/saldata.cxx b/vcl/aqua/source/app/saldata.cxx index b110141fb224..a70854306122 100644 --- a/vcl/aqua/source/app/saldata.cxx +++ b/vcl/aqua/source/app/saldata.cxx @@ -61,8 +61,9 @@ SalData::SalData() mbIsScrollbarDoubleMax( false ), mnSystemVersion( VER_TIGER ), mpMainController( NULL ), - mbIsTestTool( false ), - mpDockIconClickHandler( nil ) + mpDockIconClickHandler( nil ), + mnDPIX( 0 ), + mnDPIY( 0 ) { if( s_aAutoReleaseKey == 0 ) s_aAutoReleaseKey = osl_createThreadKey( releasePool ); diff --git a/vcl/aqua/source/app/salinst.cxx b/vcl/aqua/source/app/salinst.cxx index 0523381b9223..b9d66d1e02d3 100644 --- a/vcl/aqua/source/app/salinst.cxx +++ b/vcl/aqua/source/app/salinst.cxx @@ -178,7 +178,6 @@ static void initNSApp() // get System Version and store the value in GetSalData()->mnSystemVersion [NSApp getSystemVersionMajor: (unsigned int *)major minor:(unsigned int *)minor bugFix:(unsigned int *)bugFix ]; -// ----------------------------------------------------------------------------------------------------------------- // Initialize Apple Remote GetSalData()->mpMainController = [[MainController alloc] init]; @@ -191,13 +190,9 @@ static void initNSApp() selector: @selector(applicationWillResignActive:) name: @"AppleRemoteWillResignActive" object: nil ]; -// ----------------------------------------------------------------------------------------------------------------- - if( AquaSalInstance::isOnCommandLine( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "-enableautomation" ) ) ) ) - { + if( ImplGetSVData()->mbIsTestTool ) [NSApp activateIgnoringOtherApps: YES]; - GetSalData()->mbIsTestTool = true; - } } BOOL ImplSVMainHook( BOOL * pbInit ) diff --git a/vcl/aqua/source/gdi/salatslayout.cxx b/vcl/aqua/source/gdi/salatslayout.cxx index 929c8dd19c64..f47920004f7a 100755 --- a/vcl/aqua/source/gdi/salatslayout.cxx +++ b/vcl/aqua/source/gdi/salatslayout.cxx @@ -711,6 +711,31 @@ int ATSLayout::GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) cons if( !maATSULayout ) return STRING_LEN; + // the semantics of the legacy use case (nCharExtra!=0) cannot be mapped to ATSUBreakLine() + if( nCharExtra != 0 ) + { + // prepare the measurement by layouting and measuring the un-expanded/un-condensed text + if( !InitGIA() ) + return STRING_LEN; + + // TODO: use a better way than by testing each the char position + ATSUTextMeasurement nATSUSumWidth = 0; + const ATSUTextMeasurement nATSUMaxWidth = Vcl2Fixed( nMaxWidth / nFactor ); + const ATSUTextMeasurement nATSUExtraWidth = Vcl2Fixed( nCharExtra ) / nFactor; + for( int i = 0; i < mnCharCount; ++i ) + { + nATSUSumWidth += mpCharWidths[i]; + if( nATSUSumWidth >= nATSUMaxWidth ) + return (mnMinCharPos + i); + nATSUSumWidth += nATSUExtraWidth; + if( nATSUSumWidth >= nATSUMaxWidth ) + if( i+1 < mnCharCount ) + return (mnMinCharPos + i); + } + + return STRING_LEN; + } + // get a quick overview on what could fit const long nPixelWidth = (nMaxWidth - (nCharExtra * mnCharCount)) / nFactor; @@ -720,10 +745,10 @@ int ATSLayout::GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) cons // initial measurement of text break position UniCharArrayOffset nBreakPos = mnMinCharPos; const ATSUTextMeasurement nATSUMaxWidth = Vcl2Fixed( nPixelWidth ); - OSStatus nStatus = ATSUBreakLine( maATSULayout, mnMinCharPos, + OSStatus eStatus = ATSUBreakLine( maATSULayout, mnMinCharPos, nATSUMaxWidth, false, &nBreakPos ); - if( (nStatus != noErr) && (nStatus != kATSULineBreakInWord) ) + if( (eStatus != noErr) && (eStatus != kATSULineBreakInWord) ) return STRING_LEN; // the result from ATSUBreakLine() doesn't match the semantics expected by its @@ -734,26 +759,6 @@ int ATSLayout::GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) cons if( nBreakPos >= static_cast(mnEndCharPos) ) return STRING_LEN; - // for the nCharExtra!=0 case the resulting nBreakPos needs be involved - if( nCharExtra != 0 ) - { - // age-old nCharExtra!=0 semantic is quite incompatible with ATSUBreakLine() - // TODO: use a better way than by testing each the char position - InitGIA(); - ATSUTextMeasurement nATSUSumWidth = 0; - const ATSUTextMeasurement nATSUMaxWidth = Vcl2Fixed( nMaxWidth / nFactor ); - const ATSUTextMeasurement nATSUExtraWidth = Vcl2Fixed( nCharExtra ) / nFactor; - for( int i = 0; i < mnCharCount; ++i) - { - nATSUSumWidth += mpCharWidths[i]; - if( nATSUSumWidth >= nATSUMaxWidth ) - return (mnMinCharPos + i); - nATSUSumWidth += nATSUExtraWidth; - } - - return STRING_LEN; - } - // GetTextBreak()'s callers expect it to return the "stupid visual line break". // Returning anything else result.s in subtle problems in the application layers. static const bool bInWord = true; // TODO: add as argument to GetTextBreak() method @@ -762,15 +767,15 @@ int ATSLayout::GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) cons // emulate stupid visual line breaking by line breaking for the remaining width ATSUTextMeasurement nLeft, nRight, nDummy; - nStatus = ATSUGetUnjustifiedBounds( maATSULayout, mnMinCharPos, nBreakPos-mnMinCharPos, + eStatus = ATSUGetUnjustifiedBounds( maATSULayout, mnMinCharPos, nBreakPos-mnMinCharPos, &nLeft, &nRight, &nDummy, &nDummy ); - if( nStatus != noErr ) + if( eStatus != noErr ) return nBreakPos; const ATSUTextMeasurement nATSURemWidth = nATSUMaxWidth - (nRight - nLeft); if( nATSURemWidth <= 0 ) return nBreakPos; UniCharArrayOffset nBreakPosInWord = nBreakPos; - nStatus = ATSUBreakLine( maATSULayout, nBreakPos, nATSURemWidth, false, &nBreakPosInWord ); + eStatus = ATSUBreakLine( maATSULayout, nBreakPos, nATSURemWidth, false, &nBreakPosInWord ); return nBreakPosInWord; } diff --git a/vcl/aqua/source/gdi/salatsuifontutils.cxx b/vcl/aqua/source/gdi/salatsuifontutils.cxx index 6c8fe86bdaef..595b7d276a2a 100644 --- a/vcl/aqua/source/gdi/salatsuifontutils.cxx +++ b/vcl/aqua/source/gdi/salatsuifontutils.cxx @@ -46,17 +46,17 @@ // and SFNT fonts on Mac usually do not contain an OS/2 table. static void UpdateAttributesFromPSName( const String& rPSName, ImplDevFontAttributes& rDFA ) { - // TODO: use a multi-string ignore-case matcher once it becomes available - String aPSName = rPSName; + ByteString aPSName( rPSName, RTL_TEXTENCODING_UTF8 ); aPSName.ToLowerAscii(); - if( (aPSName.SearchAscii("regular") != STRING_NOTFOUND) - || (aPSName.SearchAscii("normal") != STRING_NOTFOUND) - || (aPSName.SearchAscii("roman") != STRING_NOTFOUND) - || (aPSName.SearchAscii("medium") != STRING_NOTFOUND) - || (aPSName.SearchAscii("plain") != STRING_NOTFOUND) - || (aPSName.SearchAscii("standard") != STRING_NOTFOUND) - || (aPSName.SearchAscii("std") != STRING_NOTFOUND) ) + // TODO: use a multi-string ignore-case matcher once it becomes available + if( (aPSName.Search("regular") != STRING_NOTFOUND) + || (aPSName.Search("normal") != STRING_NOTFOUND) + || (aPSName.Search("roman") != STRING_NOTFOUND) + || (aPSName.Search("medium") != STRING_NOTFOUND) + || (aPSName.Search("plain") != STRING_NOTFOUND) + || (aPSName.Search("standard") != STRING_NOTFOUND) + || (aPSName.Search("std") != STRING_NOTFOUND) ) { rDFA.meWidthType = WIDTH_NORMAL; rDFA.meWeight = WEIGHT_NORMAL; @@ -64,110 +64,133 @@ static void UpdateAttributesFromPSName( const String& rPSName, ImplDevFontAttrib } // heuristics for font weight - if (aPSName.SearchAscii("extrablack") != STRING_NOTFOUND) + if (aPSName.Search("extrablack") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_BLACK; - else if (aPSName.SearchAscii("black") != STRING_NOTFOUND) + else if (aPSName.Search("black") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_BLACK; - //else if (aPSName.SearchAscii("book") != STRING_NOTFOUND) + //else if (aPSName.Search("book") != STRING_NOTFOUND) // rDFA.meWeight = WEIGHT_SEMIBOLD; - else if( (aPSName.SearchAscii("semibold") != STRING_NOTFOUND) - || (aPSName.SearchAscii("smbd") != STRING_NOTFOUND)) + else if( (aPSName.Search("semibold") != STRING_NOTFOUND) + || (aPSName.Search("smbd") != STRING_NOTFOUND)) rDFA.meWeight = WEIGHT_SEMIBOLD; - else if (aPSName.SearchAscii("ultrabold") != STRING_NOTFOUND) + else if (aPSName.Search("ultrabold") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_ULTRABOLD; - else if (aPSName.SearchAscii("extrabold") != STRING_NOTFOUND) + else if (aPSName.Search("extrabold") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_BLACK; - else if( (aPSName.SearchAscii("bold") != STRING_NOTFOUND) - || (aPSName.SearchAscii("-bd") != STRING_NOTFOUND)) + else if( (aPSName.Search("bold") != STRING_NOTFOUND) + || (aPSName.Search("-bd") != STRING_NOTFOUND)) rDFA.meWeight = WEIGHT_BOLD; - else if (aPSName.SearchAscii("extralight") != STRING_NOTFOUND) + else if (aPSName.Search("extralight") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_ULTRALIGHT; - else if (aPSName.SearchAscii("ultralight") != STRING_NOTFOUND) + else if (aPSName.Search("ultralight") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_ULTRALIGHT; - else if (aPSName.SearchAscii("light") != STRING_NOTFOUND) + else if (aPSName.Search("light") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_LIGHT; - else if (aPSName.SearchAscii("thin") != STRING_NOTFOUND) + else if (aPSName.Search("thin") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_THIN; - else if (aPSName.SearchAscii("-w3") != STRING_NOTFOUND) + else if (aPSName.Search("-w3") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_LIGHT; - else if (aPSName.SearchAscii("-w4") != STRING_NOTFOUND) + else if (aPSName.Search("-w4") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_SEMILIGHT; - else if (aPSName.SearchAscii("-w5") != STRING_NOTFOUND) + else if (aPSName.Search("-w5") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_NORMAL; - else if (aPSName.SearchAscii("-w6") != STRING_NOTFOUND) + else if (aPSName.Search("-w6") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_SEMIBOLD; - else if (aPSName.SearchAscii("-w7") != STRING_NOTFOUND) + else if (aPSName.Search("-w7") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_BOLD; - else if (aPSName.SearchAscii("-w8") != STRING_NOTFOUND) + else if (aPSName.Search("-w8") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_ULTRABOLD; - else if (aPSName.SearchAscii("-w9") != STRING_NOTFOUND) + else if (aPSName.Search("-w9") != STRING_NOTFOUND) rDFA.meWeight = WEIGHT_BLACK; // heuristics for font slant - if( (aPSName.SearchAscii("italic") != STRING_NOTFOUND) - || (aPSName.SearchAscii(" ital") != STRING_NOTFOUND) - || (aPSName.SearchAscii("cursive") != STRING_NOTFOUND) - || (aPSName.SearchAscii("-it") != STRING_NOTFOUND) - || (aPSName.SearchAscii("lightit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("mediumit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("boldit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("cnit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("bdcn") != STRING_NOTFOUND) - || (aPSName.SearchAscii("bdit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("condit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("bookit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("blackit") != STRING_NOTFOUND) - || (aPSName.SearchAscii("libertineio") != STRING_NOTFOUND) ) + if( (aPSName.Search("italic") != STRING_NOTFOUND) + || (aPSName.Search(" ital") != STRING_NOTFOUND) + || (aPSName.Search("cursive") != STRING_NOTFOUND) + || (aPSName.Search("-it") != STRING_NOTFOUND) + || (aPSName.Search("lightit") != STRING_NOTFOUND) + || (aPSName.Search("mediumit") != STRING_NOTFOUND) + || (aPSName.Search("boldit") != STRING_NOTFOUND) + || (aPSName.Search("cnit") != STRING_NOTFOUND) + || (aPSName.Search("bdcn") != STRING_NOTFOUND) + || (aPSName.Search("bdit") != STRING_NOTFOUND) + || (aPSName.Search("condit") != STRING_NOTFOUND) + || (aPSName.Search("bookit") != STRING_NOTFOUND) + || (aPSName.Search("blackit") != STRING_NOTFOUND) ) rDFA.meItalic = ITALIC_NORMAL; - if( (aPSName.SearchAscii("oblique") != STRING_NOTFOUND) - || (aPSName.SearchAscii("inclined") != STRING_NOTFOUND) - || (aPSName.SearchAscii("slanted") != STRING_NOTFOUND) ) + if( (aPSName.Search("oblique") != STRING_NOTFOUND) + || (aPSName.Search("inclined") != STRING_NOTFOUND) + || (aPSName.Search("slanted") != STRING_NOTFOUND) ) rDFA.meItalic = ITALIC_OBLIQUE; // heuristics for font width - if( (aPSName.SearchAscii("condensed") != STRING_NOTFOUND) - || (aPSName.SearchAscii("-cond") != STRING_NOTFOUND) - || (aPSName.SearchAscii("boldcond") != STRING_NOTFOUND) - || (aPSName.SearchAscii("boldcn") != STRING_NOTFOUND) - || (aPSName.SearchAscii("cnit") != STRING_NOTFOUND) ) + if( (aPSName.Search("condensed") != STRING_NOTFOUND) + || (aPSName.Search("-cond") != STRING_NOTFOUND) + || (aPSName.Search("boldcond") != STRING_NOTFOUND) + || (aPSName.Search("boldcn") != STRING_NOTFOUND) + || (aPSName.Search("cnit") != STRING_NOTFOUND) ) rDFA.meWidthType = WIDTH_CONDENSED; - else if (aPSName.SearchAscii("narrow") != STRING_NOTFOUND) + else if (aPSName.Search("narrow") != STRING_NOTFOUND) rDFA.meWidthType = WIDTH_SEMI_CONDENSED; - else if (aPSName.SearchAscii("expanded") != STRING_NOTFOUND) + else if (aPSName.Search("expanded") != STRING_NOTFOUND) rDFA.meWidthType = WIDTH_EXPANDED; - else if (aPSName.SearchAscii("wide") != STRING_NOTFOUND) + else if (aPSName.Search("wide") != STRING_NOTFOUND) rDFA.meWidthType = WIDTH_EXPANDED; // heuristics for font pitch - if( (aPSName.SearchAscii("mono") != STRING_NOTFOUND) - || (aPSName.SearchAscii("courier") != STRING_NOTFOUND) - || (aPSName.SearchAscii("monaco") != STRING_NOTFOUND) - || (aPSName.SearchAscii("typewriter") != STRING_NOTFOUND) ) + if( (aPSName.Search("mono") != STRING_NOTFOUND) + || (aPSName.Search("courier") != STRING_NOTFOUND) + || (aPSName.Search("monaco") != STRING_NOTFOUND) + || (aPSName.Search("typewriter") != STRING_NOTFOUND) ) rDFA.mePitch = PITCH_FIXED; // heuristics for font family type - if( (aPSName.SearchAscii("script") != STRING_NOTFOUND) - || (aPSName.SearchAscii("chancery") != STRING_NOTFOUND) - || (aPSName.SearchAscii("zapfino") != STRING_NOTFOUND)) + if( (aPSName.Search("script") != STRING_NOTFOUND) + || (aPSName.Search("chancery") != STRING_NOTFOUND) + || (aPSName.Search("zapfino") != STRING_NOTFOUND)) rDFA.meFamily = FAMILY_SCRIPT; - else if( (aPSName.SearchAscii("comic") != STRING_NOTFOUND) - || (aPSName.SearchAscii("outline") != STRING_NOTFOUND) - || (aPSName.SearchAscii("pinpoint") != STRING_NOTFOUND) ) + else if( (aPSName.Search("comic") != STRING_NOTFOUND) + || (aPSName.Search("outline") != STRING_NOTFOUND) + || (aPSName.Search("pinpoint") != STRING_NOTFOUND) ) rDFA.meFamily = FAMILY_DECORATIVE; - else if( (aPSName.SearchAscii("sans") != STRING_NOTFOUND) - || (aPSName.SearchAscii("arial") != STRING_NOTFOUND) ) + else if( (aPSName.Search("sans") != STRING_NOTFOUND) + || (aPSName.Search("arial") != STRING_NOTFOUND) ) rDFA.meFamily = FAMILY_SWISS; - else if( (aPSName.SearchAscii("roman") != STRING_NOTFOUND) - || (aPSName.SearchAscii("times") != STRING_NOTFOUND) ) + else if( (aPSName.Search("roman") != STRING_NOTFOUND) + || (aPSName.Search("times") != STRING_NOTFOUND) ) rDFA.meFamily = FAMILY_ROMAN; // heuristics for codepoint semantic - if( (aPSName.SearchAscii("symbol") != STRING_NOTFOUND) - || (aPSName.SearchAscii("dings") != STRING_NOTFOUND) - || (aPSName.SearchAscii("dingbats") != STRING_NOTFOUND) - || (aPSName.SearchAscii("ornaments") != STRING_NOTFOUND) - || (aPSName.SearchAscii("embellishments") != STRING_NOTFOUND) ) + if( (aPSName.Search("symbol") != STRING_NOTFOUND) + || (aPSName.Search("dings") != STRING_NOTFOUND) + || (aPSName.Search("dingbats") != STRING_NOTFOUND) + || (aPSName.Search("ornaments") != STRING_NOTFOUND) + || (aPSName.Search("embellishments") != STRING_NOTFOUND) ) rDFA.mbSymbolFlag = true; + + // #i100020# special heuristic for names with single-char styles + // NOTE: we are checking name that hasn't been lower-cased + if( rPSName.Len() > 3 ) + { + int i = rPSName.Len(); + sal_Unicode c = rPSName.GetChar( --i ); + if( c == 'C' ) { // "capitals" + rDFA.meFamily = FAMILY_DECORATIVE; + c = rPSName.GetChar( --i ); + } + if( c == 'O' ) { // CFF-based OpenType + c = rPSName.GetChar( --i ); + } + if( c == 'I' ) { // "italic" + rDFA.meItalic = ITALIC_NORMAL; + c = rPSName.GetChar( --i ); + } + if( c == 'B' ) // "bold" + rDFA.meWeight = WEIGHT_BOLD; + if( c == 'C' ) // "capitals" + rDFA.meFamily = FAMILY_DECORATIVE; + // TODO: check that all single-char styles have been resolved? + } } // ----------------------------------------------------------------------- @@ -231,9 +254,9 @@ static bool GetDevFontAttributes( ATSUFontID nFontID, ImplDevFontAttributes& rDF continue; // heuristic to find the most common font name - // prefering default language names or even better the names matching to the UI language + // prefering default language names or even better the names matching to the UI language int nNameValue = (eFontNameLanguage==eUILangCode) ? 0 : ((eFontNameLanguage==0) ? -10 : -20); - rtl_TextEncoding eEncoding = RTL_TEXTENCODING_UNICODE; + rtl_TextEncoding eEncoding = RTL_TEXTENCODING_UNICODE; const int nPlatformEncoding = ((int)eFontNamePlatform << 8) + (int)eFontNameScript; switch( nPlatformEncoding ) { @@ -259,6 +282,8 @@ static bool GetDevFontAttributes( ATSUFontID nFontID, ImplDevFontAttributes& rDF // ignore name entries with no useful encoding if( nNameValue <= 0 ) continue; + if( nNameLength >= aNameBuffer.size() ) + continue; // get the encoded name aNameBuffer.reserve( nNameLength+1 ); // extra byte helps for debugging @@ -306,7 +331,7 @@ static bool GetDevFontAttributes( ATSUFontID nFontID, ImplDevFontAttributes& rDF case kFontStyleName: // get a style name matching to the family name if( nBestStyleValue < nNameValue ) - { + { nBestStyleValue = nNameValue; rDFA.maStyleName = aUtf16Name; } diff --git a/vcl/aqua/source/gdi/salgdi.cxx b/vcl/aqua/source/gdi/salgdi.cxx index c39dc26f370f..661eb64b83ce 100644 --- a/vcl/aqua/source/gdi/salgdi.cxx +++ b/vcl/aqua/source/gdi/salgdi.cxx @@ -36,8 +36,7 @@ #include "salbmp.h" #include "salframe.h" #include "salcolorutils.hxx" -#include "list.h" -#include "sft.h" +#include "sft.hxx" #include "salatsuifontutils.hxx" #include "vcl/impfont.hxx" @@ -58,6 +57,8 @@ #include "basegfx/polygon/b2dpolygontools.hxx" #include "basegfx/matrix/b2dhommatrix.hxx" +using namespace vcl; + typedef unsigned char Boolean; // copied from MacTypes.h, should be properly included typedef std::vector ByteVector; @@ -400,19 +401,8 @@ void AquaSalGraphics::initResolution( NSWindow* pWin ) DBG_ERROR( "no screen found" ); } - // equalize x- and y-resolution if they are close enough to prevent unneeded font stretching - if( (mnRealDPIX != mnRealDPIY) - && (10*mnRealDPIX < 13*mnRealDPIY) && (13*mnRealDPIX > 10*mnRealDPIY) ) - { - mnRealDPIX = mnRealDPIY = (mnRealDPIX + mnRealDPIY + 1) / 2; - } - else // #i89650# workaround bogus device resolutions - { - if( mnRealDPIY < 72 ) - mnRealDPIY = 72; - if( mnRealDPIX < mnRealDPIY ) // e.g. for TripleHead2Go only mnRealDPIX is off - mnRealDPIX = mnRealDPIY; - } + // for OSX any anisotropy reported for the display resolution is best ignored (e.g. TripleHead2Go) + mnRealDPIX = mnRealDPIY = (mnRealDPIX + mnRealDPIY + 1) / 2; mfFakeDPIScale = 1.0; } diff --git a/vcl/aqua/source/window/salframeview.mm b/vcl/aqua/source/window/salframeview.mm index b491318bbb0d..e291dae911cf 100755 --- a/vcl/aqua/source/window/salframeview.mm +++ b/vcl/aqua/source/window/salframeview.mm @@ -922,7 +922,7 @@ private: // applications and vcl's edit fields ignore key events with ALT // however we're at a place where we know text should be inserted // so it seems we need to strip the Alt modifier here - if( (nLastModifiers & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask)) + if( (nLastModifiers & (NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask)) == NSAlternateKeyMask ) { nLastModifiers = 0; diff --git a/vcl/aqua/source/window/salmenu.cxx b/vcl/aqua/source/window/salmenu.cxx index 9b4499cc1233..4fafbbdbb4cf 100644 --- a/vcl/aqua/source/window/salmenu.cxx +++ b/vcl/aqua/source/window/salmenu.cxx @@ -521,7 +521,7 @@ BOOL AquaSalMenu::VisibleMenuBar() static const char *pExperimental = getenv ("AQUA_NATIVE_MENUS"); - if ( GetSalData()->mbIsTestTool || (pExperimental && !strcasecmp(pExperimental, "FALSE")) ) + if ( ImplGetSVData()->mbIsTestTool || (pExperimental && !strcasecmp(pExperimental, "FALSE")) ) return FALSE; // End of experimental code enable/disable part diff --git a/vcl/aqua/source/window/salobj.cxx b/vcl/aqua/source/window/salobj.cxx index abbea052c3d6..79da1b155cad 100644 --- a/vcl/aqua/source/window/salobj.cxx +++ b/vcl/aqua/source/window/salobj.cxx @@ -37,11 +37,6 @@ #include "salobj.h" #include "salframe.h" -// get QTMovieView -#include "premac.h" -#include -#include "postmac.h" - // ======================================================================= AquaSalObject::AquaSalObject( AquaSalFrame* pFrame ) : @@ -66,7 +61,7 @@ AquaSalObject::AquaSalObject( AquaSalFrame* pFrame ) : [mpFrame->getView() addSubview: mpClipView]; [mpClipView setHidden: YES]; } - maSysData.pView = [[QTMovieView alloc] initWithFrame: aInitFrame]; + maSysData.pView = [[NSView alloc] initWithFrame: aInitFrame]; if( maSysData.pView ) { if( mpClipView ) diff --git a/vcl/inc/list.h b/vcl/inc/list.h index b86521a1f666..b801b43d77eb 100644 --- a/vcl/inc/list.h +++ b/vcl/inc/list.h @@ -51,6 +51,7 @@ extern "C" */ typedef struct _list *list; + typedef void (*list_destructor)(void *); /*- constructors and a destructor */ list listNewEmpty(void); @@ -58,7 +59,7 @@ extern "C" list listNewCopy(list); #endif void listDispose(list); - void listSetElementDtor(list, void (*f)(void *)); /*- this function will be executed when the element is removed via listRemove() or listClear() */ + void listSetElementDtor(list, list_destructor); /*- this function will be executed when the element is removed via listRemove() or listClear() */ /*- queries */ void * listCurrent(list); diff --git a/vcl/inc/sft.h b/vcl/inc/sft.h deleted file mode 100644 index efda0903afc5..000000000000 --- a/vcl/inc/sft.h +++ /dev/null @@ -1,641 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: sft.h,v $ - * $Revision: 1.21 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: sft.h,v 1.21 2008-06-25 14:20:49 kz Exp $ */ - -/** - - * - * @file sft.h - * @brief Sun Font Tools - * @author Alexander Gelfenbain - */ - -/* - * If NO_MAPPERS is defined, MapChar() and MapString() and consequently GetTTSimpleCharMetrics() - * don't get compiled in. This is done to avoid including a large chunk of code (TranslateXY() from - * xlat.c in the projects that don't require it. - * - * If NO_TYPE3 is defined CreateT3FromTTGlyphs() does not get compiled in. - * If NO_TYPE42 is defined Type42-related code is excluded - * If NO_TTCR is defined TrueType creation related code is excluded\ - * If NO_LIST is defined list.h and piblic functions that use it don't get compiled - */ - -/* - * Generated fonts contain an XUID entry in the form of: - * - * 103 0 T C1 N C2 C3 - * - * 103 - Sun's Adobe assigned XUID number. Contact person: Alexander Gelfenbain - * - * T - font type. 0: Type 3, 1: Type 42 - * C1 - CRC-32 of the entire source TrueType font - * N - number of glyphs in the subset - * C2 - CRC-32 of the array of glyph IDs used to generate the subset - * C3 - CRC-32 of the array of encoding numbers used to generate the subset - * - */ - - -#ifndef __SUBFONT_H -#define __SUBFONT_H - -#ifdef UNX -#include -#include -#endif -#include - -#include - -#ifndef NO_LIST -#include "list.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/*@{*/ -#ifndef __cplusplus -#define false 0 /**< standard false value */ -#define true 1 /**< standard true value */ -#endif -/*@}*/ - -/*@{*/ - typedef sal_Int16 F2Dot14; /**< fixed: 2.14 */ - typedef sal_Int32 F16Dot16; /**< fixed: 16.16 */ -/*@}*/ - - typedef struct { - sal_uInt16 s; - sal_uInt16 d; - } sal_uInt16pair; - -/** Return value of OpenTTFont() and CreateT3FromTTGlyphs() */ - enum SFErrCodes { - SF_OK, /**< no error */ - SF_BADFILE, /**< file not found */ - SF_FILEIO, /**< file I/O error */ - SF_MEMORY, /**< memory allocation error */ - SF_GLYPHNUM, /**< incorrect number of glyphs */ - SF_BADARG, /**< incorrect arguments */ - SF_TTFORMAT, /**< incorrect TrueType font format */ - SF_TABLEFORMAT, /**< incorrect format of a TrueType table */ - SF_FONTNO /**< incorrect logical font number of a TTC font */ - }; - -#ifndef FW_THIN /* WIN32 compilation would conflict */ -/** Value of the weight member of the TTGlobalFontInfo struct */ - enum WeightClass { - FW_THIN = 100, /**< Thin */ - FW_EXTRALIGHT = 200, /**< Extra-light (Ultra-light) */ - FW_LIGHT = 300, /**< Light */ - FW_NORMAL = 400, /**< Normal (Regular) */ - FW_MEDIUM = 500, /**< Medium */ - FW_SEMIBOLD = 600, /**< Semi-bold (Demi-bold) */ - FW_BOLD = 700, /**< Bold */ - FW_EXTRABOLD = 800, /**< Extra-bold (Ultra-bold) */ - FW_BLACK = 900 /**< Black (Heavy) */ - }; - -/** Value of the width member of the TTGlobalFontInfo struct */ -#ifndef OS2 - enum WidthClass { - FWIDTH_ULTRA_CONDENSED = 1, /**< 50% of normal */ - FWIDTH_EXTRA_CONDENSED = 2, /**< 62.5% of normal */ - FWIDTH_CONDENSED = 3, /**< 75% of normal */ - FWIDTH_SEMI_CONDENSED = 4, /**< 87.5% of normal */ - FWIDTH_NORMAL = 5, /**< Medium, 100% */ - FWIDTH_SEMI_EXPANDED = 6, /**< 112.5% of normal */ - FWIDTH_EXPANDED = 7, /**< 125% of normal */ - FWIDTH_EXTRA_EXPANDED = 8, /**< 150% of normal */ - FWIDTH_ULTRA_EXPANDED = 9 /**< 200% of normal */ - }; -#endif // OS2 -#endif /* FW_THIN */ - -/** Type of the 'kern' table, stored in _TrueTypeFont::kerntype */ - enum KernType { - KT_NONE = 0, /**< no kern table */ - KT_APPLE_NEW = 1, /**< new Apple kern table */ - KT_MICROSOFT = 2 /**< Microsoft table */ - }; - -/* Composite glyph flags definition */ - enum CompositeFlags { - ARG_1_AND_2_ARE_WORDS = 1, - ARGS_ARE_XY_VALUES = 1<<1, - ROUND_XY_TO_GRID = 1<<2, - WE_HAVE_A_SCALE = 1<<3, - MORE_COMPONENTS = 1<<5, - WE_HAVE_AN_X_AND_Y_SCALE = 1<<6, - WE_HAVE_A_TWO_BY_TWO = 1<<7, - WE_HAVE_INSTRUCTIONS = 1<<8, - USE_MY_METRICS = 1<<9, - OVERLAP_COMPOUND = 1<<10 - }; - -#ifndef NO_TTCR -/** Flags for TrueType generation */ - enum TTCreationFlags { - TTCF_AutoName = 1, /**< Automatically generate a compact 'name' table. - If this flag is not set, name table is generated - either from an array of NameRecord structs passed as - arguments or if the array is NULL, 'name' table - of the generated TrueType file will be a copy - of the name table of the original file. - If this flag is set the array of NameRecord structs - is ignored and a very compact 'name' table is automatically - generated. */ - - TTCF_IncludeOS2 = 2 /** If this flag is set OS/2 table from the original font will be - copied to the subset */ - }; -#endif - - - - -/** Structure used by GetTTSimpleGlyphMetrics() and GetTTSimpleCharMetrics() functions */ - typedef struct { - sal_uInt16 adv; /**< advance width or height */ - sal_Int16 sb; /**< left or top sidebearing */ - } TTSimpleGlyphMetrics; - - - -/** Structure used by the TrueType Creator and GetRawGlyphData() */ - - typedef struct { - sal_uInt32 glyphID; /**< glyph ID */ - sal_uInt16 nbytes; /**< number of bytes in glyph data */ - sal_uInt8 *ptr; /**< pointer to glyph data */ - sal_uInt16 aw; /**< advance width */ - sal_Int16 lsb; /**< left sidebearing */ - sal_uInt16 compflag; /**< 0- if non-composite, 1- otherwise */ - sal_uInt16 npoints; /**< number of points */ - sal_uInt16 ncontours; /**< number of contours */ - /* */ - sal_uInt32 newID; /**< used internally by the TTCR */ - } GlyphData; - -/** Structure used by the TrueType Creator and CreateTTFromTTGlyphs() */ - typedef struct { - sal_uInt16 platformID; /**< Platform ID */ - sal_uInt16 encodingID; /**< Platform-specific encoding ID */ - sal_uInt16 languageID; /**< Language ID */ - sal_uInt16 nameID; /**< Name ID */ - sal_uInt16 slen; /**< String length in bytes */ - sal_uInt8 *sptr; /**< Pointer to string data (not zero-terminated!) */ - } NameRecord; - - - -/** Return value of GetTTGlobalFontInfo() */ - - typedef struct { - char *family; /**< family name */ - sal_uInt16 *ufamily; /**< family name UCS2 */ - char *subfamily; /**< subfamily name */ - sal_uInt16 *usubfamily; /**< subfamily name UCS2 */ - char *psname; /**< PostScript name */ - sal_uInt16 macStyle; /**< macstyle bits from 'HEAD' table */ - int weight; /**< value of WeightClass or 0 if can't be determined */ - int width; /**< value of WidthClass or 0 if can't be determined */ - int pitch; /**< 0: proportianal font, otherwise: monospaced */ - int italicAngle; /**< in counter-clockwise degrees * 65536 */ - int xMin; /**< global bounding box: xMin */ - int yMin; /**< global bounding box: yMin */ - int xMax; /**< global bounding box: xMax */ - int yMax; /**< global bounding box: yMax */ - int ascender; /**< typographic ascent. */ - int descender; /**< typographic descent. */ - int linegap; /**< typographic line gap.\ Negative values are treated as - zero in Win 3.1, System 6 and System 7. */ - int vascent; /**< typographic ascent for vertical writing mode */ - int vdescent; /**< typographic descent for vertical writing mode */ - int typoAscender; /**< OS/2 portable typographic ascender */ - int typoDescender; /**< OS/2 portable typographic descender */ - int typoLineGap; /**< OS/2 portable typographc line gap */ - int winAscent; /**< ascender metric for Windows */ - int winDescent; /**< descender metric for Windows */ - int symbolEncoded; /**< 1: MS symbol encoded 0: not symbol encoded */ - int rangeFlag; /**< if set to 1 Unicode Range flags are applicable */ - sal_uInt32 ur1; /**< bits 0 - 31 of Unicode Range flags */ - sal_uInt32 ur2; /**< bits 32 - 63 of Unicode Range flags */ - sal_uInt32 ur3; /**< bits 64 - 95 of Unicode Range flags */ - sal_uInt32 ur4; /**< bits 96 - 127 of Unicode Range flags */ - sal_uInt8 panose[10]; /**< PANOSE classification number */ - sal_uInt16 typeFlags; /**< type flags (copyright information) */ - } TTGlobalFontInfo; - -/** Structure used by KernGlyphs() */ - typedef struct { - int x; /**< positive: right, negative: left */ - int y; /**< positive: up, negative: down */ - } KernData; - - -/** ControlPoint structure used by GetTTGlyphPoints() */ - typedef struct { - sal_uInt32 flags; /**< 00000000 00000000 e0000000 bbbbbbbb */ - /**< b - byte flags from the glyf array */ - /**< e == 0 - regular point */ - /**< e == 1 - end contour */ - sal_Int16 x; /**< X coordinate in EmSquare units */ - sal_Int16 y; /**< Y coordinate in EmSquare units */ - } ControlPoint; - - typedef struct _TrueTypeFont TrueTypeFont; - -/** - * @defgroup sft Sun Font Tools Exported Functions - */ - - -/** - * Get the number of fonts contained in a TrueType collection - * @param fname - file name - * @return number of fonts or zero, if file is not a TTC file. - * @ingroup sft - */ - int CountTTCFonts(const char* fname); - - -/** - * TrueTypeFont constructor. - * The font file has to be provided as a memory buffer and length - * @param facenum - logical font number within a TTC file. This value is ignored - * for TrueType fonts - * @return value of SFErrCodes enum - * @ingroup sft - */ - int OpenTTFontBuffer(void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf); /*FOLD01*/ -#if !defined(WIN32) && !defined(OS2) -/** - * TrueTypeFont constructor. - * Reads the font file and allocates the memory for the structure. - * on WIN32 the font has to be provided as a memory buffer and length - * @param facenum - logical font number within a TTC file. This value is ignored - * for TrueType fonts - * @return value of SFErrCodes enum - * @ingroup sft - */ - int OpenTTFontFile(const char *fname, sal_uInt32 facenum, TrueTypeFont** ttf); -#endif - -/** - * TrueTypeFont destructor. Deallocates the memory. - * @ingroup sft - */ - void CloseTTFont(TrueTypeFont *); - -/** - * Extracts TrueType control points, and stores them in an allocated array pointed to - * by *pointArray. This function returns the number of extracted points. - * - * @param ttf pointer to the TrueTypeFont structure - * @param glyphID Glyph ID - * @param pointArray Return value - address of the pointer to the first element of the array - * of points allocated by the function - * @return Returns the number of points in *pointArray or -1 if glyphID is - * invalid. - * @ingroup sft - * - */ - int GetTTGlyphPoints(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray); - -/** - * Extracts raw glyph data from the 'glyf' table and returns it in an allocated - * GlyphData structure. - * - * @param ttf pointer to the TrueTypeFont structure - * @param glyphID Glyph ID - * - * @return pointer to an allocated GlyphData structure or NULL if - * glyphID is not present in the font - * @ingroup sft - * - */ - GlyphData *GetTTRawGlyphData(TrueTypeFont *ttf, sal_uInt32 glyphID); - -#ifndef NO_LIST -/** - * For a specified glyph adds all component glyphs IDs to the list and - * return their number. If the glyph is a single glyph it has one component - * glyph (which is added to the list) and the function returns 1. - * For a composite glyphs it returns the number of component glyphs - * and adds all of them to the list. - * - * @param ttf pointer to the TrueTypeFont structure - * @param glyphID Glyph ID - * @param glyphlist list of glyphs - * - * @return number of component glyphs - * @ingroup sft - * - */ - int GetTTGlyphComponents(TrueTypeFont *ttf, sal_uInt32 glyphID, list glyphlist); -#endif - -/** - * Extracts all Name Records from the font and stores them in an allocated - * array of NameRecord structs - * - * @param ttf pointer to the TrueTypeFont struct - * @param nr pointer to the array of NameRecord structs - * - * @return number of NameRecord structs - * @ingroup sft - */ - - int GetTTNameRecords(TrueTypeFont *ttf, NameRecord **nr); - -/** - * Deallocates previously allocated array of NameRecords. - * - * @param nr array of NameRecord structs - * @param n number of elements in the array - * - * @ingroup sft - */ - void DisposeNameRecords(NameRecord* nr, int n); - - -#ifndef NO_TYPE3 -/** - * Generates a new PostScript Type 3 font and dumps it to outf file. - * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. - * @param ttf pointer to the TrueTypeFont structure - * @param outf the resulting font is written to this stream - * @param fname font name for the new font. If it is NULL the PostScript name of the - * original font will be used - * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf - * @param encoding array of encoding values. encoding[i] specifies the position of the glyph - * glyphArray[i] in the encoding vector of the resulting Type3 font - * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding - * @param wmode writing mode for the output file: 0 - horizontal, 1 - vertical - * @return return the value of SFErrCodes enum - * @see SFErrCodes - * @ingroup sft - * - */ - int CreateT3FromTTGlyphs(TrueTypeFont *ttf, FILE *outf, const char *fname, sal_uInt16 *glyphArray, sal_uInt8 *encoding, int nGlyphs, int wmode); -#endif - -#ifndef NO_TTCR -/** - * Generates a new TrueType font and dumps it to outf file. - * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. - * @param ttf pointer to the TrueTypeFont structure - * @param fname file name for the output TrueType font file - * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf. The first - * element of this array has to be glyph 0 (default glyph) - * @param encoding array of encoding values. encoding[i] specifies character code for - * the glyphID glyphArray[i]. Character code 0 usually points to a default - * glyph (glyphID 0) - * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding - * @param nNameRecs number of NameRecords for the font, if 0 the name table from the - * original font will be used - * @param nr array of NameRecords - * @param flags or'ed TTCreationFlags - * @return return the value of SFErrCodes enum - * @see SFErrCodes - * @ingroup sft - * - */ - int CreateTTFromTTGlyphs(TrueTypeFont *ttf, - const char *fname, - sal_uInt16 *glyphArray, - sal_uInt8 *encoding, - int nGlyphs, - int nNameRecs, - NameRecord *nr, - sal_uInt32 flags); -#endif - -#ifndef NO_TYPE42 -/** - * Generates a new PostScript Type42 font and dumps it to outf file. - * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. - * @param ttf pointer to the TrueTypeFont structure - * @param outf output stream for a resulting font - * @param psname PostScript name of the resulting font - * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf. The first - * element of this array has to be glyph 0 (default glyph) - * @param encoding array of encoding values. encoding[i] specifies character code for - * the glyphID glyphArray[i]. Character code 0 usually points to a default - * glyph (glyphID 0) - * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding - * @return SF_OK - no errors - * SF_GLYPHNUM - too many glyphs (> 255) - * SF_TTFORMAT - corrupted TrueType fonts - * - * @see SFErrCodes - * @ingroup sft - * - */ - int CreateT42FromTTGlyphs(TrueTypeFont *ttf, - FILE *outf, - const char *psname, - sal_uInt16 *glyphArray, - sal_uInt8 *encoding, - int nGlyphs); -#endif - - -/** - * Queries glyph metrics. Allocates an array of TTSimpleGlyphMetrics structs and returns it. - * - * @param ttf pointer to the TrueTypeFont structure - * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf - * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding - * @param mode writing mode: 0 - horizontal, 1 - vertical - * @ingroup sft - * - */ - TTSimpleGlyphMetrics *GetTTSimpleGlyphMetrics(TrueTypeFont *ttf, sal_uInt16 *glyphArray, int nGlyphs, int mode); - -#ifndef NO_MAPPERS -/** - * Queries glyph metrics. Allocates an array of TTSimpleGlyphMetrics structs and returns it. - * This function behaves just like GetTTSimpleGlyphMetrics() but it takes a range of Unicode - * characters instead of an array of glyphs. - * - * @param ttf pointer to the TrueTypeFont structure - * @param firstChar Unicode value of the first character in the range - * @param nChars number of Unicode characters in the range - * @param mode writing mode: 0 - horizontal, 1 - vertical - * - * @see GetTTSimpleGlyphMetrics - * @ingroup sft - * - */ - TTSimpleGlyphMetrics *GetTTSimpleCharMetrics(TrueTypeFont *ttf, sal_uInt16 firstChar, int nChars, int mode); - -/** - * Maps a Unicode (UCS-2) string to a glyph array. Returns the number of glyphs in the array, - * which for TrueType fonts is always the same as the number of input characters. - * - * @param ttf pointer to the TrueTypeFont structure - * @param str pointer to a UCS-2 string - * @param nchars number of characters in str - * @param glyphArray pointer to the glyph array where glyph IDs are to be recorded. - * - * @return MapString() returns -1 if the TrueType font has no usable 'cmap' tables. - * Otherwise it returns the number of characters processed: nChars - * - * glyphIDs of TrueType fonts are 2 byte positive numbers. glyphID of 0 denotes a missing - * glyph and traditionally defaults to an empty square. - * glyphArray should be at least sizeof(sal_uInt16) * nchars bytes long. If glyphArray is NULL - * MapString() replaces the UCS-2 characters in str with glyphIDs. - * @ingroup sft - */ - int MapString(TrueTypeFont *ttf, sal_uInt16 *str, int nchars, sal_uInt16 *glyphArray, int bvertical); - -/** - * Maps a Unicode (UCS-2) character to a glyph ID and returns it. Missing glyph has - * a glyphID of 0 so this function can be used to test if a character is encoded in the font. - * - * @param ttf pointer to the TrueTypeFont structure - * @param ch Unicode (UCS-2) character - * @return glyph ID, if the character is missing in the font, the return value is 0. - * @ingroup sft - */ - sal_uInt16 MapChar(TrueTypeFont *ttf, sal_uInt16 ch, int bvertical); - -/** - * Returns 0 when the font does not substitute vertical glyphs - * - * @param ttf pointer to the TrueTypeFont structure - */ - int DoesVerticalSubstitution( TrueTypeFont *ttf, int bvertical); - -#endif - -/** - * Returns global font information about the TrueType font. - * @see TTGlobalFontInfo - * - * @param ttf pointer to a TrueTypeFont structure - * @param info pointer to a TTGlobalFontInfo structure - * @ingroup sft - * - */ - void GetTTGlobalFontInfo(TrueTypeFont *ttf, TTGlobalFontInfo *info); - -#ifdef TEST5 -/** - * Returns kerning information for an array of glyphs. - * Kerning is not cumulative. - * kern[i] contains kerning information for a pair of glyphs at positions i and i+1 - * - * @param ttf pointer to a TrueTypeFont structure - * @param glyphs array of source glyphs - * @param nglyphs number of glyphs in the array - * @param wmode writing mode: 0 - horizontal, 1 - vertical - * @param kern array of KernData structures. It should contain nglyphs-1 elements - * @see KernData - * @ingroup sft - * - */ - void KernGlyphs(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern); -#endif - -/** - * Returns nonzero if font is a symbol encoded font - */ - int CheckSymbolEncoding(TrueTypeFont* ttf); - -/** - * returns the number of glyphs in a font - */ - int GetTTGlyphCount( TrueTypeFont* ttf ); - -/*- private definitions */ /*FOLD00*/ - - struct _TrueTypeFont { - sal_uInt32 tag; - - char *fname; - sal_Int32 fsize; - sal_uInt8 *ptr; - - char *psname; - char *family; - sal_uInt16 *ufamily; - char *subfamily; - sal_uInt16 *usubfamily; - - sal_uInt32 ntables; - sal_uInt32 *goffsets; - sal_uInt32 nglyphs; - sal_uInt32 unitsPerEm; - sal_uInt32 numberOfHMetrics; - sal_uInt32 numOfLongVerMetrics; /* if this number is not 0, font has vertical metrics information */ - sal_uInt8 *cmap; - int cmapType; - sal_uInt32 (*mapper)(const sal_uInt8 *, sal_uInt32); /* character to glyphID translation function */ - void **tables; /* array of pointers to tables */ - sal_uInt32 *tlens; /* array of table lengths */ - int kerntype; /* Defined in the KernType enum */ - sal_uInt32 nkern; /* number of kern subtables */ - sal_uInt8 **kerntables; /* array of pointers to kern subtables */ - void *pGSubstitution; /* info provided by GSUB for UseGSUB() */ - }; - -#ifdef __cplusplus -} -#endif - -/* indexes into _TrueTypeFont::tables[] and _TrueTypeFont::tlens[] */ -#define O_maxp 0 /* 'maxp' */ -#define O_glyf 1 /* 'glyf' */ -#define O_head 2 /* 'head' */ -#define O_loca 3 /* 'loca' */ -#define O_name 4 /* 'name' */ -#define O_hhea 5 /* 'hhea' */ -#define O_hmtx 6 /* 'hmtx' */ -#define O_cmap 7 /* 'cmap' */ -#define O_vhea 8 /* 'vhea' */ -#define O_vmtx 9 /* 'vmtx' */ -#define O_OS2 10 /* 'OS/2' */ -#define O_post 11 /* 'post' */ -#define O_kern 12 /* 'kern' */ -#define O_cvt 13 /* 'cvt_' - only used in TT->TT generation */ -#define O_prep 14 /* 'prep' - only used in TT->TT generation */ -#define O_fpgm 15 /* 'fpgm' - only used in TT->TT generation */ -#define O_gsub 16 /* 'GSUB' */ -#define NUM_TAGS 17 - -#endif /* __SUBFONT_H */ diff --git a/vcl/inc/sft.hxx b/vcl/inc/sft.hxx new file mode 100644 index 000000000000..5f22bc0a471f --- /dev/null +++ b/vcl/inc/sft.hxx @@ -0,0 +1,626 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: sft.h,v $ + * $Revision: 1.21 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/* $Id: sft.h,v 1.21 2008-06-25 14:20:49 kz Exp $ */ + +/** + + * + * @file sft.h + * @brief Sun Font Tools + * @author Alexander Gelfenbain + */ + +/* + * If NO_MAPPERS is defined, MapChar() and MapString() and consequently GetTTSimpleCharMetrics() + * don't get compiled in. This is done to avoid including a large chunk of code (TranslateXY() from + * xlat.c in the projects that don't require it. + * + * If NO_TYPE3 is defined CreateT3FromTTGlyphs() does not get compiled in. + * If NO_TYPE42 is defined Type42-related code is excluded + * If NO_TTCR is defined TrueType creation related code is excluded\ + */ + +/* + * Generated fonts contain an XUID entry in the form of: + * + * 103 0 T C1 N C2 C3 + * + * 103 - Sun's Adobe assigned XUID number. Contact person: Alexander Gelfenbain + * + * T - font type. 0: Type 3, 1: Type 42 + * C1 - CRC-32 of the entire source TrueType font + * N - number of glyphs in the subset + * C2 - CRC-32 of the array of glyph IDs used to generate the subset + * C3 - CRC-32 of the array of encoding numbers used to generate the subset + * + */ + + +#ifndef __SUBFONT_H +#define __SUBFONT_H + +#ifdef UNX +#include +#include +#endif +#include + +#include + +#include + +namespace vcl +{ + +/*@{*/ + typedef sal_Int16 F2Dot14; /**< fixed: 2.14 */ + typedef sal_Int32 F16Dot16; /**< fixed: 16.16 */ +/*@}*/ + + typedef struct { + sal_uInt16 s; + sal_uInt16 d; + } sal_uInt16pair; + +/** Return value of OpenTTFont() and CreateT3FromTTGlyphs() */ + enum SFErrCodes { + SF_OK, /**< no error */ + SF_BADFILE, /**< file not found */ + SF_FILEIO, /**< file I/O error */ + SF_MEMORY, /**< memory allocation error */ + SF_GLYPHNUM, /**< incorrect number of glyphs */ + SF_BADARG, /**< incorrect arguments */ + SF_TTFORMAT, /**< incorrect TrueType font format */ + SF_TABLEFORMAT, /**< incorrect format of a TrueType table */ + SF_FONTNO /**< incorrect logical font number of a TTC font */ + }; + +#ifndef FW_THIN /* WIN32 compilation would conflict */ +/** Value of the weight member of the TTGlobalFontInfo struct */ + enum WeightClass { + FW_THIN = 100, /**< Thin */ + FW_EXTRALIGHT = 200, /**< Extra-light (Ultra-light) */ + FW_LIGHT = 300, /**< Light */ + FW_NORMAL = 400, /**< Normal (Regular) */ + FW_MEDIUM = 500, /**< Medium */ + FW_SEMIBOLD = 600, /**< Semi-bold (Demi-bold) */ + FW_BOLD = 700, /**< Bold */ + FW_EXTRABOLD = 800, /**< Extra-bold (Ultra-bold) */ + FW_BLACK = 900 /**< Black (Heavy) */ + }; + +/** Value of the width member of the TTGlobalFontInfo struct */ +#ifndef OS2 + enum WidthClass { + FWIDTH_ULTRA_CONDENSED = 1, /**< 50% of normal */ + FWIDTH_EXTRA_CONDENSED = 2, /**< 62.5% of normal */ + FWIDTH_CONDENSED = 3, /**< 75% of normal */ + FWIDTH_SEMI_CONDENSED = 4, /**< 87.5% of normal */ + FWIDTH_NORMAL = 5, /**< Medium, 100% */ + FWIDTH_SEMI_EXPANDED = 6, /**< 112.5% of normal */ + FWIDTH_EXPANDED = 7, /**< 125% of normal */ + FWIDTH_EXTRA_EXPANDED = 8, /**< 150% of normal */ + FWIDTH_ULTRA_EXPANDED = 9 /**< 200% of normal */ + }; +#endif // OS2 +#endif /* FW_THIN */ + +/** Type of the 'kern' table, stored in _TrueTypeFont::kerntype */ + enum KernType { + KT_NONE = 0, /**< no kern table */ + KT_APPLE_NEW = 1, /**< new Apple kern table */ + KT_MICROSOFT = 2 /**< Microsoft table */ + }; + +/* Composite glyph flags definition */ + enum CompositeFlags { + ARG_1_AND_2_ARE_WORDS = 1, + ARGS_ARE_XY_VALUES = 1<<1, + ROUND_XY_TO_GRID = 1<<2, + WE_HAVE_A_SCALE = 1<<3, + MORE_COMPONENTS = 1<<5, + WE_HAVE_AN_X_AND_Y_SCALE = 1<<6, + WE_HAVE_A_TWO_BY_TWO = 1<<7, + WE_HAVE_INSTRUCTIONS = 1<<8, + USE_MY_METRICS = 1<<9, + OVERLAP_COMPOUND = 1<<10 + }; + +#ifndef NO_TTCR +/** Flags for TrueType generation */ + enum TTCreationFlags { + TTCF_AutoName = 1, /**< Automatically generate a compact 'name' table. + If this flag is not set, name table is generated + either from an array of NameRecord structs passed as + arguments or if the array is NULL, 'name' table + of the generated TrueType file will be a copy + of the name table of the original file. + If this flag is set the array of NameRecord structs + is ignored and a very compact 'name' table is automatically + generated. */ + + TTCF_IncludeOS2 = 2 /** If this flag is set OS/2 table from the original font will be + copied to the subset */ + }; +#endif + + + + +/** Structure used by GetTTSimpleGlyphMetrics() and GetTTSimpleCharMetrics() functions */ + typedef struct { + sal_uInt16 adv; /**< advance width or height */ + sal_Int16 sb; /**< left or top sidebearing */ + } TTSimpleGlyphMetrics; + + + +/** Structure used by the TrueType Creator and GetRawGlyphData() */ + + typedef struct { + sal_uInt32 glyphID; /**< glyph ID */ + sal_uInt16 nbytes; /**< number of bytes in glyph data */ + sal_uInt8 *ptr; /**< pointer to glyph data */ + sal_uInt16 aw; /**< advance width */ + sal_Int16 lsb; /**< left sidebearing */ + sal_uInt16 compflag; /**< 0- if non-composite, 1- otherwise */ + sal_uInt16 npoints; /**< number of points */ + sal_uInt16 ncontours; /**< number of contours */ + /* */ + sal_uInt32 newID; /**< used internally by the TTCR */ + } GlyphData; + +/** Structure used by the TrueType Creator and CreateTTFromTTGlyphs() */ + typedef struct { + sal_uInt16 platformID; /**< Platform ID */ + sal_uInt16 encodingID; /**< Platform-specific encoding ID */ + sal_uInt16 languageID; /**< Language ID */ + sal_uInt16 nameID; /**< Name ID */ + sal_uInt16 slen; /**< String length in bytes */ + sal_uInt8 *sptr; /**< Pointer to string data (not zero-terminated!) */ + } NameRecord; + + + +/** Return value of GetTTGlobalFontInfo() */ + + typedef struct { + char *family; /**< family name */ + sal_uInt16 *ufamily; /**< family name UCS2 */ + char *subfamily; /**< subfamily name */ + sal_uInt16 *usubfamily; /**< subfamily name UCS2 */ + char *psname; /**< PostScript name */ + sal_uInt16 macStyle; /**< macstyle bits from 'HEAD' table */ + int weight; /**< value of WeightClass or 0 if can't be determined */ + int width; /**< value of WidthClass or 0 if can't be determined */ + int pitch; /**< 0: proportianal font, otherwise: monospaced */ + int italicAngle; /**< in counter-clockwise degrees * 65536 */ + int xMin; /**< global bounding box: xMin */ + int yMin; /**< global bounding box: yMin */ + int xMax; /**< global bounding box: xMax */ + int yMax; /**< global bounding box: yMax */ + int ascender; /**< typographic ascent. */ + int descender; /**< typographic descent. */ + int linegap; /**< typographic line gap.\ Negative values are treated as + zero in Win 3.1, System 6 and System 7. */ + int vascent; /**< typographic ascent for vertical writing mode */ + int vdescent; /**< typographic descent for vertical writing mode */ + int typoAscender; /**< OS/2 portable typographic ascender */ + int typoDescender; /**< OS/2 portable typographic descender */ + int typoLineGap; /**< OS/2 portable typographc line gap */ + int winAscent; /**< ascender metric for Windows */ + int winDescent; /**< descender metric for Windows */ + int symbolEncoded; /**< 1: MS symbol encoded 0: not symbol encoded */ + int rangeFlag; /**< if set to 1 Unicode Range flags are applicable */ + sal_uInt32 ur1; /**< bits 0 - 31 of Unicode Range flags */ + sal_uInt32 ur2; /**< bits 32 - 63 of Unicode Range flags */ + sal_uInt32 ur3; /**< bits 64 - 95 of Unicode Range flags */ + sal_uInt32 ur4; /**< bits 96 - 127 of Unicode Range flags */ + sal_uInt8 panose[10]; /**< PANOSE classification number */ + sal_uInt16 typeFlags; /**< type flags (copyright information) */ + } TTGlobalFontInfo; + +/** Structure used by KernGlyphs() */ + typedef struct { + int x; /**< positive: right, negative: left */ + int y; /**< positive: up, negative: down */ + } KernData; + + +/** ControlPoint structure used by GetTTGlyphPoints() */ + typedef struct { + sal_uInt32 flags; /**< 00000000 00000000 e0000000 bbbbbbbb */ + /**< b - byte flags from the glyf array */ + /**< e == 0 - regular point */ + /**< e == 1 - end contour */ + sal_Int16 x; /**< X coordinate in EmSquare units */ + sal_Int16 y; /**< Y coordinate in EmSquare units */ + } ControlPoint; + + typedef struct _TrueTypeFont TrueTypeFont; + +/** + * @defgroup sft Sun Font Tools Exported Functions + */ + + +/** + * Get the number of fonts contained in a TrueType collection + * @param fname - file name + * @return number of fonts or zero, if file is not a TTC file. + * @ingroup sft + */ + int CountTTCFonts(const char* fname); + + +/** + * TrueTypeFont constructor. + * The font file has to be provided as a memory buffer and length + * @param facenum - logical font number within a TTC file. This value is ignored + * for TrueType fonts + * @return value of SFErrCodes enum + * @ingroup sft + */ + int OpenTTFontBuffer(void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf); /*FOLD01*/ +#if !defined(WIN32) && !defined(OS2) +/** + * TrueTypeFont constructor. + * Reads the font file and allocates the memory for the structure. + * on WIN32 the font has to be provided as a memory buffer and length + * @param facenum - logical font number within a TTC file. This value is ignored + * for TrueType fonts + * @return value of SFErrCodes enum + * @ingroup sft + */ + int OpenTTFontFile(const char *fname, sal_uInt32 facenum, TrueTypeFont** ttf); +#endif + +/** + * TrueTypeFont destructor. Deallocates the memory. + * @ingroup sft + */ + void CloseTTFont(TrueTypeFont *); + +/** + * Extracts TrueType control points, and stores them in an allocated array pointed to + * by *pointArray. This function returns the number of extracted points. + * + * @param ttf pointer to the TrueTypeFont structure + * @param glyphID Glyph ID + * @param pointArray Return value - address of the pointer to the first element of the array + * of points allocated by the function + * @return Returns the number of points in *pointArray or -1 if glyphID is + * invalid. + * @ingroup sft + * + */ + int GetTTGlyphPoints(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray); + +/** + * Extracts raw glyph data from the 'glyf' table and returns it in an allocated + * GlyphData structure. + * + * @param ttf pointer to the TrueTypeFont structure + * @param glyphID Glyph ID + * + * @return pointer to an allocated GlyphData structure or NULL if + * glyphID is not present in the font + * @ingroup sft + * + */ + GlyphData *GetTTRawGlyphData(TrueTypeFont *ttf, sal_uInt32 glyphID); + +/** + * For a specified glyph adds all component glyphs IDs to the list and + * return their number. If the glyph is a single glyph it has one component + * glyph (which is added to the list) and the function returns 1. + * For a composite glyphs it returns the number of component glyphs + * and adds all of them to the list. + * + * @param ttf pointer to the TrueTypeFont structure + * @param glyphID Glyph ID + * @param glyphlist list of glyphs + * + * @return number of component glyphs + * @ingroup sft + * + */ + int GetTTGlyphComponents(TrueTypeFont *ttf, sal_uInt32 glyphID, std::vector< sal_uInt32 >& glyphlist); + +/** + * Extracts all Name Records from the font and stores them in an allocated + * array of NameRecord structs + * + * @param ttf pointer to the TrueTypeFont struct + * @param nr pointer to the array of NameRecord structs + * + * @return number of NameRecord structs + * @ingroup sft + */ + + int GetTTNameRecords(TrueTypeFont *ttf, NameRecord **nr); + +/** + * Deallocates previously allocated array of NameRecords. + * + * @param nr array of NameRecord structs + * @param n number of elements in the array + * + * @ingroup sft + */ + void DisposeNameRecords(NameRecord* nr, int n); + + +#ifndef NO_TYPE3 +/** + * Generates a new PostScript Type 3 font and dumps it to outf file. + * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. + * @param ttf pointer to the TrueTypeFont structure + * @param outf the resulting font is written to this stream + * @param fname font name for the new font. If it is NULL the PostScript name of the + * original font will be used + * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf + * @param encoding array of encoding values. encoding[i] specifies the position of the glyph + * glyphArray[i] in the encoding vector of the resulting Type3 font + * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding + * @param wmode writing mode for the output file: 0 - horizontal, 1 - vertical + * @return return the value of SFErrCodes enum + * @see SFErrCodes + * @ingroup sft + * + */ + int CreateT3FromTTGlyphs(TrueTypeFont *ttf, FILE *outf, const char *fname, sal_uInt16 *glyphArray, sal_uInt8 *encoding, int nGlyphs, int wmode); +#endif + +#ifndef NO_TTCR +/** + * Generates a new TrueType font and dumps it to outf file. + * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. + * @param ttf pointer to the TrueTypeFont structure + * @param fname file name for the output TrueType font file + * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf. The first + * element of this array has to be glyph 0 (default glyph) + * @param encoding array of encoding values. encoding[i] specifies character code for + * the glyphID glyphArray[i]. Character code 0 usually points to a default + * glyph (glyphID 0) + * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding + * @param nNameRecs number of NameRecords for the font, if 0 the name table from the + * original font will be used + * @param nr array of NameRecords + * @param flags or'ed TTCreationFlags + * @return return the value of SFErrCodes enum + * @see SFErrCodes + * @ingroup sft + * + */ + int CreateTTFromTTGlyphs(TrueTypeFont *ttf, + const char *fname, + sal_uInt16 *glyphArray, + sal_uInt8 *encoding, + int nGlyphs, + int nNameRecs, + NameRecord *nr, + sal_uInt32 flags); +#endif + +#ifndef NO_TYPE42 +/** + * Generates a new PostScript Type42 font and dumps it to outf file. + * This functions subsititues glyph 0 for all glyphIDs that are not found in the font. + * @param ttf pointer to the TrueTypeFont structure + * @param outf output stream for a resulting font + * @param psname PostScript name of the resulting font + * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf. The first + * element of this array has to be glyph 0 (default glyph) + * @param encoding array of encoding values. encoding[i] specifies character code for + * the glyphID glyphArray[i]. Character code 0 usually points to a default + * glyph (glyphID 0) + * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding + * @return SF_OK - no errors + * SF_GLYPHNUM - too many glyphs (> 255) + * SF_TTFORMAT - corrupted TrueType fonts + * + * @see SFErrCodes + * @ingroup sft + * + */ + int CreateT42FromTTGlyphs(TrueTypeFont *ttf, + FILE *outf, + const char *psname, + sal_uInt16 *glyphArray, + sal_uInt8 *encoding, + int nGlyphs); +#endif + + +/** + * Queries glyph metrics. Allocates an array of TTSimpleGlyphMetrics structs and returns it. + * + * @param ttf pointer to the TrueTypeFont structure + * @param glyphArray pointer to an array of glyphs that are to be extracted from ttf + * @param nGlyphs number of glyph IDs in glyphArray and encoding values in encoding + * @param mode writing mode: 0 - horizontal, 1 - vertical + * @ingroup sft + * + */ + TTSimpleGlyphMetrics *GetTTSimpleGlyphMetrics(TrueTypeFont *ttf, sal_uInt16 *glyphArray, int nGlyphs, int mode); + +#ifndef NO_MAPPERS +/** + * Queries glyph metrics. Allocates an array of TTSimpleGlyphMetrics structs and returns it. + * This function behaves just like GetTTSimpleGlyphMetrics() but it takes a range of Unicode + * characters instead of an array of glyphs. + * + * @param ttf pointer to the TrueTypeFont structure + * @param firstChar Unicode value of the first character in the range + * @param nChars number of Unicode characters in the range + * @param mode writing mode: 0 - horizontal, 1 - vertical + * + * @see GetTTSimpleGlyphMetrics + * @ingroup sft + * + */ + TTSimpleGlyphMetrics *GetTTSimpleCharMetrics(TrueTypeFont *ttf, sal_uInt16 firstChar, int nChars, int mode); + +/** + * Maps a Unicode (UCS-2) string to a glyph array. Returns the number of glyphs in the array, + * which for TrueType fonts is always the same as the number of input characters. + * + * @param ttf pointer to the TrueTypeFont structure + * @param str pointer to a UCS-2 string + * @param nchars number of characters in str + * @param glyphArray pointer to the glyph array where glyph IDs are to be recorded. + * + * @return MapString() returns -1 if the TrueType font has no usable 'cmap' tables. + * Otherwise it returns the number of characters processed: nChars + * + * glyphIDs of TrueType fonts are 2 byte positive numbers. glyphID of 0 denotes a missing + * glyph and traditionally defaults to an empty square. + * glyphArray should be at least sizeof(sal_uInt16) * nchars bytes long. If glyphArray is NULL + * MapString() replaces the UCS-2 characters in str with glyphIDs. + * @ingroup sft + */ + int MapString(TrueTypeFont *ttf, sal_uInt16 *str, int nchars, sal_uInt16 *glyphArray, int bvertical); + +/** + * Maps a Unicode (UCS-2) character to a glyph ID and returns it. Missing glyph has + * a glyphID of 0 so this function can be used to test if a character is encoded in the font. + * + * @param ttf pointer to the TrueTypeFont structure + * @param ch Unicode (UCS-2) character + * @return glyph ID, if the character is missing in the font, the return value is 0. + * @ingroup sft + */ + sal_uInt16 MapChar(TrueTypeFont *ttf, sal_uInt16 ch, int bvertical); + +/** + * Returns 0 when the font does not substitute vertical glyphs + * + * @param ttf pointer to the TrueTypeFont structure + */ + int DoesVerticalSubstitution( TrueTypeFont *ttf, int bvertical); + +#endif + +/** + * Returns global font information about the TrueType font. + * @see TTGlobalFontInfo + * + * @param ttf pointer to a TrueTypeFont structure + * @param info pointer to a TTGlobalFontInfo structure + * @ingroup sft + * + */ + void GetTTGlobalFontInfo(TrueTypeFont *ttf, TTGlobalFontInfo *info); + +#ifdef TEST5 +/** + * Returns kerning information for an array of glyphs. + * Kerning is not cumulative. + * kern[i] contains kerning information for a pair of glyphs at positions i and i+1 + * + * @param ttf pointer to a TrueTypeFont structure + * @param glyphs array of source glyphs + * @param nglyphs number of glyphs in the array + * @param wmode writing mode: 0 - horizontal, 1 - vertical + * @param kern array of KernData structures. It should contain nglyphs-1 elements + * @see KernData + * @ingroup sft + * + */ + void KernGlyphs(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern); +#endif + +/** + * Returns nonzero if font is a symbol encoded font + */ + int CheckSymbolEncoding(TrueTypeFont* ttf); + +/** + * returns the number of glyphs in a font + */ + int GetTTGlyphCount( TrueTypeFont* ttf ); + +/*- private definitions */ /*FOLD00*/ + + struct _TrueTypeFont { + sal_uInt32 tag; + + char *fname; + sal_Int32 fsize; + sal_uInt8 *ptr; + + char *psname; + char *family; + sal_uInt16 *ufamily; + char *subfamily; + sal_uInt16 *usubfamily; + + sal_uInt32 ntables; + sal_uInt32 *goffsets; + sal_uInt32 nglyphs; + sal_uInt32 unitsPerEm; + sal_uInt32 numberOfHMetrics; + sal_uInt32 numOfLongVerMetrics; /* if this number is not 0, font has vertical metrics information */ + sal_uInt8 *cmap; + int cmapType; + sal_uInt32 (*mapper)(const sal_uInt8 *, sal_uInt32); /* character to glyphID translation function */ + sal_uInt8 **tables; /* array of pointers to raw subtables in SFNT file */ + sal_uInt32 *tlens; /* array of table lengths */ + int kerntype; /* Defined in the KernType enum */ + sal_uInt32 nkern; /* number of kern subtables */ + sal_uInt8 **kerntables; /* array of pointers to kern subtables */ + void *pGSubstitution; /* info provided by GSUB for UseGSUB() */ + }; + +/* indexes into _TrueTypeFont::tables[] and _TrueTypeFont::tlens[] */ +#define O_maxp 0 /* 'maxp' */ +#define O_glyf 1 /* 'glyf' */ +#define O_head 2 /* 'head' */ +#define O_loca 3 /* 'loca' */ +#define O_name 4 /* 'name' */ +#define O_hhea 5 /* 'hhea' */ +#define O_hmtx 6 /* 'hmtx' */ +#define O_cmap 7 /* 'cmap' */ +#define O_vhea 8 /* 'vhea' */ +#define O_vmtx 9 /* 'vmtx' */ +#define O_OS2 10 /* 'OS/2' */ +#define O_post 11 /* 'post' */ +#define O_kern 12 /* 'kern' */ +#define O_cvt 13 /* 'cvt_' - only used in TT->TT generation */ +#define O_prep 14 /* 'prep' - only used in TT->TT generation */ +#define O_fpgm 15 /* 'fpgm' - only used in TT->TT generation */ +#define O_gsub 16 /* 'GSUB' */ +#define NUM_TAGS 17 + +} // namespace vcl + +#endif /* __SUBFONT_H */ diff --git a/vcl/inc/vcl/svdata.hxx b/vcl/inc/vcl/svdata.hxx index e3072a4bc250..bde902c3fbcd 100644 --- a/vcl/inc/vcl/svdata.hxx +++ b/vcl/inc/vcl/svdata.hxx @@ -338,6 +338,7 @@ struct ImplSVData UnoWrapperBase* mpUnoWrapper; Window* mpIntroWindow; // the splash screen DockingManager* mpDockingManager; + BOOL mbIsTestTool; vos::OThread::TThreadIdentifier mnMainThreadId; ::com::sun::star::uno::Reference< diff --git a/vcl/os2/source/gdi/salgdi3.cxx b/vcl/os2/source/gdi/salgdi3.cxx index 15034168269e..546f4bf2b7cd 100644 --- a/vcl/os2/source/gdi/salgdi3.cxx +++ b/vcl/os2/source/gdi/salgdi3.cxx @@ -74,15 +74,14 @@ #include #endif -#ifndef __SUBFONT_H -#include -#include -#endif +#include "sft.hxx" #ifdef GCP_KERN_HACK #include #endif +using namespace vcl; + // ----------- // - Inlines - // ----------- diff --git a/vcl/prj/build.lst b/vcl/prj/build.lst index ac93ae71bdd2..8a894cba2e55 100644 --- a/vcl/prj/build.lst +++ b/vcl/prj/build.lst @@ -1,4 +1,4 @@ -vc vcl : apple_remote BOOST:boost rsc sot ucbhelper unotools ICU:icu i18npool i18nutil unoil ridljar X11_EXTENSIONS:x11_extensions offuh basegfx basebmp tools transex3 icc NULL +vc vcl : apple_remote BOOST:boost rsc sot ucbhelper unotools ICU:icu i18npool i18nutil unoil ridljar X11_EXTENSIONS:x11_extensions offuh basegfx basebmp tools transex3 icc SO:print_header NULL vc vcl usr1 - all vc_mkout NULL vc vcl\inc nmake - all vc_inc NULL vc vcl\source\glyphs nmake - all vc_glyphs vc_inc NULL diff --git a/vcl/source/app/svdata.cxx b/vcl/source/app/svdata.cxx index 56ba933e3931..db30fd4ef3ab 100644 --- a/vcl/source/app/svdata.cxx +++ b/vcl/source/app/svdata.cxx @@ -117,6 +117,20 @@ void ImplInitSVData() pImplSVData->maHelpData.mbAutoHelpId = sal_True; pImplSVData->maHelpData.mbAutoHelpId = sal_True; pImplSVData->maNWFData.maMenuBarHighlightTextColor = Color( COL_TRANSPARENT ); + + // find out whether we are running in the testtool + // in this case we need some special workarounds + sal_uInt32 nArgs = osl_getCommandArgCount(); + for( sal_uInt32 i = 0; i < nArgs; i++ ) + { + rtl::OUString aArg; + osl_getCommandArg( i, &aArg.pData ); + if( aArg.equalsAscii( "-enableautomation" ) ) + { + pImplSVData->mbIsTestTool = true; + break; + } + } } // ----------------------------------------------------------------------- diff --git a/vcl/source/fontsubset/crc32.c b/vcl/source/fontsubset/crc32.c deleted file mode 100644 index 386b873a011c..000000000000 --- a/vcl/source/fontsubset/crc32.c +++ /dev/null @@ -1,89 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: crc32.c,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: crc32.c,v 1.3 2008-04-11 10:13:50 rt Exp $ */ - -/** - * - * @file crc32.c - * @brief CRC-32 calculation function - * @author Alexander Gelfenbain - */ - -#include "sft.h" -#include "crc32.h" - -static uint32 crcTable[256] = { - 0x00000000UL, 0x77073096UL, 0xEE0E612CUL, 0x990951BAUL, 0x076DC419UL, 0x706AF48FUL, 0xE963A535UL, 0x9E6495A3UL, - 0x0EDB8832UL, 0x79DCB8A4UL, 0xE0D5E91EUL, 0x97D2D988UL, 0x09B64C2BUL, 0x7EB17CBDUL, 0xE7B82D07UL, 0x90BF1D91UL, - 0x1DB71064UL, 0x6AB020F2UL, 0xF3B97148UL, 0x84BE41DEUL, 0x1ADAD47DUL, 0x6DDDE4EBUL, 0xF4D4B551UL, 0x83D385C7UL, - 0x136C9856UL, 0x646BA8C0UL, 0xFD62F97AUL, 0x8A65C9ECUL, 0x14015C4FUL, 0x63066CD9UL, 0xFA0F3D63UL, 0x8D080DF5UL, - 0x3B6E20C8UL, 0x4C69105EUL, 0xD56041E4UL, 0xA2677172UL, 0x3C03E4D1UL, 0x4B04D447UL, 0xD20D85FDUL, 0xA50AB56BUL, - 0x35B5A8FAUL, 0x42B2986CUL, 0xDBBBC9D6UL, 0xACBCF940UL, 0x32D86CE3UL, 0x45DF5C75UL, 0xDCD60DCFUL, 0xABD13D59UL, - 0x26D930ACUL, 0x51DE003AUL, 0xC8D75180UL, 0xBFD06116UL, 0x21B4F4B5UL, 0x56B3C423UL, 0xCFBA9599UL, 0xB8BDA50FUL, - 0x2802B89EUL, 0x5F058808UL, 0xC60CD9B2UL, 0xB10BE924UL, 0x2F6F7C87UL, 0x58684C11UL, 0xC1611DABUL, 0xB6662D3DUL, - 0x76DC4190UL, 0x01DB7106UL, 0x98D220BCUL, 0xEFD5102AUL, 0x71B18589UL, 0x06B6B51FUL, 0x9FBFE4A5UL, 0xE8B8D433UL, - 0x7807C9A2UL, 0x0F00F934UL, 0x9609A88EUL, 0xE10E9818UL, 0x7F6A0DBBUL, 0x086D3D2DUL, 0x91646C97UL, 0xE6635C01UL, - 0x6B6B51F4UL, 0x1C6C6162UL, 0x856530D8UL, 0xF262004EUL, 0x6C0695EDUL, 0x1B01A57BUL, 0x8208F4C1UL, 0xF50FC457UL, - 0x65B0D9C6UL, 0x12B7E950UL, 0x8BBEB8EAUL, 0xFCB9887CUL, 0x62DD1DDFUL, 0x15DA2D49UL, 0x8CD37CF3UL, 0xFBD44C65UL, - 0x4DB26158UL, 0x3AB551CEUL, 0xA3BC0074UL, 0xD4BB30E2UL, 0x4ADFA541UL, 0x3DD895D7UL, 0xA4D1C46DUL, 0xD3D6F4FBUL, - 0x4369E96AUL, 0x346ED9FCUL, 0xAD678846UL, 0xDA60B8D0UL, 0x44042D73UL, 0x33031DE5UL, 0xAA0A4C5FUL, 0xDD0D7CC9UL, - 0x5005713CUL, 0x270241AAUL, 0xBE0B1010UL, 0xC90C2086UL, 0x5768B525UL, 0x206F85B3UL, 0xB966D409UL, 0xCE61E49FUL, - 0x5EDEF90EUL, 0x29D9C998UL, 0xB0D09822UL, 0xC7D7A8B4UL, 0x59B33D17UL, 0x2EB40D81UL, 0xB7BD5C3BUL, 0xC0BA6CADUL, - 0xEDB88320UL, 0x9ABFB3B6UL, 0x03B6E20CUL, 0x74B1D29AUL, 0xEAD54739UL, 0x9DD277AFUL, 0x04DB2615UL, 0x73DC1683UL, - 0xE3630B12UL, 0x94643B84UL, 0x0D6D6A3EUL, 0x7A6A5AA8UL, 0xE40ECF0BUL, 0x9309FF9DUL, 0x0A00AE27UL, 0x7D079EB1UL, - 0xF00F9344UL, 0x8708A3D2UL, 0x1E01F268UL, 0x6906C2FEUL, 0xF762575DUL, 0x806567CBUL, 0x196C3671UL, 0x6E6B06E7UL, - 0xFED41B76UL, 0x89D32BE0UL, 0x10DA7A5AUL, 0x67DD4ACCUL, 0xF9B9DF6FUL, 0x8EBEEFF9UL, 0x17B7BE43UL, 0x60B08ED5UL, - 0xD6D6A3E8UL, 0xA1D1937EUL, 0x38D8C2C4UL, 0x4FDFF252UL, 0xD1BB67F1UL, 0xA6BC5767UL, 0x3FB506DDUL, 0x48B2364BUL, - 0xD80D2BDAUL, 0xAF0A1B4CUL, 0x36034AF6UL, 0x41047A60UL, 0xDF60EFC3UL, 0xA867DF55UL, 0x316E8EEFUL, 0x4669BE79UL, - 0xCB61B38CUL, 0xBC66831AUL, 0x256FD2A0UL, 0x5268E236UL, 0xCC0C7795UL, 0xBB0B4703UL, 0x220216B9UL, 0x5505262FUL, - 0xC5BA3BBEUL, 0xB2BD0B28UL, 0x2BB45A92UL, 0x5CB36A04UL, 0xC2D7FFA7UL, 0xB5D0CF31UL, 0x2CD99E8BUL, 0x5BDEAE1DUL, - 0x9B64C2B0UL, 0xEC63F226UL, 0x756AA39CUL, 0x026D930AUL, 0x9C0906A9UL, 0xEB0E363FUL, 0x72076785UL, 0x05005713UL, - 0x95BF4A82UL, 0xE2B87A14UL, 0x7BB12BAEUL, 0x0CB61B38UL, 0x92D28E9BUL, 0xE5D5BE0DUL, 0x7CDCEFB7UL, 0x0BDBDF21UL, - 0x86D3D2D4UL, 0xF1D4E242UL, 0x68DDB3F8UL, 0x1FDA836EUL, 0x81BE16CDUL, 0xF6B9265BUL, 0x6FB077E1UL, 0x18B74777UL, - 0x88085AE6UL, 0xFF0F6A70UL, 0x66063BCAUL, 0x11010B5CUL, 0x8F659EFFUL, 0xF862AE69UL, 0x616BFFD3UL, 0x166CCF45UL, - 0xA00AE278UL, 0xD70DD2EEUL, 0x4E048354UL, 0x3903B3C2UL, 0xA7672661UL, 0xD06016F7UL, 0x4969474DUL, 0x3E6E77DBUL, - 0xAED16A4AUL, 0xD9D65ADCUL, 0x40DF0B66UL, 0x37D83BF0UL, 0xA9BCAE53UL, 0xDEBB9EC5UL, 0x47B2CF7FUL, 0x30B5FFE9UL, - 0xBDBDF21CUL, 0xCABAC28AUL, 0x53B39330UL, 0x24B4A3A6UL, 0xBAD03605UL, 0xCDD70693UL, 0x54DE5729UL, 0x23D967BFUL, - 0xB3667A2EUL, 0xC4614AB8UL, 0x5D681B02UL, 0x2A6F2B94UL, 0xB40BBE37UL, 0xC30C8EA1UL, 0x5A05DF1BUL, 0x2D02EF8DUL -}; - -uint32 crc32(const void *ptr, size_t len) -{ - uint32 crc = 0xFFFFFFFF; - const byte *bp = (const byte *) ptr; - size_t i; - - for (i=0; i> 8); - } - - return crc ^ 0xFFFFFFFF; -} diff --git a/vcl/source/fontsubset/crc32.h b/vcl/source/fontsubset/crc32.h deleted file mode 100644 index fa9ef71a1432..000000000000 --- a/vcl/source/fontsubset/crc32.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: crc32.h,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: crc32.h,v 1.4 2008-04-11 10:14:08 rt Exp $ */ - -/** - * - * @file crc32.h - * @brief CRC-32 calculation function - * @author Alexander Gelfenbain - */ - -#ifdef __cplusplus -extern "C"{ -#endif - sal_Int32 crc32(const void *ptr, sal_Int32 len); -#ifdef __cplusplus -} -#endif diff --git a/vcl/source/fontsubset/gsub.cxx b/vcl/source/fontsubset/gsub.cxx index e73ccccc12a4..9715e7fc8585 100644 --- a/vcl/source/fontsubset/gsub.cxx +++ b/vcl/source/fontsubset/gsub.cxx @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: gsub.cxx,v $ - * $Revision: 1.12.18.1 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -31,9 +28,7 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#include "sft.h" -#undef true -#undef false +#include "sft.hxx" #include "gsub.h" @@ -41,6 +36,9 @@ #include #include +namespace vcl +{ + typedef sal_uInt32 ULONG; typedef sal_uInt16 USHORT; typedef sal_uInt8 FT_Byte; @@ -355,3 +353,5 @@ int HasVerticalGSUB( struct _TrueTypeFont* pTTFile ) GlyphSubstitution* pGlyphSubstitution = (GlyphSubstitution*)pTTFile->pGSubstitution; return pGlyphSubstitution ? +1 : 0; } + +} diff --git a/vcl/source/fontsubset/gsub.h b/vcl/source/fontsubset/gsub.h index c64b2abb7e00..58b5b69c3e25 100644 --- a/vcl/source/fontsubset/gsub.h +++ b/vcl/source/fontsubset/gsub.h @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: gsub.h,v $ - * $Revision: 1.6.18.1 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -31,20 +28,17 @@ #ifndef _PSP_GSUB_H #define _PSP_GSUB_H -#ifdef __cplusplus -extern "C" { -#endif +namespace vcl +{ -int HasVerticalGSUB( struct _TrueTypeFont* pTTFile ); +int HasVerticalGSUB( struct vcl::_TrueTypeFont* pTTFile ); -int UseGSUB( struct _TrueTypeFont* pTTFile, int nGlyph, int wmode ); +int UseGSUB( struct vcl::_TrueTypeFont* pTTFile, int nGlyph, int wmode ); -int ReadGSUB( struct _TrueTypeFont* pTTFile, int nRequestedScript, int nRequestedLangsys ); +int ReadGSUB( struct vcl::_TrueTypeFont* pTTFile, int nRequestedScript, int nRequestedLangsys ); -void ReleaseGSUB( struct _TrueTypeFont* pTTFile ); +void ReleaseGSUB( struct vcl::_TrueTypeFont* pTTFile ); -#ifdef __cplusplus } -#endif #endif /* _PSP_GSUB_H */ diff --git a/vcl/source/fontsubset/list.c b/vcl/source/fontsubset/list.c index 83ebe8595a46..86864650db85 100644 --- a/vcl/source/fontsubset/list.c +++ b/vcl/source/fontsubset/list.c @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: list.c,v $ - * $Revision: 1.8 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,8 +25,6 @@ * ************************************************************************/ -/* $Id: list.c,v 1.8 2008-06-25 14:19:44 kz Exp $ */ - /*[]---------------------------------------------------[]*/ /*| |*/ /*| list.c - bidirectional list class |*/ @@ -67,7 +62,7 @@ typedef struct _lnode { struct _list { lnode *head, *tail, *cptr; size_t aCount; - void (*eDtor)(void *); + list_destructor eDtor; }; /*- private methods */ @@ -177,7 +172,7 @@ void listDispose(list this) /*- dtor */ free(this); } -void listSetElementDtor(list this, void (*f)(void *)) +void listSetElementDtor(list this, list_destructor f) { assert(this != 0); this->eDtor = f; diff --git a/vcl/source/fontsubset/makefile.mk b/vcl/source/fontsubset/makefile.mk index b1d2552752a8..b7d719f3c912 100644 --- a/vcl/source/fontsubset/makefile.mk +++ b/vcl/source/fontsubset/makefile.mk @@ -6,10 +6,6 @@ # # OpenOffice.org - a multi-platform office productivity suite # -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.6 $ -# # This file is part of OpenOffice.org. # # OpenOffice.org is free software: you can redistribute it and/or modify diff --git a/vcl/source/fontsubset/sft.c b/vcl/source/fontsubset/sft.c deleted file mode 100644 index be54a872fd7f..000000000000 --- a/vcl/source/fontsubset/sft.c +++ /dev/null @@ -1,3334 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: sft.c,v $ - * $Revision: 1.47.4.1 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* - * Sun Font Tools - * - * Author: Alexander Gelfenbain - * - */ - -#if OSL_DEBUG_LEVEL == 0 -# ifndef NDEBUG -# define NDEBUG -# endif -#endif -#include - -#include -#include -#include -#ifdef UNX -#include -#include -#endif -#include "sft.h" -#include "gsub.h" -#if ! (defined(NO_TTCR) && defined(NO_TYPE42)) -#include "ttcr.h" -#endif -#ifdef NO_LIST -#include "list.h" /* list.h does not get included in the sft.h */ -#endif -#ifndef NO_MAPPERS /* include MapChar() and MapString() */ -#include "xlat.h" -#endif -#ifndef NO_TYPE3 /* include CreateT3FromTTGlyphs() */ -#include -#endif - -#include - -#ifdef TEST7 -#include -#endif - -/*- module identification */ - -const char *modname = "SunTypeTools-TT"; -const char *modver = "1.0"; -const char *modextra = "gelf"; - -/*- private functions, constants and data types */ /*FOLD00*/ - -enum PathSegmentType { - PS_NOOP = 0, - PS_MOVETO = 1, - PS_LINETO = 2, - PS_CURVETO = 3, - PS_CLOSEPATH = 4 -}; - -typedef struct { - int type; - int x1, y1; - int x2, y2; - int x3, y3; -} PSPathElement; - -/*- In horisontal writing mode right sidebearing is calculated using this formula - *- rsb = aw - (lsb + xMax - xMin) -*/ -typedef struct { - sal_Int16 xMin; - sal_Int16 yMin; - sal_Int16 xMax; - sal_Int16 yMax; - sal_uInt16 aw; /*- Advance Width (horisontal writing mode) */ - sal_Int16 lsb; /*- Left sidebearing (horisontal writing mode) */ - sal_uInt16 ah; /*- advance height (vertical writing mode) */ - sal_Int16 tsb; /*- top sidebearing (vertical writing mode) */ -} TTGlyphMetrics; - -#define HFORMAT_LINELEN 64 - -typedef struct { - FILE *o; - char buffer[HFORMAT_LINELEN]; - int bufpos; - int total; -} HexFmt; - -typedef struct { - sal_uInt32 nGlyphs; /* number of glyphs in the font + 1 */ - sal_uInt32 *offs; /* array of nGlyphs offsets */ -} GlyphOffsets; - -/* private tags */ -static const sal_uInt32 TTFontClassTag = 0x74746663; /* 'ttfc' */ - -static const sal_uInt32 T_true = 0x74727565; /* 'true' */ -static const sal_uInt32 T_ttcf = 0x74746366; /* 'ttcf' */ - -/* standard TrueType table tags */ -#define T_maxp 0x6D617870 -#define T_glyf 0x676C7966 -#define T_head 0x68656164 -#define T_loca 0x6C6F6361 -#define T_name 0x6E616D65 -#define T_hhea 0x68686561 -#define T_hmtx 0x686D7478 -#define T_cmap 0x636D6170 -#define T_vhea 0x76686561 -#define T_vmtx 0x766D7478 -#define T_OS2 0x4F532F32 -#define T_post 0x706F7374 -#define T_kern 0x6B65726E -#define T_cvt 0x63767420 -#define T_prep 0x70726570 -#define T_fpgm 0x6670676D -#define T_gsub 0x47535542 - -#define LAST_URANGE_BIT 69 -const char *ulcodes[LAST_URANGE_BIT+2] = { - /* 0 */ "Basic Latin", - /* 1 */ "Latin-1 Supplement", - /* 2 */ "Latin Extended-A", - /* 3 */ "Latin Extended-B", - /* 4 */ "IPA Extensions", - /* 5 */ "Spacing Modifier Letters", - /* 6 */ "Combining Diacritical Marks", - /* 7 */ "Basic Greek", - /* 8 */ "Greek Symbols And Coptic", - /* 9 */ "Cyrillic", - /* 10 */ "Armenian", - /* 11 */ "Basic Hebrew", - /* 12 */ "Hebrew Extended (A and B blocks combined)", - /* 13 */ "Basic Arabic", - /* 14 */ "Arabic Extended", - /* 15 */ "Devanagari", - /* 16 */ "Bengali", - /* 17 */ "Gurmukhi", - /* 18 */ "Gujarati", - /* 19 */ "Oriya", - /* 20 */ "Tamil", - /* 21 */ "Telugu", - /* 22 */ "Kannada", - /* 23 */ "Malayalam", - /* 24 */ "Thai", - /* 25 */ "Lao", - /* 26 */ "Basic Georgian", - /* 27 */ "Georgian Extended", - /* 28 */ "Hangul Jamo", - /* 29 */ "Latin Extended Additional", - /* 30 */ "Greek Extended", - /* 31 */ "General Punctuation", - /* 32 */ "Superscripts And Subscripts", - /* 33 */ "Currency Symbols", - /* 34 */ "Combining Diacritical Marks For Symbols", - /* 35 */ "Letterlike Symbols", - /* 36 */ "Number Forms", - /* 37 */ "Arrows", - /* 38 */ "Mathematical Operators", - /* 39 */ "Miscellaneous Technical", - /* 40 */ "Control Pictures", - /* 41 */ "Optical Character Recognition", - /* 42 */ "Enclosed Alphanumerics", - /* 43 */ "Box Drawing", - /* 44 */ "Block Elements", - /* 45 */ "Geometric Shapes", - /* 46 */ "Miscellaneous Symbols", - /* 47 */ "Dingbats", - /* 48 */ "CJK Symbols And Punctuation", - /* 49 */ "Hiragana", - /* 50 */ "Katakana", - /* 51 */ "Bopomofo", - /* 52 */ "Hangul Compatibility Jamo", - /* 53 */ "CJK Miscellaneous", - /* 54 */ "Enclosed CJK Letters And Months", - /* 55 */ "CJK Compatibility", - /* 56 */ "Hangul", - /* 57 */ "Reserved for Unicode SubRanges", - /* 58 */ "Reserved for Unicode SubRanges", - /* 59 */ "CJK Unified Ideographs", - /* 60 */ "Private Use Area", - /* 61 */ "CJK Compatibility Ideographs", - /* 62 */ "Alphabetic Presentation Forms", - /* 63 */ "Arabic Presentation Forms-A", - /* 64 */ "Combining Half Marks", - /* 65 */ "CJK Compatibility Forms", - /* 66 */ "Small Form Variants", - /* 67 */ "Arabic Presentation Forms-B", - /* 68 */ "Halfwidth And Fullwidth Forms", - /* 69 */ "Specials", - /*70-127*/ "Reserved for Unicode SubRanges" -}; - - - -/*- inline functions */ /*FOLD01*/ -#ifdef __GNUC__ -#define _inline static __inline__ -#else -#define _inline static -#endif - -_inline void *smalloc(size_t size) -{ - void *res = malloc(size); - assert(res != 0); - return res; -} - -_inline void *scalloc(size_t n, size_t size) -{ - void *res = calloc(n, size); - assert(res != 0); - return res; -} - -_inline sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) { - return (a << 24) | (b << 16) | (c << 8) | d; -} - -/*- Data access macros for data stored in big-endian or little-endian format */ -_inline sal_Int16 GetInt16(const sal_uInt8 *ptr, size_t offset, int bigendian) -{ - sal_Int16 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; - } else { - t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_uInt16 GetUInt16(const sal_uInt8 *ptr, size_t offset, int bigendian) -{ - sal_uInt16 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; - } else { - t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_Int32 GetInt32(const sal_uInt8 *ptr, size_t offset, int bigendian) -{ - sal_Int32 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | - (ptr+offset)[2] << 8 | (ptr+offset)[3]; - } else { - t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | - (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_uInt32 GetUInt32(const sal_uInt8 *ptr, size_t offset, int bigendian) -{ - sal_uInt32 t; - assert(ptr != 0); - - - if (bigendian) { - t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | - (ptr+offset)[2] << 8 | (ptr+offset)[3]; - } else { - t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | - (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline void PutInt16(sal_Int16 val, sal_uInt8 *ptr, size_t offset, int bigendian) -{ - assert(ptr != 0); - - if (bigendian) { - ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset+1] = (sal_uInt8)(val & 0xFF); - } else { - ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset] = (sal_uInt8)(val & 0xFF); - } - -} - -#if defined(OSL_BIG_ENDIAN) -#define Int16FromMOTA(a) (a) -#define Int32FromMOTA(a) (a) -#else -static sal_uInt16 Int16FromMOTA(sal_uInt16 a) { - return (sal_uInt16) (((sal_uInt8)((a) >> 8)) | ((sal_uInt8)(a) << 8)); -} -static sal_uInt32 Int32FromMOTA(sal_uInt32 a) { - return ((a>>24)&0xFF) | (((a>>8)&0xFF00) | ((a&0xFF00)<<8) | ((a&0xFF)<<24)); -} -#endif - -_inline F16Dot16 fixedMul(F16Dot16 a, F16Dot16 b) -{ - unsigned int a1, b1; - unsigned int a2, b2; - F16Dot16 res; - int sign; - - sign = (a & 0x80000000) ^ (b & 0x80000000); - if (a < 0) a = -a; - if (b < 0) b = -b; - - a1 = a >> 16; - b1 = a & 0xFFFF; - a2 = b >> 16; - b2 = b & 0xFFFF; - - res = a1 * a2; - - /* if (res > 0x7FFF) assert(!"fixedMul: F16Dot16 overflow"); */ - - res <<= 16; - res += a1 * b2 + b1 * a2 + ((b1 * b2) >> 16); - - return sign ? -res : res; -} - - -_inline F16Dot16 fixedDiv(F16Dot16 a, F16Dot16 b) -{ - unsigned int f, r; - F16Dot16 res; - int sign; - - sign = (a & 0x80000000) ^ (b & 0x80000000); - if (a < 0) a = -a; - if (b < 0) b = -b; - - f = a / b; - r = a % b; - - /* if (f > 0x7FFFF) assert(!"fixedDiv: F16Dot16 overflow"); */ - - while (r > 0xFFFF) { - r >>= 1; - b >>= 1; - } - - res = (f << 16) + (r << 16) / b; - - return sign ? -res : res; -} - -/*- returns a * b / c -*/ -/* XXX provide a real implementation that preserves accuracy */ -_inline F16Dot16 fixedMulDiv(F16Dot16 a, F16Dot16 b, F16Dot16 c) -{ - F16Dot16 res; - - res = fixedMul(a, b); - return fixedDiv(res, c); -} - -/*- Translate units from TT to PS (standard 1/1000) -*/ -_inline int XUnits(int unitsPerEm, int n) -{ - return (n * 1000) / unitsPerEm; -} - -_inline const char *UnicodeRangeName(sal_uInt16 bit) -{ - if (bit > LAST_URANGE_BIT) bit = LAST_URANGE_BIT+1; - - return ulcodes[bit]; -} - -_inline sal_uInt8 *getTable(TrueTypeFont *ttf, sal_uInt32 ord) -{ - return ttf->tables[ord]; -} - -_inline sal_uInt32 getTableSize(TrueTypeFont *ttf, sal_uInt32 ord) -{ - return ttf->tlens[ord]; -} - -#ifndef NO_TYPE42 -/* Hex Formatter functions */ -static char HexChars[] = "0123456789ABCDEF"; - -static HexFmt *HexFmtNew(FILE *outf) -{ - HexFmt *res = smalloc(sizeof(HexFmt)); - res->bufpos = res->total = 0; - res->o = outf; - return res; -} - -static void HexFmtFlush(HexFmt *_this) -{ - if (_this->bufpos) { - fwrite(_this->buffer, 1, _this->bufpos, _this->o); - _this->bufpos = 0; - } -} - - -_inline void HexFmtOpenString(HexFmt *_this) -{ - fputs("<\n", _this->o); -} - -_inline void HexFmtCloseString(HexFmt *_this) -{ - HexFmtFlush(_this); - fputs("00\n>\n", _this->o); -} - -_inline void HexFmtDispose(HexFmt *_this) -{ - HexFmtFlush(_this); - free(_this); -} - -static void HexFmtBlockWrite(HexFmt *_this, const void *ptr, sal_uInt32 size) -{ - sal_uInt8 Ch; - sal_uInt32 i; - - if (_this->total + size > 65534) { - HexFmtFlush(_this); - HexFmtCloseString(_this); - _this->total = 0; - HexFmtOpenString(_this); - } - for (i=0; ibuffer[_this->bufpos++] = HexChars[Ch >> 4]; - _this->buffer[_this->bufpos++] = HexChars[Ch & 0xF]; - if (_this->bufpos == HFORMAT_LINELEN) { - HexFmtFlush(_this); - fputc('\n', _this->o); - } - - } - _this->total += size; -} -#endif - - - -/* Outline Extraction functions */ /*FOLD01*/ - -/* fills the aw and lsb entries of the TTGlyphMetrics structure from hmtx table -*/ -static void GetMetrics(TrueTypeFont *ttf, sal_uInt32 glyphID, TTGlyphMetrics *metrics) -{ - sal_uInt8 *table = getTable(ttf, O_hmtx); - - metrics->aw = metrics->lsb = metrics->ah = metrics->tsb = 0; - if (!table || !ttf->numberOfHMetrics) return; - - if (glyphID < ttf->numberOfHMetrics) { - metrics->aw = GetUInt16(table, 4 * glyphID, 1); - metrics->lsb = GetInt16(table, 4 * glyphID + 2, 1); - } else { - metrics->aw = GetUInt16(table, 4 * (ttf->numberOfHMetrics - 1), 1); - metrics->lsb = GetInt16(table + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2, 1); - } - - table = getTable(ttf, O_vmtx); - if (!table || !ttf->numOfLongVerMetrics) return; - - if (glyphID < ttf->numOfLongVerMetrics) { - metrics->ah = GetUInt16(table, 4 * glyphID, 1); - metrics->tsb = GetInt16(table, 4 * glyphID + 2, 1); - } else { - metrics->ah = GetUInt16(table, 4 * (ttf->numOfLongVerMetrics - 1), 1); - metrics->tsb = GetInt16(table + ttf->numOfLongVerMetrics * 4, (glyphID - ttf->numOfLongVerMetrics) * 2, 1); - } -} - -static int GetTTGlyphOutline(TrueTypeFont *, sal_uInt32 , ControlPoint **, TTGlyphMetrics *, list ); - -/* returns the number of control points, allocates the pointArray */ -static int GetSimpleTTOutline(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics) /*FOLD02*/ -{ - sal_uInt8 *table = getTable(ttf, O_glyf); - sal_uInt8 *ptr, *p, flag, n; - sal_Int16 numberOfContours; - sal_uInt16 t, instLen, lastPoint=0; - int i, j, z; - ControlPoint* pa; - - *pointArray = 0; - - /* printf("GetSimpleTTOutline(%d)\n", glyphID); */ - - if (glyphID >= ttf->nglyphs) return 0; /*- glyph is not present in the font */ - ptr = table + ttf->goffsets[glyphID]; - if ((numberOfContours = GetInt16(ptr, 0, 1)) <= 0) return 0; /*- glyph is not simple */ - - if (metrics) { /*- GetCompoundTTOutline() calls this function with NULL metrics -*/ - metrics->xMin = GetInt16(ptr, 2, 1); - metrics->yMin = GetInt16(ptr, 4, 1); - metrics->xMax = GetInt16(ptr, 6, 1); - metrics->yMax = GetInt16(ptr, 8, 1); - GetMetrics(ttf, glyphID, metrics); - } - - /* determine the last point and be extra safe about it. But probably this code is not needed */ - - for (i=0; i lastPoint) lastPoint = t; - } - - instLen = GetUInt16(ptr, 10 + numberOfContours*2, 1); - p = ptr + 10 + 2 * numberOfContours + 2 + instLen; - pa = calloc(lastPoint+1, sizeof(ControlPoint)); - - i = 0; - while (i <= lastPoint) { - pa[i++].flags = (sal_uInt32) (flag = *p++); - if (flag & 8) { /*- repeat flag */ - n = *p++; - for (j=0; j lastPoint) { /*- if the font is really broken */ - free(pa); - return 0; - } - pa[i++].flags = flag; - } - } - } - - /*- Process the X coordinate */ - z = 0; - for (i = 0; i <= lastPoint; i++) { - if (pa[i].flags & 0x02) { - if (pa[i].flags & 0x10) { - z += (int) (*p++); - } else { - z -= (int) (*p++); - } - } else if ( !(pa[i].flags & 0x10)) { - z += GetInt16(p, 0, 1); - p += 2; - } - pa[i].x = (sal_Int16)z; - } - - /*- Process the Y coordinate */ - z = 0; - for (i = 0; i <= lastPoint; i++) { - if (pa[i].flags & 0x04) { - if (pa[i].flags & 0x20) { - z += *p++; - } else { - z -= *p++; - } - } else if ( !(pa[i].flags & 0x20)) { - z += GetInt16(p, 0, 1); - p += 2; - } - pa[i].y = (sal_Int16)z; - } - - for (i=0; i= ttf->nglyphs) { /*- incorrect glyphID */ - return 0; - } - ptr = table + ttf->goffsets[glyphID]; - if ((numberOfContours = GetInt16(ptr, 0, 1)) != -1) { /*- glyph is not compound */ - return 0; - } - - myPoints = listNewEmpty(); - listSetElementDtor(myPoints, free); - - if (metrics) { - metrics->xMin = GetInt16(ptr, 2, 1); - metrics->yMin = GetInt16(ptr, 4, 1); - metrics->xMax = GetInt16(ptr, 6, 1); - metrics->yMax = GetInt16(ptr, 8, 1); - GetMetrics(ttf, glyphID, metrics); - } - - ptr += 10; - - do { - flags = GetUInt16(ptr, 0, 1); - /* printf("flags: 0x%X\n", flags); */ - index = GetUInt16(ptr, 2, 1); - ptr += 4; - - if (listFind(glyphlist, (void *) (sal_IntPtr) index)) { -#if OSL_DEBUG_LEVEL > 1 - fprintf(stderr, "Endless loop found in a compound glyph.\n"); - fprintf(stderr, "%d -> ", index); - listToFirst(glyphlist); - fprintf(stderr," ["); - do { - fprintf(stderr,"%d ", (int) listCurrent(glyphlist)); - } while (listNext(glyphlist)); - fprintf(stderr,"]\n"); - /**/ -#endif - } - - listAppend(glyphlist, (void *) (sal_IntPtr) index); - -#ifdef DEBUG2 - fprintf(stderr,"glyphlist: += %d\n", index); -#endif - - if ((np = GetTTGlyphOutline(ttf, index, &nextComponent, 0, glyphlist)) == 0) { - /* XXX that probably indicates a corrupted font */ -#if OSL_DEBUG_LEVEL > 1 - fprintf(stderr, "An empty compound!\n"); - /* assert(!"An empty compound"); */ -#endif - } - - listToLast(glyphlist); -#ifdef DEBUG2 - listToFirst(glyphlist); - fprintf(stderr,"%d [", listCount(glyphlist)); - if (!listIsEmpty(glyphlist)) { - do { - fprintf(stderr,"%d ", (int) listCurrent(glyphlist)); - } while (listNext(glyphlist)); - } - fprintf(stderr, "]\n"); - fprintf(stderr, "glyphlist: -= %d\n", (int) listCurrent(glyphlist)); - -#endif - listRemove(glyphlist); - - if (flags & USE_MY_METRICS) { - if (metrics) GetMetrics(ttf, index, metrics); - } - - if (flags & ARG_1_AND_2_ARE_WORDS) { - e = GetInt16(ptr, 0, 1); - f = GetInt16(ptr, 2, 1); - /* printf("ARG_1_AND_2_ARE_WORDS: %d %d\n", e & 0xFFFF, f & 0xFFFF); */ - ptr += 4; - } else { - if (flags & ARGS_ARE_XY_VALUES) { /* args are signed */ - e = (sal_Int8) *ptr++; - f = (sal_Int8) *ptr++; - /* printf("ARGS_ARE_XY_VALUES: %d %d\n", e & 0xFF, f & 0xFF); */ - } else { /* args are unsigned */ - /* printf("!ARGS_ARE_XY_VALUES\n"); */ - e = *ptr++; - f = *ptr++; - } - - } - - a = d = 0x10000; - b = c = 0; - - if (flags & WE_HAVE_A_SCALE) { -#ifdef DEBUG2 - fprintf(stderr, "WE_HAVE_A_SCALE\n"); -#endif - a = GetInt16(ptr, 0, 1) << 2; - d = a; - ptr += 2; - } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { -#ifdef DEBUG2 - fprintf(stderr, "WE_HAVE_AN_X_AND_Y_SCALE\n"); -#endif - a = GetInt16(ptr, 0, 1) << 2; - d = GetInt16(ptr, 2, 1) << 2; - ptr += 4; - } else if (flags & WE_HAVE_A_TWO_BY_TWO) { -#ifdef DEBUG2 - fprintf(stderr, "WE_HAVE_A_TWO_BY_TWO\n"); -#endif - a = GetInt16(ptr, 0, 1) << 2; - b = GetInt16(ptr, 2, 1) << 2; - c = GetInt16(ptr, 4, 1) << 2; - d = GetInt16(ptr, 6, 1) << 2; - ptr += 8; - } - - abs1 = (a < 0) ? -a : a; - abs2 = (b < 0) ? -b : b; - m = (abs1 > abs2) ? abs1 : abs2; - abs3 = abs1 - abs2; - if (abs3 < 0) abs3 = -abs3; - if (abs3 <= 33) m *= 2; - - abs1 = (c < 0) ? -c : c; - abs2 = (d < 0) ? -d : d; - n = (abs1 > abs2) ? abs1 : abs2; - abs3 = abs1 - abs2; - if (abs3 < 0) abs3 = -abs3; - if (abs3 <= 33) n *= 2; - - if (!ARGS_ARE_XY_VALUES) { /* match the points */ - assert(!"ARGS_ARE_XY_VALUES is not implemented!!!\n"); - } - -#ifdef DEBUG2 - fprintf(stderr, "a: %f, b: %f, c: %f, d: %f, e: %f, f: %f, m: %f, n: %f\n", - ((double) a) / 65536, - ((double) b) / 65536, - ((double) c) / 65536, - ((double) d) / 65536, - ((double) e) / 65536, - ((double) f) / 65536, - ((double) m) / 65536, - ((double) n) / 65536); -#endif - - for (i=0; iflags = nextComponent[i].flags; - t = fixedMulDiv(a, nextComponent[i].x << 16, m) + fixedMulDiv(c, nextComponent[i].y << 16, m) + (e << 16); - cp->x = (sal_Int16)(fixedMul(t, m) >> 16); - t = fixedMulDiv(b, nextComponent[i].x << 16, n) + fixedMulDiv(d, nextComponent[i].y << 16, n) + (f << 16); - cp->y = (sal_Int16)(fixedMul(t, n) >> 16); - -#ifdef DEBUG2 - fprintf(stderr, "( %d %d ) -> ( %d %d )\n", nextComponent[i].x, nextComponent[i].y, cp->x, cp->y); -#endif - - listAppend(myPoints, cp); - } - - free(nextComponent); - - } while (flags & MORE_COMPONENTS); - - - - np = listCount(myPoints); - - pa = calloc(np, sizeof(ControlPoint)); - assert(pa != 0); - listToFirst(myPoints); - for (i=0; i= ttf->nglyphs) return -1; /**/ - - ptr = table + ttf->goffsets[glyphID]; - length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID]; - - if (length == 0) { /*- empty glyphs still have hmtx and vmtx metrics values */ - if (metrics) GetMetrics(ttf, glyphID, metrics); - return 0; - } - - numberOfContours = GetInt16(ptr, 0, 1); - - if (numberOfContours >= 0) { - res=GetSimpleTTOutline(ttf, glyphID, pointArray, metrics); - } else { - int glyphlistFlag = 0; - if (!glyphlist) { - glyphlistFlag = 1; - glyphlist = listNewEmpty(); - listAppend(glyphlist, (void *) (sal_IntPtr) glyphID); - } - res = GetCompoundTTOutline(ttf, glyphID, pointArray, metrics, glyphlist); - if (glyphlistFlag) { - glyphlistFlag = 0; - listDispose(glyphlist); - glyphlist = 0; - } - } - -#ifdef DEBUG3 - { - int i; - FILE *out = fopen("points.dat", "a"); - assert(out != 0); - fprintf(out, "Glyph: %d\nPoints: %d\n", glyphID, res); - for (i=0; itype = t; - return p; -} - -/*- returns the number of items in the path -*/ - -static int BSplineToPSPath(ControlPoint *srcA, int srcCount, PSPathElement **path) -{ - list pList = listNewEmpty(); - int i = 0, pCount = 0; - PSPathElement *p; - - int x0 = 0, y0 = 0, x1 = 0, y1 = 0, x2, y2, curx, cury; - int lastOff = 0; /*- last point was off-contour */ - int scflag = 1; /*- start contour flag */ - int ecflag = 0; /*- end contour flag */ - int cp = 0; /*- current point */ - int StartContour = 0, EndContour = 1; - - listSetElementDtor(pList, free); - *path = 0; - - /* if (srcCount > 0) for(;;) */ - while (srcCount > 0) { /*- srcCount does not get changed inside the loop. */ - if (scflag) { - int l = cp; - StartContour = cp; - while (!(srcA[l].flags & 0x8000)) l++; - EndContour = l; - if (StartContour == EndContour) { - if (cp + 1 < srcCount) { - cp++; - continue; - } else { - break; - } - } - p = newPSPathElement(PS_MOVETO); - if (!(srcA[cp].flags & 1)) { - if (!(srcA[EndContour].flags & 1)) { - p->x1 = x0 = (srcA[cp].x + srcA[EndContour].x + 1) / 2; - p->y1 = y0 = (srcA[cp].y + srcA[EndContour].y + 1) / 2; - } else { - p->x1 = x0 = srcA[EndContour].x; - p->y1 = y0 = srcA[EndContour].y; - } - } else { - p->x1 = x0 = srcA[cp].x; - p->y1 = y0 = srcA[cp].y; - cp++; - } - listAppend(pList, p); - lastOff = 0; - scflag = 0; - } - - curx = srcA[cp].x; - cury = srcA[cp].y; - - if (srcA[cp].flags & 1) { - if (lastOff) { - p = newPSPathElement(PS_CURVETO); - p->x1 = x0 + (2 * (x1 - x0) + 1) / 3; - p->y1 = y0 + (2 * (y1 - y0) + 1) / 3; - p->x2 = x1 + (curx - x1 + 1) / 3; - p->y2 = y1 + (cury - y1 + 1) / 3; - p->x3 = curx; - p->y3 = cury; - listAppend(pList, p); - } else { - if (!(x0 == curx && y0 == cury)) { /* eliminate empty lines */ - p = newPSPathElement(PS_LINETO); - p->x1 = curx; - p->y1 = cury; - listAppend(pList, p); - } - } - - x0 = curx; y0 = cury; lastOff = 0; - } else { - if (lastOff) { - x2 = (x1 + curx + 1) / 2; - y2 = (y1 + cury + 1) / 2; - p = newPSPathElement(PS_CURVETO); - p->x1 = x0 + (2 * (x1 - x0) + 1) / 3; - p->y1 = y0 + (2 * (y1 - y0) + 1) / 3; - p->x2 = x1 + (x2 - x1 + 1) / 3; - p->y2 = y1 + (y2 - y1 + 1) / 3; - p->x3 = x2; - p->y3 = y2; - listAppend(pList, p); - x0 = x2; y0 = y2; - x1 = curx; y1 = cury; - } else { - x1 = curx; y1 = cury; - } - lastOff = true; - } - - if (ecflag) { - listAppend(pList, newPSPathElement(PS_CLOSEPATH)); - scflag = 1; - ecflag = 0; - cp = EndContour + 1; - if (cp >= srcCount) break; - continue; - } - - - if (cp == EndContour) { - cp = StartContour; - ecflag = true; - } else { - cp++; - } - } - - if ((pCount = listCount(pList)) > 0) { - p = calloc(pCount, sizeof(PSPathElement)); - assert(p != 0); - listToFirst(pList); - for (i=0; i= (name+nTableSize-len) ) - { - if( ucs2result ) - *ucs2result = NULL; - return NULL; - } - - if( ucs2result ) - *ucs2result = NULL; - if (dbFlag) { - res = malloc(1 + len/2); - assert(res != 0); - for (i = 0; i < len/2; i++) res[i] = *(ptr + i * 2 + 1); - res[len/2] = 0; - if( ucs2result ) - { - *ucs2result = malloc( len+2 ); - for (i = 0; i < len/2; i++ ) (*ucs2result)[i] = GetUInt16( ptr, 2*i, 1 ); - (*ucs2result)[len/2] = 0; - } - } else { - res = malloc(1 + len); - assert(res != 0); - memcpy(res, ptr, len); - res[len] = 0; - } - - return res; -} - -static int findname(sal_uInt8 *name, sal_uInt16 n, sal_uInt16 platformID, sal_uInt16 encodingID, sal_uInt16 languageID, sal_uInt16 nameID) -{ - int l = 0, r = n-1, i; - sal_uInt32 t1, t2; - sal_uInt32 m1, m2; - - if (n == 0) return -1; - - m1 = (platformID << 16) | encodingID; - m2 = (languageID << 16) | nameID; - - do { - i = (l + r) >> 1; - t1 = GetUInt32(name + 6, i * 12 + 0, 1); - t2 = GetUInt32(name + 6, i * 12 + 4, 1); - - if (! ((m1 < t1) || ((m1 == t1) && (m2 < t2)))) l = i + 1; - if (! ((m1 > t1) || ((m1 == t1) && (m2 > t2)))) r = i - 1; - } while (l <= r); - - if (l - r == 2) { - return l - 1; - } - - return -1; -} - -/* XXX marlett.ttf uses (3, 0, 1033) instead of (3, 1, 1033) and does not have any Apple tables. - * Fix: if (3, 1, 1033) is not found - need to check for (3, 0, 1033) - * - * /d/fonts/ttzh_tw/Big5/Hanyi/ma6b5p uses (1, 0, 19) for English strings, instead of (1, 0, 0) - * and does not have (3, 1, 1033) - * Fix: if (1, 0, 0) and (3, 1, 1033) are not found need to look for (1, 0, *) - that will - * require a change in algorithm - * - * /d/fonts/fdltest/Korean/h2drrm has unsorted names and a an unknown (to me) Mac LanguageID, - * but (1, 0, 1042) strings usable - * Fix: change algorithm, and use (1, 0, *) if both standard Mac and MS strings are not found - */ - -static void GetNames(TrueTypeFont *t) -{ - sal_uInt8 *table = getTable(t, O_name); - int nTableSize = getTableSize(t, O_name); - - sal_uInt16 n = GetUInt16(table, 2, 1); - int i, r; - sal_Bool bPSNameOK = sal_True; - - /* #129743# simple sanity check for name table entry count */ - if( nTableSize <= n * 12 + 6 ) - n = 0; - - /* PostScript name: preferred Microsoft */ - t->psname = NULL; - if ((r = findname(table, n, 3, 1, 0x0409, 6)) != -1) - t->psname = nameExtract(table, nTableSize, r, 1, NULL); - if ( ! t->psname && (r = findname(table, n, 1, 0, 0, 6)) != -1) - t->psname = nameExtract(table, nTableSize, r, 0, NULL); - if ( ! t->psname && (r = findname(table, n, 3, 0, 0x0409, 6)) != -1) - { - // some symbol fonts like Marlett have a 3,0 name! - t->psname = nameExtract(table, nTableSize, r, 1, NULL); - } - if ( ! t->psname ) - { - if ( t->fname ) - { - char* pReverse = t->fname + strlen(t->fname); - /* take only last token of filename */ - while(pReverse != t->fname && *pReverse != '/') pReverse--; - if(*pReverse == '/') pReverse++; - t->psname = strdup(pReverse); - assert(t->psname != 0); - for (i=strlen(t->psname) - 1; i > 0; i--) - { - /*- Remove the suffix -*/ - if (t->psname[i] == '.' ) { - t->psname[i] = 0; - break; - } - } - } - else - t->psname = strdup( "Unknown" ); - } - - /* Font family and subfamily names: preferred Apple */ - t->family = NULL; - if ((r = findname(table, n, 0, 0, 0, 1)) != -1) - t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); - if ( ! t->family && (r = findname(table, n, 3, 1, 0x0409, 1)) != -1) - t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); - if ( ! t->family && (r = findname(table, n, 1, 0, 0, 1)) != -1) - t->family = nameExtract(table, nTableSize, r, 0, NULL); - if ( ! t->family && (r = findname(table, n, 3, 1, 0x0411, 1)) != -1) - t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); - if ( ! t->family && (r = findname(table, n, 3, 0, 0x0409, 1)) != -1) - t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); - if ( ! t->family ) - { - t->family = strdup(t->psname); - assert(t->family != 0); - } - - t->subfamily = NULL; - t->usubfamily = NULL; - if ((r = findname(table, n, 1, 0, 0, 2)) != -1) - t->subfamily = nameExtract(table, nTableSize, r, 0, &t->usubfamily); - if ( ! t->subfamily && (r = findname(table, n, 3, 1, 0x0409, 2)) != -1) - t->subfamily = nameExtract(table, nTableSize, r, 1, &t->usubfamily); - if ( ! t->subfamily ) - { - t->subfamily = strdup(""); - } - - /* #i60349# sanity check psname - * psname parctically has to be 7bit ascii and should not contains spaces - * there is a class of broken fonts which do not fullfill that at all, so let's try - * if the family name is 7bit ascii and take it instead if so - */ - /* check psname */ - for( i = 0; t->psname[i] != 0 && bPSNameOK; i++ ) - if( t->psname[ i ] < 33 || (t->psname[ i ] & 0x80) ) - bPSNameOK = sal_False; - if( bPSNameOK == sal_False ) - { - sal_Bool bReplace = sal_True; - /* check if family is a suitable replacement */ - if( t->ufamily && t->family ) - { - for( i = 0; t->ufamily[ i ] != 0 && bReplace; i++ ) - if( t->ufamily[ i ] < 33 || t->ufamily[ i ] > 127 ) - bReplace = sal_False; - if( bReplace ) - { - free( t->psname ); - t->psname = strdup( t->family ); - } - } - } -} - -enum cmapType { - CMAP_NOT_USABLE = -1, - CMAP_MS_Symbol = 10, - CMAP_MS_Unicode = 11, - CMAP_MS_ShiftJIS = 12, - CMAP_MS_Big5 = 13, - CMAP_MS_PRC = 14, - CMAP_MS_Wansung = 15, - CMAP_MS_Johab = 16 -}; - -#define MISSING_GLYPH_INDEX 0 - -/* - * getGlyph[0246]() functions and freinds are implemented by: - * @author Manpreet Singh - * getGlyph12() function and friends by: - * @author HDU - */ -static sal_uInt32 getGlyph0(const sal_uInt8* cmap, sal_uInt32 c) { - if (c <= 255) { - return *(cmap + 6 + c); - } else { - return MISSING_GLYPH_INDEX; - } -} - -typedef struct _subHeader2 { - sal_uInt16 firstCode; - sal_uInt16 entryCount; - sal_uInt16 idDelta; - sal_uInt16 idRangeOffset; -} subHeader2; - -static sal_uInt32 getGlyph2(const sal_uInt8 *cmap, sal_uInt32 c) { - sal_uInt16 *CMAP2 = (sal_uInt16 *) cmap; - sal_uInt8 theHighByte; - - sal_uInt8 theLowByte; - subHeader2* subHeader2s; - sal_uInt16* subHeader2Keys; - sal_uInt16 firstCode; - int k; - sal_uInt32 ToReturn; - - theHighByte = (sal_uInt8)((c >> 8) & 0x00ff); - theLowByte = (sal_uInt8)(c & 0x00ff); - subHeader2Keys = CMAP2 + 3; - subHeader2s = (subHeader2 *)(subHeader2Keys + 256); - k = Int16FromMOTA(subHeader2Keys[theHighByte]) / 8; - - if(k == 0) { - firstCode = Int16FromMOTA(subHeader2s[k].firstCode); - if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) { - return *((&(subHeader2s[0].idRangeOffset)) - + (Int16FromMOTA(subHeader2s[0].idRangeOffset)/2) /* + offset */ - + theLowByte /* + to_look */ - - Int16FromMOTA(subHeader2s[0].firstCode) - ); - } else { - return MISSING_GLYPH_INDEX; - } - } else if (k > 0) { - firstCode = Int16FromMOTA(subHeader2s[k].firstCode); - if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) { - ToReturn = *((&(subHeader2s[k].idRangeOffset)) - + (Int16FromMOTA(subHeader2s[k].idRangeOffset)/2) - + theLowByte - firstCode); - if(ToReturn == 0) { - return MISSING_GLYPH_INDEX; - } else { - ToReturn += Int16FromMOTA(subHeader2s[k].idDelta); - return (ToReturn & 0xFFFF); - } - } else { - return MISSING_GLYPH_INDEX; - } - } else { - return MISSING_GLYPH_INDEX; - } -} - -static sal_uInt32 getGlyph6(const sal_uInt8 *cmap, sal_uInt32 c) { - sal_uInt16 firstCode, lastCode, count; - sal_uInt16 *CMAP6 = (sal_uInt16 *) cmap; - - firstCode = Int16FromMOTA(*(CMAP6 + 3)); - count = Int16FromMOTA(*(CMAP6 + 4)); - lastCode = firstCode + count - 1; - if (c < firstCode || c > lastCode) { - return MISSING_GLYPH_INDEX; - } else { - return *((CMAP6 + 5)/*glyphIdArray*/ + (c - firstCode)); - } -} - -static sal_uInt16 GEbinsearch(sal_uInt16 *ar, sal_uInt16 length, sal_uInt16 toSearch) { - signed int low, mid, high, lastfound = 0xffff; - sal_uInt16 res; - if(length == (sal_uInt16)0 || length == (sal_uInt16)0xFFFF) { - return (sal_uInt16)0xFFFF; - } - low = 0; - high = length - 1; - while(high >= low) { - mid = (high + low)/2; - res = Int16FromMOTA(*(ar+mid)); - if(res >= toSearch) { - lastfound = mid; - high = --mid; - } else { - low = ++mid; - } - } - return (sal_uInt16)lastfound; -} - - -static sal_uInt32 getGlyph4(const sal_uInt8 *cmap, sal_uInt32 c) { - sal_uInt16 i; - int ToReturn; - sal_uInt16 segCount; - sal_uInt16 * startCode; - sal_uInt16 * endCode; - sal_uInt16 * idDelta; - /* sal_uInt16 * glyphIdArray; */ - sal_uInt16 * idRangeOffset; - sal_uInt16 * glyphIndexArray; - sal_uInt16 *CMAP4 = (sal_uInt16 *) cmap; - /* sal_uInt16 GEbinsearch(sal_uInt16 *ar, sal_uInt16 length, sal_uInt16 toSearch); */ - - segCount = Int16FromMOTA(*(CMAP4 + 3))/2; - endCode = CMAP4 + 7; - i = GEbinsearch(endCode, segCount, (sal_uInt16)c); - - if (i == (sal_uInt16) 0xFFFF) { - return MISSING_GLYPH_INDEX; - } - startCode = endCode + segCount + 1; - - if(Int16FromMOTA(startCode[i]) > c) { - return MISSING_GLYPH_INDEX; - } - idDelta = startCode + segCount; - idRangeOffset = idDelta + segCount; - glyphIndexArray = idRangeOffset + segCount; - - if(Int16FromMOTA(idRangeOffset[i]) != 0) { - c = Int16FromMOTA(*(&(idRangeOffset[i]) + (Int16FromMOTA(idRangeOffset[i])/2 + (c - Int16FromMOTA(startCode[i]))))); - } - - ToReturn = (Int16FromMOTA(idDelta[i]) + c) & 0xFFFF; - return ToReturn; -} - -static sal_uInt32 getGlyph12(const sal_uInt8 *pCmap, sal_uInt32 cChar) { - const sal_uInt32* pCMAP12 = (const sal_uInt32*)pCmap; - int nLength = Int32FromMOTA( pCMAP12[1] ); - int nGroups = Int32FromMOTA( pCMAP12[3] ); - int nLower = 0; - int nUpper = nGroups; - - if( nUpper > (nLength-16)/12 ) - nUpper = (nLength-16)/12; - - /* binary search in "segmented coverage" subtable */ - while( nLower < nUpper ) { - int nIndex = (nLower + nUpper) / 2; - const sal_uInt32* pEntry = &pCMAP12[ 4 + 3*nIndex ]; - sal_uInt32 cStart = Int32FromMOTA( pEntry[0] ); - sal_uInt32 cLast = Int32FromMOTA( pEntry[1] ); - if( cChar < cStart ) - nUpper = nIndex; - else if( cChar > cLast ) - nLower = nIndex + 1; - else { /* found matching entry! */ - sal_uInt32 nGlyph = Int32FromMOTA( pEntry[2] ); - nGlyph += cChar - cStart; - return nGlyph; - } - } - - return MISSING_GLYPH_INDEX; -} - - -static void FindCmap(TrueTypeFont *ttf) -{ - sal_uInt8 *table = getTable(ttf, O_cmap); - sal_uInt32 table_size = getTableSize(ttf, O_cmap); - sal_uInt16 ncmaps = GetUInt16(table, 2, 1); - unsigned int i; - sal_uInt32 ThreeZero = 0; /* MS Symbol */ - sal_uInt32 ThreeOne = 0; /* MS UCS-2 */ - sal_uInt32 ThreeTwo = 0; /* MS ShiftJIS */ - sal_uInt32 ThreeThree = 0; /* MS Big5 */ - sal_uInt32 ThreeFour = 0; /* MS PRC */ - sal_uInt32 ThreeFive = 0; /* MS Wansung */ - sal_uInt32 ThreeSix = 0; /* MS Johab */ - - for (i = 0; i < ncmaps; i++) { - sal_uInt32 offset; - sal_uInt16 pID, eID; - - /* sanity check, cmap entry must lie within table */ - if( i*8+4 > table_size ) - break; - - pID = GetUInt16(table, 4 + i * 8, 1); - eID = GetUInt16(table, 6 + i * 8, 1); - offset = GetUInt32(table, 8 + i * 8, 1); - - /* sanity check, cmap must lie within file */ - if( (table - ttf->ptr) + offset > (sal_uInt32)ttf->fsize ) - continue; - - /* Unicode tables in Apple fonts */ - if (pID == 0) { - ThreeOne = offset; break; - } - - if (pID == 3) { - switch (eID) { - case 0: ThreeZero = offset; break; - case 10: // UCS-4 - case 1: ThreeOne = offset; break; - case 2: ThreeTwo = offset; break; - case 3: ThreeThree = offset; break; - case 4: ThreeFour = offset; break; - case 5: ThreeFive = offset; break; - case 6: ThreeSix = offset; break; - } - } - } - - if (ThreeOne) { - ttf->cmapType = CMAP_MS_Unicode; - ttf->cmap = table + ThreeOne; - } else if (ThreeTwo) { - ttf->cmapType = CMAP_MS_ShiftJIS; - ttf->cmap = table + ThreeTwo; - } else if (ThreeThree) { - ttf->cmapType = CMAP_MS_Big5; - ttf->cmap = table + ThreeThree; - } else if (ThreeFour) { - ttf->cmapType = CMAP_MS_PRC; - ttf->cmap = table + ThreeFour; - } else if (ThreeFive) { - ttf->cmapType = CMAP_MS_Wansung; - ttf->cmap = table + ThreeFive; - } else if (ThreeSix) { - ttf->cmapType = CMAP_MS_Johab; - ttf->cmap = table + ThreeSix; - } else if (ThreeZero) { - ttf->cmapType = CMAP_MS_Symbol; - ttf->cmap = table + ThreeZero; - } else { - ttf->cmapType = CMAP_NOT_USABLE; - ttf->cmap = 0; - } - - if (ttf->cmapType != CMAP_NOT_USABLE) { - switch (GetUInt16(ttf->cmap, 0, 1)) { - case 0: ttf->mapper = getGlyph0; break; - case 2: ttf->mapper = getGlyph2; break; - case 4: ttf->mapper = getGlyph4; break; - case 6: ttf->mapper = getGlyph6; break; - case 12: ttf->mapper= getGlyph12; break; - default: -#if OSL_DEBUG_LEVEL > 1 - /*- if the cmap table is really broken */ - printf("%s: %d is not a recognized cmap format.\n", ttf->fname, GetUInt16(ttf->cmap, 0, 1)); -#endif - ttf->cmapType = CMAP_NOT_USABLE; - ttf->cmap = 0; - ttf->mapper = 0; - } - } -} - -static void GetKern(TrueTypeFont *ttf) -{ - sal_uInt8 *table = getTable(ttf, O_kern); - sal_uInt8 *ptr; - sal_uInt32 i; - /* - sal_uInt16 v1; - sal_uInt32 v2; - */ - - if (!table) goto badtable; - - if (GetUInt16(table, 0, 1) == 0) { /* Traditional Microsoft style table with USHORT version and nTables fields */ - ttf->nkern = GetUInt16(table, 2, 1); - ttf->kerntables = calloc(ttf->nkern, sizeof(sal_uInt8 *)); - assert(ttf->kerntables != 0); - memset(ttf->kerntables, 0, ttf->nkern * sizeof(sal_uInt8 *)); - ttf->kerntype = KT_MICROSOFT; - ptr = table + 4; - for (i=0; i < ttf->nkern; i++) { - ttf->kerntables[i] = ptr; - ptr += GetUInt16(ptr, 2, 1); - /* sanity check */ - if( ptr > ttf->ptr+ttf->fsize ) - { - free( ttf->kerntables ); - goto badtable; - } - } - return; - } - - if (GetUInt32(table, 0, 1) == 0x00010000) { /* MacOS style kern tables: fixed32 version and sal_uInt32 nTables fields */ - ttf->nkern = GetUInt32(table, 4, 1); - ttf->kerntables = calloc(ttf->nkern, sizeof(sal_uInt8 *)); - assert(ttf->kerntables != 0); - memset(ttf->kerntables, 0, ttf->nkern * sizeof(sal_uInt8 *)); - ttf->kerntype = KT_APPLE_NEW; - ptr = table + 8; - for (i = 0; i < ttf->nkern; i++) { - ttf->kerntables[i] = ptr; - ptr += GetUInt32(ptr, 0, 1); - /* sanity check; there are some fonts that are broken in this regard */ - if( ptr > ttf->ptr+ttf->fsize ) - { - free( ttf->kerntables ); - goto badtable; - } - } - return; - } - - badtable: - ttf->kerntype = KT_NONE; - ttf->kerntables = 0; - - return; -} - -#ifdef TEST5 -/* KernGlyphsPrim?() functions expect the caller to ensure the validity of their arguments and - * that x and y elements of the kern array are initialized to zeroes - */ -static void KernGlyphsPrim1(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) -{ - (void)ttf; /* avoid warning */ - (void)glyphs; /* avoid warning */ - (void)nglyphs; /* avoid warning */ - (void)wmode; /* avoid warning */ - (void)nglyphs; /* avoid warning */ - (void)kern; /* avoid warning */ - fprintf(stderr, "MacOS kerning tables have not been implemented yet!\n"); -} - -static void KernGlyphsPrim2(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) -{ - sal_uInt32 i, j; - sal_uInt32 gpair; - - if( ! nglyphs ) - return; - - for (i = 0; i < (sal_uInt32)nglyphs - 1; i++) { - gpair = (glyphs[i] << 16) | glyphs[i+1]; -#ifdef DEBUG2 - /* All fonts with MS kern table that I've seen so far contain just one kern subtable. - * MS kern documentation is very poor and I doubt that font developers will be using - * several subtables. I expect them to be using OpenType tables instead. - * According to MS documention, format 2 subtables are not supported by Windows and OS/2. - */ - if (ttf->nkern > 1) { - fprintf(stderr, "KernGlyphsPrim2: %d kern tables found.\n", ttf->nkern); - } -#endif - for (j = 0; j < ttf->nkern; j++) { - sal_uInt16 coverage = GetUInt16(ttf->kerntables[j], 4, 1); - sal_uInt8 *ptr; - int npairs; - sal_uInt32 t; - int l, r, k; - - if (! ((coverage & 1) ^ wmode)) continue; - if ((coverage & 0xFFFE) != 0) { -#ifdef DEBUG2 - fprintf(stderr, "KernGlyphsPrim2: coverage flags are not supported: %04X.\n", coverage); -#endif - continue; - } - ptr = ttf->kerntables[j]; - npairs = GetUInt16(ptr, 6, 1); - ptr += 14; - l = 0; - r = npairs; - do { - k = (l + r) >> 1; - t = GetUInt32(ptr, k * 6, 1); - if (gpair >= t) l = k + 1; - if (gpair <= t) r = k - 1; - } while (l <= r); - if (l - r == 2) { - if (!wmode) { - kern[i].x = XUnits(ttf->unitsPerEm, GetInt16(ptr, 4 + (l-1) * 6, 1)); - } else { - kern[i].y = XUnits(ttf->unitsPerEm, GetInt16(ptr, 4 + (l-1) * 6, 1)); - } - /* !wmode ? kern[i].x : kern[i].y = GetInt16(ptr, 4 + (l-1) * 6, 1); */ - } - } - } -} -#endif - -/*- Public functions */ /*FOLD00*/ - -int CountTTCFonts(const char* fname) -{ - int nFonts = 0; - sal_uInt8 buffer[12]; - FILE* fd = fopen(fname, "rb"); - if( fd ) { - if (fread(buffer, 1, 12, fd) == 12) { - if(GetUInt32(buffer, 0, 1) == T_ttcf ) - nFonts = GetUInt32(buffer, 8, 1); - } - fclose(fd); - } - return nFonts; -} - -static void allocTrueTypeFont( TrueTypeFont** ttf ) -{ - *ttf = calloc(1,sizeof(TrueTypeFont)); - if( *ttf != NULL ) - { - (*ttf)->tag = 0; - (*ttf)->fname = 0; - (*ttf)->fsize = -1; - (*ttf)->ptr = 0; - (*ttf)->nglyphs = 0xFFFFFFFF; - (*ttf)->pGSubstitution = 0; - } -} - -/* forward declariotn for the two entry points to use*/ -static int doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t ); - -#if !defined(WIN32) && !defined(OS2) -int OpenTTFontFile( const char* fname, sal_uInt32 facenum, TrueTypeFont** ttf ) -{ - int ret, fd = -1; - struct stat st; - - if (!fname || !*fname) return SF_BADFILE; - - allocTrueTypeFont( ttf ); - if( ! *ttf ) - return SF_MEMORY; - - (*ttf)->fname = strdup(fname); - if( ! (*ttf)->fname ) - { - ret = SF_MEMORY; - goto cleanup; - } - - fd = open(fname, O_RDONLY); - - if (fd == -1) { - ret = SF_BADFILE; - goto cleanup; - } - - if (fstat(fd, &st) == -1) { - ret = SF_FILEIO; - goto cleanup; - } - - (*ttf)->fsize = st.st_size; - - /* On Mac OS, most likely will happen if a Mac user renames a font file - * to be .ttf when its really a Mac resource-based font. - * Size will be 0, but fonts smaller than 4 bytes would be broken anyway. - */ - if ((*ttf)->fsize == 0) { - ret = SF_BADFILE; - goto cleanup; - } - - - if (((*ttf)->ptr = (sal_uInt8 *) mmap(0, (*ttf)->fsize, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { - ret = SF_MEMORY; - goto cleanup; - } - close(fd); - - return doOpenTTFont( facenum, *ttf ); - -cleanup: - if (fd != -1) close(fd); - /*- t and t->fname have been allocated! */ - free((*ttf)->fname); - free(*ttf); - *ttf = NULL; - return ret; -} -#endif - -int OpenTTFontBuffer(void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf) -{ - allocTrueTypeFont( ttf ); - if( *ttf == NULL ) - return SF_MEMORY; - - (*ttf)->fname = NULL; - (*ttf)->fsize = nLen; - (*ttf)->ptr = pBuffer; - - return doOpenTTFont( facenum, *ttf ); -} - -static int doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t ) -{ - int i; - sal_uInt32 version; - sal_uInt8 *table, *offset; - sal_uInt32 length, tag; - sal_uInt32 tdoffset = 0; /* offset to TableDirectory in a TTC file. For TTF files is 0 */ - int indexfmt, k; - - version = GetInt32(t->ptr, 0, 1); - - if ((version == 0x00010000) || (version == T_true)) { - tdoffset = 0; - } else if (version == T_ttcf) { /*- TrueType collection */ - if (GetUInt32(t->ptr, 4, 1) != 0x00010000) { - CloseTTFont(t); - return SF_TTFORMAT; - } - if (facenum >= GetUInt32(t->ptr, 8, 1)) { - CloseTTFont(t); - return SF_FONTNO; - } - tdoffset = GetUInt32(t->ptr, 12 + 4 * facenum, 1); - } else { - CloseTTFont(t); - return SF_TTFORMAT; - } - -#ifdef DEBUG2 - fprintf(stderr, "tdoffset: %d\n", tdoffset); -#endif - - /* magic number */ - t->tag = TTFontClassTag; - - t->ntables = GetUInt16(t->ptr + tdoffset, 4, 1); - if( t->ntables >= 128 ) - return SF_TTFORMAT; - - t->tables = calloc(NUM_TAGS, sizeof(void *)); - assert(t->tables != 0); - t->tlens = calloc(NUM_TAGS, sizeof(sal_uInt32)); - assert(t->tlens != 0); - - memset(t->tables, 0, NUM_TAGS * sizeof(void *)); - memset(t->tlens, 0, NUM_TAGS * sizeof(sal_uInt32)); - - /* parse the tables */ - for (i=0; i<(int)t->ntables; i++) { - int nIndex; - tag = GetUInt32(t->ptr + tdoffset + 12, 16 * i, 1); - switch( tag ) { - case T_maxp: nIndex = O_maxp; break; - case T_glyf: nIndex = O_glyf; break; - case T_head: nIndex = O_head; break; - case T_loca: nIndex = O_loca; break; - case T_name: nIndex = O_name; break; - case T_hhea: nIndex = O_hhea; break; - case T_hmtx: nIndex = O_hmtx; break; - case T_cmap: nIndex = O_cmap; break; - case T_vhea: nIndex = O_vhea; break; - case T_vmtx: nIndex = O_vmtx; break; - case T_OS2 : nIndex = O_OS2; break; - case T_post: nIndex = O_post; break; - case T_kern: nIndex = O_kern; break; - case T_cvt : nIndex = O_cvt; break; - case T_prep: nIndex = O_prep; break; - case T_fpgm: nIndex = O_fpgm; break; - case T_gsub: nIndex = O_gsub; break; - default: nIndex = -1; break; - } - if( nIndex >= 0 ) { - offset = t->ptr + GetUInt32(t->ptr + tdoffset + 12, 16 * i + 8, 1); - length = GetUInt32(t->ptr + tdoffset + 12, 16 * i + 12, 1); - t->tables[nIndex] = offset; - t->tlens[nIndex] = length; - } - } - - /* Fixup offsets when only a TTC extract was provided */ - if( facenum == (sal_uInt32)~0 ) { - sal_uInt8 *pHead = t->tables[O_head], *p = NULL; - if( !pHead ) - return SF_TTFORMAT; - /* limit Head candidate to TTC extract's limits */ - if( pHead > t->ptr + (t->fsize - 54) ) - pHead = t->ptr + (t->fsize - 54); - /* TODO: find better method than searching head table's magic */ - for( p = pHead + 12; p > t->ptr; --p ) { - if( p[0]==0x5F && p[1]==0x0F && p[2]==0x3C && p[3]==0xF5 ) { - int nDelta = (pHead + 12) - p, j; - if( nDelta ) - for( j=0; jtables[j] ) - *(char**)&t->tables[j] -= nDelta; - break; - } - } - if( p <= t->ptr ) - return SF_TTFORMAT; - } - - /* Check the table offsets after TTC correction */ - for (i=0; itables[i] < t->ptr ) - { - t->tlens[i] = 0; - t->tables[i] = NULL; -#if OSL_DEBUG_LEVEL > 1 - fprintf( stderr, "font file %s has bad table offset (tagnum=%d)\n", t->fname, i ); -#endif - } - else if( (sal_uInt8*)t->tables[i] + t->tlens[i] > t->ptr + t->fsize ) - { - int nMaxLen = (t->ptr + t->fsize) - (sal_uInt8*)t->tables[i]; - if( nMaxLen < 0 ) - nMaxLen = 0; - t->tlens[i] = nMaxLen; -#if OSL_DEBUG_LEVEL > 1 - fprintf( stderr, "font file %s has too big table (tagnum=%d)\n", t->fname, i ); -#endif - } - } - - /* At this point TrueTypeFont is constructed, now need to verify the font format - and read the basic font properties */ - - /* The following tables are absolutely required: - * maxp, head, glyf, loca, name, cmap - */ - - if (!(getTable(t, O_maxp) && getTable(t, O_head) && getTable(t, O_glyf) && getTable(t, O_loca) && getTable(t, O_name) && getTable(t, O_cmap) )) { - CloseTTFont(t); - return SF_TTFORMAT; - } - - table = getTable(t, O_maxp); - t->nglyphs = GetUInt16(table, 4, 1); - - table = getTable(t, O_head); - t->unitsPerEm = GetUInt16(table, 18, 1); - indexfmt = GetInt16(table, 50, 1); - - if( ((indexfmt != 0) && (indexfmt != 1)) || (t->unitsPerEm <= 0) ) { - CloseTTFont(t); - return SF_TTFORMAT; - } - - k = (getTableSize(t, O_loca) / (indexfmt ? 4 : 2)) - 1; - if (k < (int)t->nglyphs) t->nglyphs = k; /* Hack for broken Chinese fonts */ - - table = getTable(t, O_loca); - - t->goffsets = (sal_uInt32 *) calloc(1+t->nglyphs, sizeof(sal_uInt32)); - assert(t->goffsets != 0); - - for (i = 0; i <= (int)t->nglyphs; i++) { - t->goffsets[i] = indexfmt ? GetUInt32(table, i << 2, 1) : (sal_uInt32)GetUInt16(table, i << 1, 1) << 1; - } - - table = getTable(t, O_hhea); - t->numberOfHMetrics = (table != 0) ? GetUInt16(table, 34, 1) : 0; - - table = getTable(t, O_vhea); - t->numOfLongVerMetrics = (table != 0) ? GetUInt16(table, 34, 1) : 0; - - GetNames(t); - FindCmap(t); - GetKern(t); - ReadGSUB( t, 0, 0 ); - - return SF_OK; -} - -void CloseTTFont(TrueTypeFont *ttf) /*FOLD01*/ -{ - if (ttf->tag != TTFontClassTag) return; - -#if !defined(WIN32) && !defined(OS2) - if( ttf->fname ) - munmap((char *) ttf->ptr, ttf->fsize); -#endif - free(ttf->fname); - free(ttf->goffsets); - free(ttf->psname); - free(ttf->family); - if( ttf->ufamily ) - free( ttf->ufamily ); - free(ttf->subfamily); - if( ttf->usubfamily ) - free( ttf->usubfamily ); - free(ttf->tables); - free(ttf->tlens); - free(ttf->kerntables); - - ReleaseGSUB(ttf); - - free(ttf); - return; -} - -int GetTTGlyphPoints(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray) -{ - return GetTTGlyphOutline(ttf, glyphID, pointArray, 0, 0); -} - -#ifdef NO_LIST -static -#endif -int GetTTGlyphComponents(TrueTypeFont *ttf, sal_uInt32 glyphID, list glyphlist) -{ - sal_uInt8 *ptr, *glyf = getTable(ttf, O_glyf); - int n = 1; - - if (glyphID >= ttf->nglyphs) return 0; - ptr = glyf + ttf->goffsets[glyphID]; - - listAppend(glyphlist, (void *) (sal_IntPtr) glyphID); - - if (GetInt16(ptr, 0, 1) == -1) { - sal_uInt16 flags, index; - ptr += 10; - do { - flags = GetUInt16(ptr, 0, 1); - index = GetUInt16(ptr, 2, 1); - - ptr += 4; - n += GetTTGlyphComponents(ttf, index, glyphlist); - - if (flags & ARG_1_AND_2_ARE_WORDS) { - ptr += 4; - } else { - ptr += 2; - } - - if (flags & WE_HAVE_A_SCALE) { - ptr += 2; - } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { - ptr += 4; - } else if (flags & WE_HAVE_A_TWO_BY_TWO) { - ptr += 8; - } - } while (flags & MORE_COMPONENTS); - } - - return n; -} - -#ifndef NO_TYPE3 -int CreateT3FromTTGlyphs(TrueTypeFont *ttf, FILE *outf, const char *fname, /*FOLD00*/ - sal_uInt16 *glyphArray, sal_uInt8 *encoding, int nGlyphs, - int wmode) -{ - ControlPoint *pa; - PSPathElement *path; - int i, j, r, n; - sal_uInt8 *table = getTable(ttf, O_head); - TTGlyphMetrics metrics; - int UPEm = ttf->unitsPerEm; - - const char *h01 = "%%!PS-AdobeFont-%d.%d-%d.%d\n"; - const char *h02 = "%% Creator: %s %s %s\n"; - const char *h09 = "%% Original font name: %s\n"; - - const char *h10 = - "30 dict begin\n" - "/PaintType 0 def\n" - "/FontType 3 def\n" - "/StrokeWidth 0 def\n"; - - const char *h11 = "/FontName (%s) cvn def\n"; - - /* - const char *h12 = "%/UniqueID %d def\n"; - */ - const char *h13 = "/FontMatrix [.001 0 0 .001 0 0] def\n"; - const char *h14 = "/FontBBox [%d %d %d %d] def\n"; - - const char *h15= - "/Encoding 256 array def\n" - " 0 1 255 {Encoding exch /.notdef put} for\n"; - - const char *h16 = " Encoding %d /glyph%d put\n"; - const char *h17 = "/XUID [103 0 0 16#%08X %d 16#%08X 16#%08X] def\n"; - - const char *h30 = "/CharProcs %d dict def\n"; - const char *h31 = " CharProcs begin\n"; - const char *h32 = " /.notdef {} def\n"; - const char *h33 = " /glyph%d {\n"; - const char *h34 = " } bind def\n"; - const char *h35 = " end\n"; - - const char *h40 = - "/BuildGlyph {\n" - " exch /CharProcs get exch\n" - " 2 copy known not\n" - " {pop /.notdef} if\n" - " get exec\n" - "} bind def\n" - "/BuildChar {\n" - " 1 index /Encoding get exch get\n" - " 1 index /BuildGlyph get exec\n" - "} bind def\n" - "currentdict end\n"; - - const char *h41 = "(%s) cvn exch definefont pop\n"; - - - if (!((nGlyphs > 0) && (nGlyphs <= 256))) return SF_GLYPHNUM; - if (!glyphArray) return SF_BADARG; - if (!fname) fname = ttf->psname; - - fprintf(outf, h01, GetInt16(table, 0, 1), GetUInt16(table, 2, 1), GetInt16(table, 4, 1), GetUInt16(table, 6, 1)); - fprintf(outf, h02, modname, modver, modextra); - fprintf(outf, h09, ttf->psname); - - fprintf(outf, h10); - fprintf(outf, h11, fname); -/* fprintf(outf, h12, 4000000); */ - - /* XUID generation: - * 103 0 0 C1 C2 C3 C4 - * C1 - CRC-32 of the entire source TrueType font - * C2 - number of glyphs in the subset - * C3 - CRC-32 of the glyph array - * C4 - CRC-32 of the encoding array - * - * All CRC-32 numbers are presented as hexadecimal numbers - */ - - fprintf(outf, h17, rtl_crc32(0, ttf->ptr, ttf->fsize), nGlyphs, rtl_crc32(0, glyphArray, nGlyphs * 2), rtl_crc32(0, encoding, nGlyphs)); - fprintf(outf, h13); - fprintf(outf, h14, XUnits(UPEm, GetInt16(table, 36, 1)), XUnits(UPEm, GetInt16(table, 38, 1)), XUnits(UPEm, GetInt16(table, 40, 1)), XUnits(UPEm, GetInt16(table, 42, 1))); - fprintf(outf, h15); - - for (i = 0; i < nGlyphs; i++) { - fprintf(outf, h16, encoding[i], i); - } - - fprintf(outf, h30, nGlyphs+1); - fprintf(outf, h31); - fprintf(outf, h32); - - for (i = 0; i < nGlyphs; i++) { - fprintf(outf, h33, i); - r = GetTTGlyphOutline(ttf, glyphArray[i] < ttf->nglyphs ? glyphArray[i] : 0, &pa, &metrics, 0); - - if (r > 0) { - n = BSplineToPSPath(pa, r, &path); - } else { - n = 0; /* glyph might have zero contours but valid metrics ??? */ - path = 0; - if (r < 0) { /* glyph is not present in the font - pa array was not allocated, so no need to free it */ - continue; - } - } - fprintf(outf, "\t%d %d %d %d %d %d setcachedevice\n", - wmode == 0 ? XUnits(UPEm, metrics.aw) : 0, - wmode == 0 ? 0 : -XUnits(UPEm, metrics.ah), - XUnits(UPEm, metrics.xMin), - XUnits(UPEm, metrics.yMin), - XUnits(UPEm, metrics.xMax), - XUnits(UPEm, metrics.yMax)); - - for (j = 0; j < n; j++) { - switch (path[j].type) { - case PS_MOVETO: - fprintf(outf, "\t%d %d moveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1)); - break; - - case PS_LINETO: - fprintf(outf, "\t%d %d lineto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1)); - break; - - case PS_CURVETO: - fprintf(outf, "\t%d %d %d %d %d %d curveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1), XUnits(UPEm, path[j].x2), XUnits(UPEm, path[j].y2), XUnits(UPEm, path[j].x3), XUnits(UPEm, path[j].y3)); - break; - - case PS_CLOSEPATH: - fprintf(outf, "\tclosepath\n"); - break; - } - } - if (n > 0) fprintf(outf, "\tfill\n"); /* if glyph is not a whitespace character */ - - fprintf(outf, h34); - - free(pa); - free(path); - } - fprintf(outf, h35); - - fprintf(outf, h40); - fprintf(outf, h41, fname); - - return SF_OK; -} -#endif - -#ifndef NO_TTCR -int CreateTTFromTTGlyphs(TrueTypeFont *ttf, - const char *fname, - sal_uInt16 *glyphArray, - sal_uInt8 *encoding, - int nGlyphs, - int nNameRecs, - NameRecord *nr, - sal_uInt32 flags) -{ - TrueTypeCreator *ttcr; - TrueTypeTable *head=0, *hhea=0, *maxp=0, *cvt=0, *prep=0, *glyf=0, *fpgm=0, *cmap=0, *name=0, *post = 0, *os2 = 0; - sal_uInt8 *p; - int i; - int res; - sal_uInt32 *gID; - - TrueTypeCreatorNewEmpty(T_true, &ttcr); - - /** name **/ - - if (flags & TTCF_AutoName) { - /* not implemented yet - NameRecord *names; - NameRecord newname; - int n = GetTTNameRecords(ttf, &names); - int n1 = 0, n2 = 0, n3 = 0, n4 = 0, n5 = 0, n6 = 0; - sal_uInt8 *cp1; - sal_uInt8 suffix[32]; - sal_uInt32 c1 = crc32(glyphArray, nGlyphs * 2); - sal_uInt32 c2 = crc32(encoding, nGlyphs); - int len; - snprintf(suffix, 31, "S%08X%08X-%d", c1, c2, nGlyphs); - - name = TrueTypeTableNew_name(0, 0); - for (i = 0; i < n; i++) { - if (names[i].platformID == 1 && names[i].encodingID == 0 && names[i].languageID == 0 && names[i].nameID == 1) { - - memcpy(newname, names+i, sizeof(NameRecord)); - newname.slen = name[i].slen + strlen(suffix); - */ - const sal_uInt8 ptr[] = {0,'T',0,'r',0,'u',0,'e',0,'T',0,'y',0,'p',0,'e',0,'S',0,'u',0,'b',0,'s',0,'e',0,'t'}; - NameRecord n1 = {1, 0, 0, 6, 14, (sal_uInt8*)"TrueTypeSubset"}; - NameRecord n2 = {3, 1, 1033, 6, 28, 0}; - n2.sptr = (sal_uInt8 *) ptr; - name = TrueTypeTableNew_name(0, 0); - nameAdd(name, &n1); - nameAdd(name, &n2); - } else { - if (nNameRecs == 0) { - NameRecord *names; - int n = GetTTNameRecords(ttf, &names); - name = TrueTypeTableNew_name(n, names); - DisposeNameRecords(names, n); - } else { - name = TrueTypeTableNew_name(nNameRecs, nr); - } - } - - /** maxp **/ - maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp)); - - /** hhea **/ - p = getTable(ttf, O_hhea); - if (p) { - hhea = TrueTypeTableNew_hhea(GetUInt16(p, 4, 1), GetUInt16(p, 6, 1), GetUInt16(p, 8, 1), GetUInt16(p, 18, 1), GetUInt16(p, 20, 1)); - } else { - hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0); - } - - /** head **/ - - p = getTable(ttf, O_head); - assert(p != 0); - head = TrueTypeTableNew_head(GetUInt32(p, 4, 1), - GetUInt16(p, 16, 1), - GetUInt16(p, 18, 1), - p+20, - GetUInt16(p, 44, 1), - GetUInt16(p, 46, 1), - GetInt16(p, 48, 1)); - - - /** glyf **/ - - glyf = TrueTypeTableNew_glyf(); - gID = scalloc(nGlyphs, sizeof(sal_uInt32)); - - for (i = 0; i < nGlyphs; i++) { - gID[i] = glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf); - } - - /** cmap **/ - cmap = TrueTypeTableNew_cmap(); - - for (i=0; i < nGlyphs; i++) { - cmapAdd(cmap, 0x010000, encoding[i], gID[i]); - } - - /** cvt **/ - if ((p = getTable(ttf, O_cvt)) != 0) { - cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p); - } - - /** prep **/ - if ((p = getTable(ttf, O_prep)) != 0) { - prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p); - } - - /** fpgm **/ - if ((p = getTable(ttf, O_fpgm)) != 0) { - fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p); - } - - /** post **/ - if ((p = getTable(ttf, O_post)) != 0) { - post = TrueTypeTableNew_post(0x00030000, - GetUInt32(p, 4, 1), - GetUInt16(p, 8, 1), - GetUInt16(p, 10, 1), - GetUInt16(p, 12, 1)); - } else { - post = TrueTypeTableNew_post(0x00030000, 0, 0, 0, 0); - } - - if (flags & TTCF_IncludeOS2) { - if ((p = getTable(ttf, O_OS2)) != 0) { - os2 = TrueTypeTableNew(T_OS2, getTableSize(ttf, O_OS2), p); - } - } - - AddTable(ttcr, name); AddTable(ttcr, maxp); AddTable(ttcr, hhea); - AddTable(ttcr, head); AddTable(ttcr, glyf); AddTable(ttcr, cmap); - AddTable(ttcr, cvt ); AddTable(ttcr, prep); AddTable(ttcr, fpgm); - AddTable(ttcr, post); AddTable(ttcr, os2); - - if ((res = StreamToFile(ttcr, fname)) != SF_OK) { -#if OSL_DEBUG_LEVEL > 1 - fprintf(stderr, "StreamToFile: error code: %d.\n", res); -#endif - } - - TrueTypeCreatorDispose(ttcr); - free(gID); - - return res; -} -#endif - - -#ifndef NO_TYPE42 -static GlyphOffsets *GlyphOffsetsNew(sal_uInt8 *sfntP) -{ - GlyphOffsets *res = smalloc(sizeof(GlyphOffsets)); - sal_uInt8 *loca = NULL; - sal_uInt16 i, numTables = GetUInt16(sfntP, 4, 1); - sal_uInt32 locaLen = 0; - sal_Int16 indexToLocFormat = 0; - - for (i = 0; i < numTables; i++) { - sal_uInt32 tag = GetUInt32(sfntP + 12, 16 * i, 1); - sal_uInt32 off = GetUInt32(sfntP + 12, 16 * i + 8, 1); - sal_uInt32 len = GetUInt32(sfntP + 12, 16 * i + 12, 1); - - if (tag == T_loca) { - loca = sfntP + off; - locaLen = len; - } else if (tag == T_head) { - indexToLocFormat = GetInt16(sfntP + off, 50, 1); - } - } - - res->nGlyphs = locaLen / ((indexToLocFormat == 1) ? 4 : 2); - assert(res->nGlyphs != 0); - res->offs = scalloc(res->nGlyphs, sizeof(sal_uInt32)); - - for (i = 0; i < res->nGlyphs; i++) { - if (indexToLocFormat == 1) { - res->offs[i] = GetUInt32(loca, i * 4, 1); - } else { - res->offs[i] = GetUInt16(loca, i * 2, 1) << 1; - } - } - return res; -} - -static void GlyphOffsetsDispose(GlyphOffsets *_this) -{ - if (_this) { - free(_this->offs); - free(_this); - } -} - -static void DumpSfnts(FILE *outf, sal_uInt8 *sfntP) -{ - HexFmt *h = HexFmtNew(outf); - sal_uInt16 i, numTables = GetUInt16(sfntP, 4, 1); - sal_uInt32 j, *offs, *len; - GlyphOffsets *go = GlyphOffsetsNew(sfntP); - sal_uInt8 pad[] = {0,0,0,0}; /* zeroes */ - - assert(numTables <= 9); /* Type42 has 9 required tables */ - - offs = scalloc(numTables, sizeof(sal_uInt32)); - len = scalloc(numTables, sizeof(sal_uInt32)); - - fputs("/sfnts [", outf); - HexFmtOpenString(h); - HexFmtBlockWrite(h, sfntP, 12); /* stream out the Offset Table */ - HexFmtBlockWrite(h, sfntP+12, 16 * numTables); /* stream out the Table Directory */ - - for (i=0; inGlyphs - 1; j++) { - o = go->offs[j]; - l = go->offs[j + 1] - o; - HexFmtBlockWrite(h, glyf + o, l); - } - } - HexFmtBlockWrite(h, pad, (4 - (len & 3)) & 3); - } - HexFmtCloseString(h); - fputs("] def\n", outf); - GlyphOffsetsDispose(go); - HexFmtDispose(h); - free(offs); - free(len); -} - -int CreateT42FromTTGlyphs(TrueTypeFont *ttf, - FILE *outf, - const char *psname, - sal_uInt16 *glyphArray, - sal_uInt8 *encoding, - int nGlyphs) -{ - TrueTypeCreator *ttcr; - TrueTypeTable *head=0, *hhea=0, *maxp=0, *cvt=0, *prep=0, *glyf=0, *fpgm=0; - sal_uInt8 *p; - int i; - int res; - - sal_uInt32 ver, rev; - sal_uInt8 *headP; - - sal_uInt8 *sfntP; - sal_uInt32 sfntLen; - int UPEm = ttf->unitsPerEm; - - sal_uInt16 *gID; - - if (nGlyphs >= 256) return SF_GLYPHNUM; - - assert(psname != 0); - - TrueTypeCreatorNewEmpty(T_true, &ttcr); - - /* head */ - headP = p = getTable(ttf, O_head); - assert(p != 0); - head = TrueTypeTableNew_head(GetUInt32(p, 4, 1), GetUInt16(p, 16, 1), GetUInt16(p, 18, 1), p+20, GetUInt16(p, 44, 1), GetUInt16(p, 46, 1), GetInt16(p, 48, 1)); - ver = GetUInt32(p, 0, 1); - rev = GetUInt32(p, 4, 1); - - /** hhea **/ - p = getTable(ttf, O_hhea); - if (p) { - hhea = TrueTypeTableNew_hhea(GetUInt16(p, 4, 1), GetUInt16(p, 6, 1), GetUInt16(p, 8, 1), GetUInt16(p, 18, 1), GetUInt16(p, 20, 1)); - } else { - hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0); - } - - /** maxp **/ - maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp)); - - /** cvt **/ - if ((p = getTable(ttf, O_cvt)) != 0) { - cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p); - } - - /** prep **/ - if ((p = getTable(ttf, O_prep)) != 0) { - prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p); - } - - /** fpgm **/ - if ((p = getTable(ttf, O_fpgm)) != 0) { - fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p); - } - - /** glyf **/ - glyf = TrueTypeTableNew_glyf(); - gID = scalloc(nGlyphs, sizeof(sal_uInt32)); - - for (i = 0; i < nGlyphs; i++) { - gID[i] = (sal_uInt16)glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf); - } - - AddTable(ttcr, head); AddTable(ttcr, hhea); AddTable(ttcr, maxp); AddTable(ttcr, cvt); - AddTable(ttcr, prep); AddTable(ttcr, glyf); AddTable(ttcr, fpgm); - - if ((res = StreamToMemory(ttcr, &sfntP, &sfntLen)) != SF_OK) { - TrueTypeCreatorDispose(ttcr); - free(gID); - return res; - } - - fprintf(outf, "%%!PS-TrueTypeFont-%d.%d-%d.%d\n", (int)(ver>>16), (int)(ver & 0xFFFF), (int)(rev>>16), (int)(rev & 0xFFFF)); - fprintf(outf, "%%%%Creator: %s %s %s\n", modname, modver, modextra); - fprintf(outf, "%%- Font subset generated from a source font file: '%s'\n", ttf->fname); - fprintf(outf, "%%- Original font name: %s\n", ttf->psname); - fprintf(outf, "%%- Original font family: %s\n", ttf->family); - fprintf(outf, "%%- Original font sub-family: %s\n", ttf->subfamily); - fprintf(outf, "11 dict begin\n"); - fprintf(outf, "/FontName (%s) cvn def\n", psname); - fprintf(outf, "/PaintType 0 def\n"); - fprintf(outf, "/FontMatrix [1 0 0 1 0 0] def\n"); - fprintf(outf, "/FontBBox [%d %d %d %d] def\n", XUnits(UPEm, GetInt16(headP, 36, 1)), XUnits(UPEm, GetInt16(headP, 38, 1)), XUnits(UPEm, GetInt16(headP, 40, 1)), XUnits(UPEm, GetInt16(headP, 42, 1))); - fprintf(outf, "/FontType 42 def\n"); - fprintf(outf, "/Encoding 256 array def\n"); - fprintf(outf, " 0 1 255 {Encoding exch /.notdef put} for\n"); - - for (i = 1; iptr, ttf->fsize), (unsigned int)nGlyphs, (unsigned int)rtl_crc32(0, glyphArray, nGlyphs * 2), (unsigned int)rtl_crc32(0, encoding, nGlyphs)); - - DumpSfnts(outf, sfntP); - - /* dump charstrings */ - fprintf(outf, "/CharStrings %d dict dup begin\n", nGlyphs); - fprintf(outf, "/.notdef 0 def\n"); - for (i = 1; i < (int)glyfCount(glyf); i++) { - fprintf(outf,"/glyph%d %d def\n", i, i); - } - fprintf(outf, "end readonly def\n"); - - fprintf(outf, "FontName currentdict end definefont pop\n"); - TrueTypeCreatorDispose(ttcr); - free(gID); - free(sfntP); - return SF_OK; -} -#endif - - -#ifndef NO_MAPPERS -int MapString(TrueTypeFont *ttf, sal_uInt16 *str, int nchars, sal_uInt16 *glyphArray, int bvertical) -{ - int i; - sal_uInt16 *cp; - - if (ttf->cmapType == CMAP_NOT_USABLE ) return -1; - if (!nchars) return 0; - - if (glyphArray == 0) { - cp = str; - } else { - cp = glyphArray; - } - - switch (ttf->cmapType) { - case CMAP_MS_Symbol: - if( ttf->mapper == getGlyph0 ) { - sal_uInt16 aChar; - for( i = 0; i < nchars; i++ ) { - aChar = str[i]; - if( ( aChar & 0xf000 ) == 0xf000 ) - aChar &= 0x00ff; - cp[i] = aChar; - } - } - else if( glyphArray ) - memcpy(glyphArray, str, nchars * 2); - break; - - case CMAP_MS_Unicode: - if (glyphArray != 0) { - memcpy(glyphArray, str, nchars * 2); - } - break; - - case CMAP_MS_ShiftJIS: TranslateString12(str, cp, nchars); break; - case CMAP_MS_Big5: TranslateString13(str, cp, nchars); break; - case CMAP_MS_PRC: TranslateString14(str, cp, nchars); break; - case CMAP_MS_Wansung: TranslateString15(str, cp, nchars); break; - case CMAP_MS_Johab: TranslateString16(str, cp, nchars); break; - } - - for (i = 0; i < nchars; i++) { - cp[i] = (sal_uInt16)ttf->mapper(ttf->cmap, cp[i]); - if (cp[i]!=0 && bvertical!=0) - cp[i] = (sal_uInt16)UseGSUB(ttf,cp[i],bvertical); - } - return nchars; -} - -sal_uInt16 MapChar(TrueTypeFont *ttf, sal_uInt16 ch, int bvertical) -{ - switch (ttf->cmapType) { - case CMAP_MS_Symbol: - - if( ttf->mapper == getGlyph0 && ( ch & 0xf000 ) == 0xf000 ) - ch &= 0x00ff; - return (sal_uInt16)ttf->mapper(ttf->cmap, ch ); - - case CMAP_MS_Unicode: break; - case CMAP_MS_ShiftJIS: ch = TranslateChar12(ch); break; - case CMAP_MS_Big5: ch = TranslateChar13(ch); break; - case CMAP_MS_PRC: ch = TranslateChar14(ch); break; - case CMAP_MS_Wansung: ch = TranslateChar15(ch); break; - case CMAP_MS_Johab: ch = TranslateChar16(ch); break; - default: return 0; - } - ch = (sal_uInt16)ttf->mapper(ttf->cmap, ch); - if (ch!=0 && bvertical!=0) - ch = (sal_uInt16)UseGSUB(ttf,ch,bvertical); - return ch; -} - -int DoesVerticalSubstitution( TrueTypeFont *ttf, int bvertical) -{ - int nRet = 0; - if( bvertical) - nRet = HasVerticalGSUB( ttf); - return nRet; -} - -#endif - -int GetTTGlyphCount( TrueTypeFont* ttf ) -{ - return ttf->nglyphs; -} - -TTSimpleGlyphMetrics *GetTTSimpleGlyphMetrics(TrueTypeFont *ttf, sal_uInt16 *glyphArray, int nGlyphs, int mode) -{ - sal_uInt8* pTable; - TTSimpleGlyphMetrics *res; - int i; - sal_uInt16 glyphID; - sal_uInt32 n; - int UPEm = ttf->unitsPerEm; - int nTableSize; - - if (mode == 0) { - n = ttf->numberOfHMetrics; - pTable = getTable( ttf, O_hmtx ); - nTableSize = getTableSize( ttf, O_hmtx ); - } else { - n = ttf->numOfLongVerMetrics; - pTable = getTable( ttf, O_vmtx ); - nTableSize = getTableSize( ttf, O_vmtx ); - } - - if (!nGlyphs || !glyphArray) return 0; /* invalid parameters */ - if (!n || !pTable) return 0; /* the font does not contain the requested metrics */ - - res = calloc(nGlyphs, sizeof(TTSimpleGlyphMetrics)); - assert(res != 0); - - for (i=0; inglyphs ) - nLsbOffset = 4 * n + 2 * (glyphID - n); - else /* font is broken -> use lsb of last hmetrics */ - nLsbOffset = nAdvOffset + 2; - } - - if( nAdvOffset >= nTableSize) - res[i].adv = 0; /* better than a crash for buggy fonts */ - else - res[i].adv = SAL_INT_CAST( - sal_uInt16, - XUnits( UPEm, GetUInt16( pTable, nAdvOffset, 1) ) ); - - if( nLsbOffset >= nTableSize) - res[i].sb = 0; /* better than a crash for buggy fonts */ - else - res[i].sb = SAL_INT_CAST( - sal_Int16, - XUnits( UPEm, GetInt16( pTable, nLsbOffset, 1) ) ); - } - - return res; -} - -#ifndef NO_MAPPERS -TTSimpleGlyphMetrics *GetTTSimpleCharMetrics(TrueTypeFont * ttf, sal_uInt16 firstChar, int nChars, int mode) -{ - TTSimpleGlyphMetrics *res = 0; - sal_uInt16 *str; - int i, n; - - str = malloc(nChars * 2); - assert(str != 0); - - for (i=0; iunitsPerEm; - - memset(info, 0, sizeof(TTGlobalFontInfo)); - - info->family = ttf->family; - info->ufamily = ttf->ufamily; - info->subfamily = ttf->subfamily; - info->usubfamily = ttf->usubfamily; - info->psname = ttf->psname; - info->symbolEncoded = (ttf->cmapType == CMAP_MS_Symbol); - - table = getTable(ttf, O_OS2); - if (table) { - info->weight = GetUInt16(table, 4, 1); - info->width = GetUInt16(table, 6, 1); - - /* There are 3 different versions of OS/2 table: original (68 bytes long), - * Microsoft old (78 bytes long) and Microsoft new (86 bytes long,) - * Apple's documentation recommends looking at the table length. - */ - if (getTableSize(ttf, O_OS2) > 68) { - info->typoAscender = XUnits(UPEm,GetInt16(table, 68, 1)); - info->typoDescender = XUnits(UPEm, GetInt16(table, 70, 1)); - info->typoLineGap = XUnits(UPEm, GetInt16(table, 72, 1)); - info->winAscent = XUnits(UPEm, GetUInt16(table, 74, 1)); - info->winDescent = XUnits(UPEm, GetUInt16(table, 76, 1)); - /* sanity check; some fonts treat winDescent as signed - * violating the standard */ - if( info->winDescent > 5*UPEm ) - info->winDescent = XUnits(UPEm, GetInt16(table, 76,1)); - } - if (ttf->cmapType == CMAP_MS_Unicode) { - info->rangeFlag = 1; - info->ur1 = GetUInt32(table, 42, 1); - info->ur2 = GetUInt32(table, 46, 1); - info->ur3 = GetUInt32(table, 50, 1); - info->ur4 = GetUInt32(table, 54, 1); - } - memcpy(info->panose, table + 32, 10); - info->typeFlags = GetUInt16( table, 8, 1 ); - } - - table = getTable(ttf, O_post); - if (table) { - info->pitch = GetUInt32(table, 12, 1); - info->italicAngle = GetInt32(table, 4, 1); - } - - table = getTable(ttf, O_head); /* 'head' tables is always there */ - info->xMin = XUnits(UPEm, GetInt16(table, 36, 1)); - info->yMin = XUnits(UPEm, GetInt16(table, 38, 1)); - info->xMax = XUnits(UPEm, GetInt16(table, 40, 1)); - info->yMax = XUnits(UPEm, GetInt16(table, 42, 1)); - info->macStyle = GetInt16(table, 44, 1); - - table = getTable(ttf, O_hhea); - if (table) { - info->ascender = XUnits(UPEm, GetInt16(table, 4, 1)); - info->descender = XUnits(UPEm, GetInt16(table, 6, 1)); - info->linegap = XUnits(UPEm, GetInt16(table, 8, 1)); - } - - table = getTable(ttf, O_vhea); - if (table) { - info->vascent = XUnits(UPEm, GetInt16(table, 4, 1)); - info->vdescent = XUnits(UPEm, GetInt16(table, 6, 1)); - } -} - -#ifdef TEST5 -void KernGlyphs(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) -{ - int i; - - if (!nglyphs || !glyphs || !kern) return; - - for (i = 0; i < nglyphs-1; i++) kern[i].x = kern[i].y = 0; - - switch (ttf->kerntype) { - case KT_APPLE_NEW: KernGlyphsPrim1(ttf, glyphs, nglyphs, wmode, kern); return; - case KT_MICROSOFT: KernGlyphsPrim2(ttf, glyphs, nglyphs, wmode, kern); return; - default: return; - } -} -#endif - -GlyphData *GetTTRawGlyphData(TrueTypeFont *ttf, sal_uInt32 glyphID) -{ - sal_uInt8 *glyf = getTable(ttf, O_glyf); - sal_uInt8 *hmtx = getTable(ttf, O_hmtx); - sal_uInt32 length; - GlyphData *d; - ControlPoint *cp; - int i, n, m; - - if( glyphID >= ttf->nglyphs ) - return 0; - - /* #127161# check the glyph offsets */ - length = getTableSize( ttf, O_glyf ); - if( length < ttf->goffsets[ glyphID+1 ] ) - return 0; - - length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID]; - - d = malloc(sizeof(GlyphData)); assert(d != 0); - - if (length > 0) { - sal_uInt8 *srcptr = glyf + ttf->goffsets[glyphID]; - d->ptr = malloc((length + 1) & ~1); assert(d->ptr != 0); - memcpy( d->ptr, srcptr, length ); - d->compflag = (GetInt16( srcptr, 0, 1 ) < 0); - } else { - d->ptr = 0; - d->compflag = 0; - } - - d->glyphID = glyphID; - d->nbytes = (sal_uInt16)((length + 1) & ~1); - - /* now calculate npoints and ncontours */ - n = GetTTGlyphPoints(ttf, glyphID, &cp); - if (n != -1) { - m = 0; - for (i = 0; i < n; i++) { - if (cp[i].flags & 0x8000) m++; - } - d->npoints = (sal_uInt16)n; - d->ncontours = (sal_uInt16)m; - free(cp); - } else { - d->npoints = 0; - d->ncontours = 0; - } - - /* get advance width and left sidebearing */ - if (glyphID < ttf->numberOfHMetrics) { - d->aw = GetUInt16(hmtx, 4 * glyphID, 1); - d->lsb = GetInt16(hmtx, 4 * glyphID + 2, 1); - } else { - d->aw = GetUInt16(hmtx, 4 * (ttf->numberOfHMetrics - 1), 1); - d->lsb = GetInt16(hmtx + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2, 1); - } - - return d; -} - -int GetTTNameRecords(TrueTypeFont *ttf, NameRecord **nr) -{ - sal_uInt8 *table = getTable(ttf, O_name); - int nTableSize = getTableSize(ttf, O_name ); - sal_uInt16 n = GetUInt16(table, 2, 1); - sal_uInt8* rec_string = NULL; - int nStrBase = GetUInt16(table, 4, 1); - NameRecord *rec; - int i; - - *nr = 0; - if (n == 0) return 0; - - rec = calloc(n, sizeof(NameRecord)); - - for (i = 0; i < n; i++) { - int nStrOffset = GetUInt16(table + 6, 10 + 12 * i, 1); - rec[i].platformID = GetUInt16(table + 6, 12 * i, 1); - rec[i].encodingID = GetUInt16(table + 6, 2 + 12 * i, 1); - rec[i].languageID = GetUInt16(table + 6, 4 + 12 * i, 1); - rec[i].nameID = GetUInt16(table + 6, 6 + 12 * i, 1); - rec[i].slen = GetUInt16(table + 6, 8 + 12 * i, 1); - if (rec[i].slen) { - if( nStrBase+nStrOffset+rec[i].slen >= nTableSize ) { - rec[i].sptr = 0; - rec[i].slen = 0; - continue; - } - - rec_string = table + nStrBase + nStrOffset; - // sanity check - if( rec_string > (sal_uInt8*)ttf->ptr && rec_string < ((sal_uInt8*)ttf->ptr + ttf->fsize - rec[i].slen ) ) - { - rec[i].sptr = (sal_uInt8 *) malloc(rec[i].slen); assert(rec[i].sptr != 0); - memcpy(rec[i].sptr, rec_string, rec[i].slen); - } - else - { -#ifdef DEBUG - fprintf( stderr, "found invalid name record %d with name id %d for file %s\n", - i, rec[i].nameID, ttf->fname ); -#endif - rec[i].sptr = 0; - rec[i].slen = 0; - } - } else { - rec[i].sptr = 0; - } - // some fonts have 3.0 names => fix them to 3.1 - if( (rec[i].platformID == 3) && (rec[i].encodingID == 0) ) - rec[i].encodingID = 1; - } - - *nr = rec; - return n; -} - -void DisposeNameRecords(NameRecord* nr, int n) -{ - int i; - for (i = 0; i < n; i++) { - if (nr[i].sptr) free(nr[i].sptr); - } - free(nr); -} - - - - -#ifdef TEST1 -/* This example creates a subset of a TrueType font with two encoded characters */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int r; - - /* Array of Unicode source characters */ - sal_uInt16 chars[2]; - - /* Encoding vector maps character encoding to the ordinal number - * of the glyph in the output file */ - sal_uInt8 encoding[2]; - - /* This array is for glyph IDs that source characters map to */ - sal_uInt16 g[2]; - - - if (ac < 2) return 0; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - - /* We want to create the output file that only contains two Unicode characters: - * L'a' and L'A' */ - - chars[0] = L'a'; - chars[1] = L'A'; - - /* Figure out what glyphs do these characters map in our font */ - MapString(fnt, chars, 2, g); - - /* Encode the characters. Value of encoding[i] is the number 0..255 which maps to glyph i of the - * newly generated font */ - encoding[0] = chars[0]; - encoding[1] = chars[1]; - - - /* Generate a subset */ - CreateT3FromTTGlyphs(fnt, stdout, 0, g, encoding, 2, 0); - - /* Now call the dtor for the font */ - CloseTTFont(fnt); - return 0; -} -#endif - -#ifdef TEST2 -/* This example extracts first 224 glyphs from a TT fonts and encodes them starting at 32 */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int i, r; - - /* Array of Unicode source characters */ - sal_uInt16 glyphs[224]; - - /* Encoding vector maps character encoding to the ordinal number - * of the glyph in the output file */ - sal_uInt8 encoding[224]; - - - - for (i=0; i<224; i++) { - glyphs[i] = i; - encoding[i] = 32 + i; - } - - if (ac < 2) return 0; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - - /* Encode the characters. Value of encoding[i] is the number 0..255 which maps to glyph i of the - * newly generated font */ - - /* Generate a subset */ - CreateT3FromTTGlyphs(fnt, stdout, 0, glyphs, encoding, 224, 0); - - /* Now call the dtor for the font */ - CloseTTFont(fnt); - return 0; -} -#endif - -#ifdef TEST3 -/* Glyph metrics example */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int i, r; - sal_uInt16 glyphs[224]; - TTSimpleGlyphMetrics *m; - - for (i=0; i<224; i++) { - glyphs[i] = i; - } - - if (ac < 2) return 0; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - if ((m = GetTTSimpleGlyphMetrics(fnt, glyphs, 224, 0)) == 0) { - printf("Requested metrics is not available\n"); - } else { - for (i=0; i<224; i++) { - printf("%d. advWid: %5d, LSBear: %5d\n", i, m[i].adv, m[i].sb); - } - } - - /* Now call the dtor for the font */ - free(m); - CloseTTFont(fnt); - return 0; -} -#endif - -#ifdef TEST4 -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - TTGlobalFontInfo info; - int i, r; - - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - printf("Font file: %s\n", av[1]); - -#ifdef PRINT_KERN - switch (fnt->kerntype) { - case KT_MICROSOFT: - printf("\tkern: MICROSOFT, ntables: %d.", fnt->nkern); - if (fnt->nkern) { - printf(" ["); - for (i=0; inkern; i++) { - printf("%04X ", GetUInt16(fnt->kerntables[i], 4, 1)); - } - printf("]"); - } - printf("\n"); - break; - - case KT_APPLE_NEW: - printf("\tkern: APPLE_NEW, ntables: %d.", fnt->nkern); - if (fnt->nkern) { - printf(" ["); - for (i=0; inkern; i++) { - printf("%04X ", GetUInt16(fnt->kerntables[i], 4, 1)); - } - printf("]"); - } - printf("\n"); - break; - - case KT_NONE: - printf("\tkern: none.\n"); - break; - - default: - printf("\tkern: unrecoginzed.\n"); - break; - } - printf("\n"); -#endif - - GetTTGlobalFontInfo(fnt, &info); - printf("\tfamily name: `%s`\n", info.family); - printf("\tsubfamily name: `%s`\n", info.subfamily); - printf("\tpostscript name: `%s`\n", info.psname); - printf("\tweight: %d\n", info.weight); - printf("\twidth: %d\n", info.width); - printf("\tpitch: %d\n", info.pitch); - printf("\titalic angle: %d\n", info.italicAngle); - printf("\tbouding box: [%d %d %d %d]\n", info.xMin, info.yMin, info.xMax, info.yMax); - printf("\tascender: %d\n", info.ascender); - printf("\tdescender: %d\n", info.descender); - printf("\tlinegap: %d\n", info.linegap); - printf("\tvascent: %d\n", info.vascent); - printf("\tvdescent: %d\n", info.vdescent); - printf("\ttypoAscender: %d\n", info.typoAscender); - printf("\ttypoDescender: %d\n", info.typoDescender); - printf("\ttypoLineGap: %d\n", info.typoLineGap); - printf("\twinAscent: %d\n", info.winAscent); - printf("\twinDescent: %d\n", info.winDescent); - printf("\tUnicode ranges:\n"); - for (i = 0; i < 32; i++) { - if ((info.ur1 >> i) & 1) { - printf("\t\t\t%s\n", UnicodeRangeName(i)); - } - } - for (i = 0; i < 32; i++) { - if ((info.ur2 >> i) & 1) { - printf("\t\t\t%s\n", UnicodeRangeName(i+32)); - } - } - for (i = 0; i < 32; i++) { - if ((info.ur3 >> i) & 1) { - printf("\t\t\t%s\n", UnicodeRangeName(i+64)); - } - } - for (i = 0; i < 32; i++) { - if ((info.ur4 >> i) & 1) { - printf("\t\t\t%s\n", UnicodeRangeName(i+96)); - } - } - - CloseTTFont(fnt); - return 0; -} -#endif - -#ifdef TEST5 -/* Kerning example */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - sal_uInt16 g[224]; - KernData d[223]; - int r, i, k = 0; - - g[k++] = 11; - g[k++] = 36; - g[k++] = 11; - g[k++] = 98; - g[k++] = 11; - g[k++] = 144; - g[k++] = 41; - g[k++] = 171; - g[k++] = 51; - g[k++] = 15; - - if (ac < 2) return 0; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - KernGlyphs(fnt, g, k, 0, d); - - for (i = 0; i < k-1; i++) { - printf("%3d %3d: [%3d %3d]\n", g[i], g[i+1], d[i].x, d[i].y); - } - - CloseTTFont(fnt); - return 0; -} -#endif - - - -#ifdef TEST6 -/* This example extracts a single glyph from a font */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int r, i; - - sal_uInt16 glyphs[256]; - sal_uInt8 encoding[256]; - - for (i=0; i<256; i++) { - glyphs[i] = 512 + i; - encoding[i] = i; - } - -#if 0 - i=0; - glyphs[i++] = 2001; - glyphs[i++] = 2002; - glyphs[i++] = 2003; - glyphs[i++] = 2004; - glyphs[i++] = 2005; - glyphs[i++] = 2006; - glyphs[i++] = 2007; - glyphs[i++] = 2008; - glyphs[i++] = 2009; - glyphs[i++] = 2010; - glyphs[i++] = 2011; - glyphs[i++] = 2012; - glyphs[i++] = 2013; - glyphs[i++] = 2014; - glyphs[i++] = 2015; - glyphs[i++] = 2016; - glyphs[i++] = 2017; - glyphs[i++] = 2018; - glyphs[i++] = 2019; - glyphs[i++] = 2020; - - - r = 97; - i = 0; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; - encoding[i++] = r++; -#endif - - if (ac < 2) return 0; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - /* Generate a subset */ - CreateT3FromTTGlyphs(fnt, stdout, 0, glyphs, encoding, 256, 0); - - fprintf(stderr, "UnitsPerEm: %d.\n", fnt->unitsPerEm); - - /* Now call the dtor for the font */ - CloseTTFont(fnt); - return 0; -} -#endif - -#ifdef TEST7 -/* NameRecord extraction example */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int r, i, j, n; - NameRecord *nr; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - if ((n = GetTTNameRecords(fnt, &nr)) == 0) { - fprintf(stderr, "No name records in the font.\n"); - return 0; - } - - printf("Number of name records: %d.\n", n); - for (i = 0; i < n; i++) { - printf("%d %d %04X %d [", nr[i].platformID, nr[i].encodingID, nr[i].languageID, nr[i].nameID); - for (j=0; j TrueType subsetting */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - sal_uInt16 glyphArray[] = { 0, 98, 99, 22, 24, 25, 26, 27, 28, 29, 30, 31, 1270, 1289, 34}; - sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; - int r; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - CreateTTFromTTGlyphs(fnt, "subfont.ttf", glyphArray, encoding, 15, 0, 0, TTCF_AutoName | TTCF_IncludeOS2); - - - CloseTTFont(fnt); - - return 0; -} -#endif - -#ifdef TEST9 -/* TrueType -> Type42 subsetting */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - /* - sal_uInt16 glyphArray[] = { 0, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34}; - sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; - */ - sal_uInt16 glyphArray[] = { 0, 6711, 6724, 11133, 11144, 14360, 26, 27, 28, 29, 30, 31, 1270, 1289, 34}; - sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; - int r; - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - CreateT42FromTTGlyphs(fnt, stdout, "testfont", glyphArray, encoding, 15); - - CloseTTFont(fnt); - - return 0; -} -#endif - -#ifdef TEST10 -/* Component glyph test */ -int main(int ac, char **av) -{ - TrueTypeFont *fnt; - int r, i; - list glyphlist = listNewEmpty(); - - - if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { - fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); - return 0; - } - - for (i = 0; i < fnt->nglyphs; i++) { - r = GetTTGlyphComponents(fnt, i, glyphlist); - if (r > 1) { - printf("%d -> ", i); - listToFirst(glyphlist); - do { - printf("%d ", (int) listCurrent(glyphlist)); - } while (listNext(glyphlist)); - printf("\n"); - } else { - printf("%d: single glyph.\n", i); - } - listClear(glyphlist); - } - - CloseTTFont(fnt); - listDispose(glyphlist); - - return 0; -} -#endif - - diff --git a/vcl/source/fontsubset/sft.cxx b/vcl/source/fontsubset/sft.cxx new file mode 100644 index 000000000000..10d4cf774b04 --- /dev/null +++ b/vcl/source/fontsubset/sft.cxx @@ -0,0 +1,3312 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/* + * Sun Font Tools + * + * Author: Alexander Gelfenbain + * + */ + +#if OSL_DEBUG_LEVEL == 0 +# ifndef NDEBUG +# define NDEBUG +# endif +#endif +#include + +#include +#include +#include +#ifdef UNX +#include +#include +#endif +#include "sft.hxx" +#include "gsub.h" +#if ! (defined(NO_TTCR) && defined(NO_TYPE42)) +#include "ttcr.hxx" +#endif +#ifndef NO_MAPPERS /* include MapChar() and MapString() */ +#include "xlat.hxx" +#endif +#ifndef NO_TYPE3 /* include CreateT3FromTTGlyphs() */ +#include +#endif + +#include +#include + +#ifdef TEST7 +#include +#endif + +namespace vcl +{ + +/*- module identification */ + +static const char *modname = "SunTypeTools-TT"; +static const char *modver = "1.0"; +static const char *modextra = "gelf"; + +/*- private functions, constants and data types */ /*FOLD00*/ + +enum PathSegmentType { + PS_NOOP = 0, + PS_MOVETO = 1, + PS_LINETO = 2, + PS_CURVETO = 3, + PS_CLOSEPATH = 4 +}; + +struct PSPathElement +{ + PathSegmentType type; + int x1, y1; + int x2, y2; + int x3, y3; + + PSPathElement( PathSegmentType i_eType ) : type( i_eType ), + x1( 0 ), y1( 0 ), + x2( 0 ), y2( 0 ), + x3( 0 ), y3( 0 ) + { + } +}; + +/*- In horisontal writing mode right sidebearing is calculated using this formula + *- rsb = aw - (lsb + xMax - xMin) -*/ +typedef struct { + sal_Int16 xMin; + sal_Int16 yMin; + sal_Int16 xMax; + sal_Int16 yMax; + sal_uInt16 aw; /*- Advance Width (horisontal writing mode) */ + sal_Int16 lsb; /*- Left sidebearing (horisontal writing mode) */ + sal_uInt16 ah; /*- advance height (vertical writing mode) */ + sal_Int16 tsb; /*- top sidebearing (vertical writing mode) */ +} TTGlyphMetrics; + +#define HFORMAT_LINELEN 64 + +typedef struct { + FILE *o; + char buffer[HFORMAT_LINELEN]; + int bufpos; + int total; +} HexFmt; + +typedef struct { + sal_uInt32 nGlyphs; /* number of glyphs in the font + 1 */ + sal_uInt32 *offs; /* array of nGlyphs offsets */ +} GlyphOffsets; + +/* private tags */ +static const sal_uInt32 TTFontClassTag = 0x74746663; /* 'ttfc' */ + +static const sal_uInt32 T_true = 0x74727565; /* 'true' */ +static const sal_uInt32 T_ttcf = 0x74746366; /* 'ttcf' */ + +/* standard TrueType table tags */ +#define T_maxp 0x6D617870 +#define T_glyf 0x676C7966 +#define T_head 0x68656164 +#define T_loca 0x6C6F6361 +#define T_name 0x6E616D65 +#define T_hhea 0x68686561 +#define T_hmtx 0x686D7478 +#define T_cmap 0x636D6170 +#define T_vhea 0x76686561 +#define T_vmtx 0x766D7478 +#define T_OS2 0x4F532F32 +#define T_post 0x706F7374 +#define T_kern 0x6B65726E +#define T_cvt 0x63767420 +#define T_prep 0x70726570 +#define T_fpgm 0x6670676D +#define T_gsub 0x47535542 + +#define LAST_URANGE_BIT 69 +const char *ulcodes[LAST_URANGE_BIT+2] = { + /* 0 */ "Basic Latin", + /* 1 */ "Latin-1 Supplement", + /* 2 */ "Latin Extended-A", + /* 3 */ "Latin Extended-B", + /* 4 */ "IPA Extensions", + /* 5 */ "Spacing Modifier Letters", + /* 6 */ "Combining Diacritical Marks", + /* 7 */ "Basic Greek", + /* 8 */ "Greek Symbols And Coptic", + /* 9 */ "Cyrillic", + /* 10 */ "Armenian", + /* 11 */ "Basic Hebrew", + /* 12 */ "Hebrew Extended (A and B blocks combined)", + /* 13 */ "Basic Arabic", + /* 14 */ "Arabic Extended", + /* 15 */ "Devanagari", + /* 16 */ "Bengali", + /* 17 */ "Gurmukhi", + /* 18 */ "Gujarati", + /* 19 */ "Oriya", + /* 20 */ "Tamil", + /* 21 */ "Telugu", + /* 22 */ "Kannada", + /* 23 */ "Malayalam", + /* 24 */ "Thai", + /* 25 */ "Lao", + /* 26 */ "Basic Georgian", + /* 27 */ "Georgian Extended", + /* 28 */ "Hangul Jamo", + /* 29 */ "Latin Extended Additional", + /* 30 */ "Greek Extended", + /* 31 */ "General Punctuation", + /* 32 */ "Superscripts And Subscripts", + /* 33 */ "Currency Symbols", + /* 34 */ "Combining Diacritical Marks For Symbols", + /* 35 */ "Letterlike Symbols", + /* 36 */ "Number Forms", + /* 37 */ "Arrows", + /* 38 */ "Mathematical Operators", + /* 39 */ "Miscellaneous Technical", + /* 40 */ "Control Pictures", + /* 41 */ "Optical Character Recognition", + /* 42 */ "Enclosed Alphanumerics", + /* 43 */ "Box Drawing", + /* 44 */ "Block Elements", + /* 45 */ "Geometric Shapes", + /* 46 */ "Miscellaneous Symbols", + /* 47 */ "Dingbats", + /* 48 */ "CJK Symbols And Punctuation", + /* 49 */ "Hiragana", + /* 50 */ "Katakana", + /* 51 */ "Bopomofo", + /* 52 */ "Hangul Compatibility Jamo", + /* 53 */ "CJK Miscellaneous", + /* 54 */ "Enclosed CJK Letters And Months", + /* 55 */ "CJK Compatibility", + /* 56 */ "Hangul", + /* 57 */ "Reserved for Unicode SubRanges", + /* 58 */ "Reserved for Unicode SubRanges", + /* 59 */ "CJK Unified Ideographs", + /* 60 */ "Private Use Area", + /* 61 */ "CJK Compatibility Ideographs", + /* 62 */ "Alphabetic Presentation Forms", + /* 63 */ "Arabic Presentation Forms-A", + /* 64 */ "Combining Half Marks", + /* 65 */ "CJK Compatibility Forms", + /* 66 */ "Small Form Variants", + /* 67 */ "Arabic Presentation Forms-B", + /* 68 */ "Halfwidth And Fullwidth Forms", + /* 69 */ "Specials", + /*70-127*/ "Reserved for Unicode SubRanges" +}; + + + +/*- inline functions */ /*FOLD01*/ +#ifdef __GNUC__ +#define _inline static __inline__ +#else +#define _inline static +#endif + +_inline void *smalloc(size_t size) +{ + void *res = malloc(size); + assert(res != 0); + return res; +} + +_inline void *scalloc(size_t n, size_t size) +{ + void *res = calloc(n, size); + assert(res != 0); + return res; +} + +_inline sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) { + return (a << 24) | (b << 16) | (c << 8) | d; +} + +/*- Data access macros for data stored in big-endian or little-endian format */ +_inline sal_Int16 GetInt16(const sal_uInt8 *ptr, size_t offset, int bigendian) +{ + sal_Int16 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; + } else { + t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_uInt16 GetUInt16(const sal_uInt8 *ptr, size_t offset, int bigendian) +{ + sal_uInt16 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; + } else { + t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_Int32 GetInt32(const sal_uInt8 *ptr, size_t offset, int bigendian) +{ + sal_Int32 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | + (ptr+offset)[2] << 8 | (ptr+offset)[3]; + } else { + t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | + (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_uInt32 GetUInt32(const sal_uInt8 *ptr, size_t offset, int bigendian) +{ + sal_uInt32 t; + assert(ptr != 0); + + + if (bigendian) { + t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | + (ptr+offset)[2] << 8 | (ptr+offset)[3]; + } else { + t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | + (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline void PutInt16(sal_Int16 val, sal_uInt8 *ptr, size_t offset, int bigendian) +{ + assert(ptr != 0); + + if (bigendian) { + ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset+1] = (sal_uInt8)(val & 0xFF); + } else { + ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset] = (sal_uInt8)(val & 0xFF); + } + +} + +#if defined(OSL_BIG_ENDIAN) +#define Int16FromMOTA(a) (a) +#define Int32FromMOTA(a) (a) +#else +static sal_uInt16 Int16FromMOTA(sal_uInt16 a) { + return (sal_uInt16) (((sal_uInt8)((a) >> 8)) | ((sal_uInt8)(a) << 8)); +} +static sal_uInt32 Int32FromMOTA(sal_uInt32 a) { + return ((a>>24)&0xFF) | (((a>>8)&0xFF00) | ((a&0xFF00)<<8) | ((a&0xFF)<<24)); +} +#endif + +_inline F16Dot16 fixedMul(F16Dot16 a, F16Dot16 b) +{ + unsigned int a1, b1; + unsigned int a2, b2; + F16Dot16 res; + int sign; + + sign = (a & 0x80000000) ^ (b & 0x80000000); + if (a < 0) a = -a; + if (b < 0) b = -b; + + a1 = a >> 16; + b1 = a & 0xFFFF; + a2 = b >> 16; + b2 = b & 0xFFFF; + + res = a1 * a2; + + /* if (res > 0x7FFF) assert(!"fixedMul: F16Dot16 overflow"); */ + + res <<= 16; + res += a1 * b2 + b1 * a2 + ((b1 * b2) >> 16); + + return sign ? -res : res; +} + + +_inline F16Dot16 fixedDiv(F16Dot16 a, F16Dot16 b) +{ + unsigned int f, r; + F16Dot16 res; + int sign; + + sign = (a & 0x80000000) ^ (b & 0x80000000); + if (a < 0) a = -a; + if (b < 0) b = -b; + + f = a / b; + r = a % b; + + /* if (f > 0x7FFFF) assert(!"fixedDiv: F16Dot16 overflow"); */ + + while (r > 0xFFFF) { + r >>= 1; + b >>= 1; + } + + res = (f << 16) + (r << 16) / b; + + return sign ? -res : res; +} + +/*- returns a * b / c -*/ +/* XXX provide a real implementation that preserves accuracy */ +_inline F16Dot16 fixedMulDiv(F16Dot16 a, F16Dot16 b, F16Dot16 c) +{ + F16Dot16 res; + + res = fixedMul(a, b); + return fixedDiv(res, c); +} + +/*- Translate units from TT to PS (standard 1/1000) -*/ +_inline int XUnits(int unitsPerEm, int n) +{ + return (n * 1000) / unitsPerEm; +} + +_inline const char *UnicodeRangeName(sal_uInt16 bit) +{ + if (bit > LAST_URANGE_BIT) bit = LAST_URANGE_BIT+1; + + return ulcodes[bit]; +} + +_inline sal_uInt8 *getTable(TrueTypeFont *ttf, sal_uInt32 ord) +{ + return (sal_uInt8*)ttf->tables[ord]; +} + +_inline sal_uInt32 getTableSize(TrueTypeFont *ttf, sal_uInt32 ord) +{ + return ttf->tlens[ord]; +} + +#ifndef NO_TYPE42 +/* Hex Formatter functions */ +static char HexChars[] = "0123456789ABCDEF"; + +static HexFmt *HexFmtNew(FILE *outf) +{ + HexFmt* res = (HexFmt*)smalloc(sizeof(HexFmt)); + res->bufpos = res->total = 0; + res->o = outf; + return res; +} + +static void HexFmtFlush(HexFmt *_this) +{ + if (_this->bufpos) { + fwrite(_this->buffer, 1, _this->bufpos, _this->o); + _this->bufpos = 0; + } +} + + +_inline void HexFmtOpenString(HexFmt *_this) +{ + fputs("<\n", _this->o); +} + +_inline void HexFmtCloseString(HexFmt *_this) +{ + HexFmtFlush(_this); + fputs("00\n>\n", _this->o); +} + +_inline void HexFmtDispose(HexFmt *_this) +{ + HexFmtFlush(_this); + free(_this); +} + +static void HexFmtBlockWrite(HexFmt *_this, const void *ptr, sal_uInt32 size) +{ + sal_uInt8 Ch; + sal_uInt32 i; + + if (_this->total + size > 65534) { + HexFmtFlush(_this); + HexFmtCloseString(_this); + _this->total = 0; + HexFmtOpenString(_this); + } + for (i=0; ibuffer[_this->bufpos++] = HexChars[Ch >> 4]; + _this->buffer[_this->bufpos++] = HexChars[Ch & 0xF]; + if (_this->bufpos == HFORMAT_LINELEN) { + HexFmtFlush(_this); + fputc('\n', _this->o); + } + + } + _this->total += size; +} +#endif + + + +/* Outline Extraction functions */ /*FOLD01*/ + +/* fills the aw and lsb entries of the TTGlyphMetrics structure from hmtx table -*/ +static void GetMetrics(TrueTypeFont *ttf, sal_uInt32 glyphID, TTGlyphMetrics *metrics) +{ + sal_uInt8 *table = getTable(ttf, O_hmtx); + + metrics->aw = metrics->lsb = metrics->ah = metrics->tsb = 0; + if (!table || !ttf->numberOfHMetrics) return; + + if (glyphID < ttf->numberOfHMetrics) { + metrics->aw = GetUInt16(table, 4 * glyphID, 1); + metrics->lsb = GetInt16(table, 4 * glyphID + 2, 1); + } else { + metrics->aw = GetUInt16(table, 4 * (ttf->numberOfHMetrics - 1), 1); + metrics->lsb = GetInt16(table + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2, 1); + } + + table = getTable(ttf, O_vmtx); + if (!table || !ttf->numOfLongVerMetrics) return; + + if (glyphID < ttf->numOfLongVerMetrics) { + metrics->ah = GetUInt16(table, 4 * glyphID, 1); + metrics->tsb = GetInt16(table, 4 * glyphID + 2, 1); + } else { + metrics->ah = GetUInt16(table, 4 * (ttf->numOfLongVerMetrics - 1), 1); + metrics->tsb = GetInt16(table + ttf->numOfLongVerMetrics * 4, (glyphID - ttf->numOfLongVerMetrics) * 2, 1); + } +} + +static int GetTTGlyphOutline(TrueTypeFont *, sal_uInt32 , ControlPoint **, TTGlyphMetrics *, std::vector< sal_uInt32 >* ); + +/* returns the number of control points, allocates the pointArray */ +static int GetSimpleTTOutline(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics) /*FOLD02*/ +{ + sal_uInt8 *table = getTable(ttf, O_glyf); + sal_uInt8 *ptr, *p, flag, n; + sal_Int16 numberOfContours; + sal_uInt16 t, instLen, lastPoint=0; + int i, j, z; + + *pointArray = 0; + + /* printf("GetSimpleTTOutline(%d)\n", glyphID); */ + + if (glyphID >= ttf->nglyphs) return 0; /*- glyph is not present in the font */ + ptr = table + ttf->goffsets[glyphID]; + if ((numberOfContours = GetInt16(ptr, 0, 1)) <= 0) return 0; /*- glyph is not simple */ + + if (metrics) { /*- GetCompoundTTOutline() calls this function with NULL metrics -*/ + metrics->xMin = GetInt16(ptr, 2, 1); + metrics->yMin = GetInt16(ptr, 4, 1); + metrics->xMax = GetInt16(ptr, 6, 1); + metrics->yMax = GetInt16(ptr, 8, 1); + GetMetrics(ttf, glyphID, metrics); + } + + /* determine the last point and be extra safe about it. But probably this code is not needed */ + + for (i=0; i lastPoint) lastPoint = t; + } + + instLen = GetUInt16(ptr, 10 + numberOfContours*2, 1); + p = ptr + 10 + 2 * numberOfContours + 2 + instLen; + ControlPoint* pa = (ControlPoint*)calloc(lastPoint+1, sizeof(ControlPoint)); + + i = 0; + while (i <= lastPoint) { + pa[i++].flags = (sal_uInt32) (flag = *p++); + if (flag & 8) { /*- repeat flag */ + n = *p++; + for (j=0; j lastPoint) { /*- if the font is really broken */ + free(pa); + return 0; + } + pa[i++].flags = flag; + } + } + } + + /*- Process the X coordinate */ + z = 0; + for (i = 0; i <= lastPoint; i++) { + if (pa[i].flags & 0x02) { + if (pa[i].flags & 0x10) { + z += (int) (*p++); + } else { + z -= (int) (*p++); + } + } else if ( !(pa[i].flags & 0x10)) { + z += GetInt16(p, 0, 1); + p += 2; + } + pa[i].x = (sal_Int16)z; + } + + /*- Process the Y coordinate */ + z = 0; + for (i = 0; i <= lastPoint; i++) { + if (pa[i].flags & 0x04) { + if (pa[i].flags & 0x20) { + z += *p++; + } else { + z -= *p++; + } + } else if ( !(pa[i].flags & 0x20)) { + z += GetInt16(p, 0, 1); + p += 2; + } + pa[i].y = (sal_Int16)z; + } + + for (i=0; i& glyphlist) /*FOLD02*/ +{ + sal_uInt16 flags, index; + sal_Int16 e, f, numberOfContours; + sal_uInt8 *table = getTable(ttf, O_glyf); + sal_uInt8 *ptr; + std::vector myPoints; + ControlPoint *nextComponent, *pa; + int i, np; + F16Dot16 a = 0x10000, b = 0, c = 0, d = 0x10000, m, n, abs1, abs2, abs3; + + *pointArray = 0; + /* printf("GetCompoundTTOutline(%d)\n", glyphID); */ + + if (glyphID >= ttf->nglyphs) { /*- incorrect glyphID */ + return 0; + } + ptr = table + ttf->goffsets[glyphID]; + if ((numberOfContours = GetInt16(ptr, 0, 1)) != -1) { /*- glyph is not compound */ + return 0; + } + + if (metrics) { + metrics->xMin = GetInt16(ptr, 2, 1); + metrics->yMin = GetInt16(ptr, 4, 1); + metrics->xMax = GetInt16(ptr, 6, 1); + metrics->yMax = GetInt16(ptr, 8, 1); + GetMetrics(ttf, glyphID, metrics); + } + + ptr += 10; + + do { + flags = GetUInt16(ptr, 0, 1); + /* printf("flags: 0x%X\n", flags); */ + index = GetUInt16(ptr, 2, 1); + ptr += 4; + + if( std::find( glyphlist.begin(), glyphlist.end(), index ) != glyphlist.end() ) + { +#if OSL_DEBUG_LEVEL > 1 + fprintf(stderr, "Endless loop found in a compound glyph.\n"); + fprintf(stderr, "%d -> ", index); + fprintf(stderr," ["); + for( std::vector< sal_uInt32 >::const_iterator it = glyphlist.begin(); + it != glyphlist.end(); ++it ) + { + fprintf( stderr,"%d ", (int) *it ); + } + fprintf(stderr,"]\n"); + /**/ +#endif + } + + glyphlist.push_back( index ); + +#ifdef DEBUG2 + fprintf(stderr,"glyphlist: += %d\n", index); +#endif + + if ((np = GetTTGlyphOutline(ttf, index, &nextComponent, 0, &glyphlist)) == 0) + { + /* XXX that probably indicates a corrupted font */ +#if OSL_DEBUG_LEVEL > 1 + fprintf(stderr, "An empty compound!\n"); + /* assert(!"An empty compound"); */ +#endif + } + +#ifdef DEBUG2 + fprintf(stderr,"%d [", (int)glyphlist.size() ); + for( std::vector< sal_uInt32 >::const_iterator it = glyphlist.begin(); + it != glyphlist.end(); ++it ) + { + fprintf( stderr,"%d ", (int) *it ); + } + fprintf(stderr, "]\n"); + if( ! glyphlist.empty() ) + fprintf(stderr, "glyphlist: -= %d\n", (int) glyphlist.back()); + +#endif + if( ! glyphlist.empty() ) + glyphlist.pop_back(); + + if (flags & USE_MY_METRICS) { + if (metrics) GetMetrics(ttf, index, metrics); + } + + if (flags & ARG_1_AND_2_ARE_WORDS) { + e = GetInt16(ptr, 0, 1); + f = GetInt16(ptr, 2, 1); + /* printf("ARG_1_AND_2_ARE_WORDS: %d %d\n", e & 0xFFFF, f & 0xFFFF); */ + ptr += 4; + } else { + if (flags & ARGS_ARE_XY_VALUES) { /* args are signed */ + e = (sal_Int8) *ptr++; + f = (sal_Int8) *ptr++; + /* printf("ARGS_ARE_XY_VALUES: %d %d\n", e & 0xFF, f & 0xFF); */ + } else { /* args are unsigned */ + /* printf("!ARGS_ARE_XY_VALUES\n"); */ + e = *ptr++; + f = *ptr++; + } + + } + + a = d = 0x10000; + b = c = 0; + + if (flags & WE_HAVE_A_SCALE) { +#ifdef DEBUG2 + fprintf(stderr, "WE_HAVE_A_SCALE\n"); +#endif + a = GetInt16(ptr, 0, 1) << 2; + d = a; + ptr += 2; + } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { +#ifdef DEBUG2 + fprintf(stderr, "WE_HAVE_AN_X_AND_Y_SCALE\n"); +#endif + a = GetInt16(ptr, 0, 1) << 2; + d = GetInt16(ptr, 2, 1) << 2; + ptr += 4; + } else if (flags & WE_HAVE_A_TWO_BY_TWO) { +#ifdef DEBUG2 + fprintf(stderr, "WE_HAVE_A_TWO_BY_TWO\n"); +#endif + a = GetInt16(ptr, 0, 1) << 2; + b = GetInt16(ptr, 2, 1) << 2; + c = GetInt16(ptr, 4, 1) << 2; + d = GetInt16(ptr, 6, 1) << 2; + ptr += 8; + } + + abs1 = (a < 0) ? -a : a; + abs2 = (b < 0) ? -b : b; + m = (abs1 > abs2) ? abs1 : abs2; + abs3 = abs1 - abs2; + if (abs3 < 0) abs3 = -abs3; + if (abs3 <= 33) m *= 2; + + abs1 = (c < 0) ? -c : c; + abs2 = (d < 0) ? -d : d; + n = (abs1 > abs2) ? abs1 : abs2; + abs3 = abs1 - abs2; + if (abs3 < 0) abs3 = -abs3; + if (abs3 <= 33) n *= 2; + + if (!ARGS_ARE_XY_VALUES) { /* match the points */ + assert(!"ARGS_ARE_XY_VALUES is not implemented!!!\n"); + } + +#ifdef DEBUG2 + fprintf(stderr, "a: %f, b: %f, c: %f, d: %f, e: %f, f: %f, m: %f, n: %f\n", + ((double) a) / 65536, + ((double) b) / 65536, + ((double) c) / 65536, + ((double) d) / 65536, + ((double) e) / 65536, + ((double) f) / 65536, + ((double) m) / 65536, + ((double) n) / 65536); +#endif + + for (i=0; i> 16); + t = fixedMulDiv(b, nextComponent[i].x << 16, n) + fixedMulDiv(d, nextComponent[i].y << 16, n) + (f << 16); + cp.y = (sal_Int16)(fixedMul(t, n) >> 16); + +#ifdef DEBUG2 + fprintf(stderr, "( %d %d ) -> ( %d %d )\n", nextComponent[i].x, nextComponent[i].y, cp.x, cp.y); +#endif + + myPoints.push_back( cp ); + } + + free(nextComponent); + + } while (flags & MORE_COMPONENTS); + + + + np = myPoints.size(); + + pa = (ControlPoint*)calloc(np, sizeof(ControlPoint)); + assert(pa != 0); + + memcpy( pa, &myPoints[0], np*sizeof(ControlPoint) ); + + *pointArray = pa; + return np; +} + +/* NOTE: GetTTGlyphOutline() returns -1 if the glyphID is incorrect, + * but Get{Simple|Compound}GlyphOutline returns 0 in such a case. + * + * NOTE: glyphlist is the stack of glyphs traversed while constructing + * a composite glyph. This is a safequard against endless recursion + * in corrupted fonts. + */ +static int GetTTGlyphOutline(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray, TTGlyphMetrics *metrics, std::vector< sal_uInt32 >* glyphlist) +{ + sal_uInt8 *ptr, *table = getTable(ttf, O_glyf); + sal_Int16 numberOfContours; + int length; + int res; + *pointArray = 0; + + if (metrics) { + memset(metrics, 0, sizeof(TTGlyphMetrics)); /*- metrics is initialized to all zeroes */ + } + + if (glyphID >= ttf->nglyphs) return -1; /**/ + + ptr = table + ttf->goffsets[glyphID]; + length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID]; + + if (length == 0) { /*- empty glyphs still have hmtx and vmtx metrics values */ + if (metrics) GetMetrics(ttf, glyphID, metrics); + return 0; + } + + numberOfContours = GetInt16(ptr, 0, 1); + + if (numberOfContours >= 0) + { + res=GetSimpleTTOutline(ttf, glyphID, pointArray, metrics); + } + else + { + std::vector< sal_uInt32 > aPrivList; + aPrivList.push_back( glyphID ); + res = GetCompoundTTOutline(ttf, glyphID, pointArray, metrics, glyphlist ? *glyphlist : aPrivList ); + } + +#ifdef DEBUG3 + { + int i; + FILE *out = fopen("points.dat", "a"); + assert(out != 0); + fprintf(out, "Glyph: %d\nPoints: %d\n", glyphID, res); + for (i=0; i aPathList; + int nPathCount = 0; + PSPathElement p( PS_NOOP ); + + int x0 = 0, y0 = 0, x1 = 0, y1 = 0, x2, y2, curx, cury; + int lastOff = 0; /*- last point was off-contour */ + int scflag = 1; /*- start contour flag */ + int ecflag = 0; /*- end contour flag */ + int cp = 0; /*- current point */ + int StartContour = 0, EndContour = 1; + + *path = 0; + + /* if (srcCount > 0) for(;;) */ + while (srcCount > 0) { /*- srcCount does not get changed inside the loop. */ + if (scflag) { + int l = cp; + StartContour = cp; + while (!(srcA[l].flags & 0x8000)) l++; + EndContour = l; + if (StartContour == EndContour) { + if (cp + 1 < srcCount) { + cp++; + continue; + } else { + break; + } + } + p = PSPathElement(PS_MOVETO); + if (!(srcA[cp].flags & 1)) { + if (!(srcA[EndContour].flags & 1)) { + p.x1 = x0 = (srcA[cp].x + srcA[EndContour].x + 1) / 2; + p.y1 = y0 = (srcA[cp].y + srcA[EndContour].y + 1) / 2; + } else { + p.x1 = x0 = srcA[EndContour].x; + p.y1 = y0 = srcA[EndContour].y; + } + } else { + p.x1 = x0 = srcA[cp].x; + p.y1 = y0 = srcA[cp].y; + cp++; + } + aPathList.push_back( p ); + lastOff = 0; + scflag = 0; + } + + curx = srcA[cp].x; + cury = srcA[cp].y; + + if (srcA[cp].flags & 1) + { + if (lastOff) + { + p = PSPathElement(PS_CURVETO); + p.x1 = x0 + (2 * (x1 - x0) + 1) / 3; + p.y1 = y0 + (2 * (y1 - y0) + 1) / 3; + p.x2 = x1 + (curx - x1 + 1) / 3; + p.y2 = y1 + (cury - y1 + 1) / 3; + p.x3 = curx; + p.y3 = cury; + aPathList.push_back( p ); + } + else + { + if (!(x0 == curx && y0 == cury)) + { /* eliminate empty lines */ + p = PSPathElement(PS_LINETO); + p.x1 = curx; + p.y1 = cury; + aPathList.push_back( p ); + } + } + x0 = curx; y0 = cury; lastOff = 0; + } + else + { + if (lastOff) + { + x2 = (x1 + curx + 1) / 2; + y2 = (y1 + cury + 1) / 2; + p = PSPathElement(PS_CURVETO); + p.x1 = x0 + (2 * (x1 - x0) + 1) / 3; + p.y1 = y0 + (2 * (y1 - y0) + 1) / 3; + p.x2 = x1 + (x2 - x1 + 1) / 3; + p.y2 = y1 + (y2 - y1 + 1) / 3; + p.x3 = x2; + p.y3 = y2; + aPathList.push_back( p ); + x0 = x2; y0 = y2; + x1 = curx; y1 = cury; + } else { + x1 = curx; y1 = cury; + } + lastOff = true; + } + + if (ecflag) { + aPathList.push_back( PSPathElement(PS_CLOSEPATH) ); + scflag = 1; + ecflag = 0; + cp = EndContour + 1; + if (cp >= srcCount) break; + continue; + } + + + if (cp == EndContour) { + cp = StartContour; + ecflag = true; + } else { + cp++; + } + } + + if( (nPathCount = (int)aPathList.size()) > 0) + { + *path = (PSPathElement*)calloc(nPathCount, sizeof(PSPathElement)); + assert(*path != 0); + memcpy( *path, &aPathList[0], nPathCount * sizeof(PSPathElement) ); + } + + return nPathCount; +} + +#endif + +/*- Extracts a string from the name table and allocates memory for it -*/ + +static char *nameExtract(sal_uInt8 *name, int nTableSize, int n, int dbFlag, sal_uInt16** ucs2result ) +{ + int i; + char *res; + sal_uInt8 *ptr = name + GetUInt16(name, 4, 1) + GetUInt16(name + 6, 12 * n + 10, 1); + int len = GetUInt16(name+6, 12 * n + 8, 1); + + // sanity check + if( ! len || ptr >= (name+nTableSize-len) ) + { + if( ucs2result ) + *ucs2result = NULL; + return NULL; + } + + if( ucs2result ) + *ucs2result = NULL; + if (dbFlag) { + res = (char*)malloc(1 + len/2); + assert(res != 0); + for (i = 0; i < len/2; i++) res[i] = *(ptr + i * 2 + 1); + res[len/2] = 0; + if( ucs2result ) + { + *ucs2result = (sal_uInt16*)malloc( len+2 ); + for (i = 0; i < len/2; i++ ) (*ucs2result)[i] = GetUInt16( ptr, 2*i, 1 ); + (*ucs2result)[len/2] = 0; + } + } else { + res = (char*)malloc(1 + len); + assert(res != 0); + memcpy(res, ptr, len); + res[len] = 0; + } + + return res; +} + +static int findname(sal_uInt8 *name, sal_uInt16 n, sal_uInt16 platformID, sal_uInt16 encodingID, sal_uInt16 languageID, sal_uInt16 nameID) +{ + int l = 0, r = n-1, i; + sal_uInt32 t1, t2; + sal_uInt32 m1, m2; + + if (n == 0) return -1; + + m1 = (platformID << 16) | encodingID; + m2 = (languageID << 16) | nameID; + + do { + i = (l + r) >> 1; + t1 = GetUInt32(name + 6, i * 12 + 0, 1); + t2 = GetUInt32(name + 6, i * 12 + 4, 1); + + if (! ((m1 < t1) || ((m1 == t1) && (m2 < t2)))) l = i + 1; + if (! ((m1 > t1) || ((m1 == t1) && (m2 > t2)))) r = i - 1; + } while (l <= r); + + if (l - r == 2) { + return l - 1; + } + + return -1; +} + +/* XXX marlett.ttf uses (3, 0, 1033) instead of (3, 1, 1033) and does not have any Apple tables. + * Fix: if (3, 1, 1033) is not found - need to check for (3, 0, 1033) + * + * /d/fonts/ttzh_tw/Big5/Hanyi/ma6b5p uses (1, 0, 19) for English strings, instead of (1, 0, 0) + * and does not have (3, 1, 1033) + * Fix: if (1, 0, 0) and (3, 1, 1033) are not found need to look for (1, 0, *) - that will + * require a change in algorithm + * + * /d/fonts/fdltest/Korean/h2drrm has unsorted names and a an unknown (to me) Mac LanguageID, + * but (1, 0, 1042) strings usable + * Fix: change algorithm, and use (1, 0, *) if both standard Mac and MS strings are not found + */ + +static void GetNames(TrueTypeFont *t) +{ + sal_uInt8 *table = getTable(t, O_name); + int nTableSize = getTableSize(t, O_name); + + sal_uInt16 n = GetUInt16(table, 2, 1); + int i, r; + sal_Bool bPSNameOK = sal_True; + + /* #129743# simple sanity check for name table entry count */ + if( nTableSize <= n * 12 + 6 ) + n = 0; + + /* PostScript name: preferred Microsoft */ + t->psname = NULL; + if ((r = findname(table, n, 3, 1, 0x0409, 6)) != -1) + t->psname = nameExtract(table, nTableSize, r, 1, NULL); + if ( ! t->psname && (r = findname(table, n, 1, 0, 0, 6)) != -1) + t->psname = nameExtract(table, nTableSize, r, 0, NULL); + if ( ! t->psname && (r = findname(table, n, 3, 0, 0x0409, 6)) != -1) + { + // some symbol fonts like Marlett have a 3,0 name! + t->psname = nameExtract(table, nTableSize, r, 1, NULL); + } + if ( ! t->psname ) + { + if ( t->fname ) + { + char* pReverse = t->fname + strlen(t->fname); + /* take only last token of filename */ + while(pReverse != t->fname && *pReverse != '/') pReverse--; + if(*pReverse == '/') pReverse++; + t->psname = strdup(pReverse); + assert(t->psname != 0); + for (i=strlen(t->psname) - 1; i > 0; i--) + { + /*- Remove the suffix -*/ + if (t->psname[i] == '.' ) { + t->psname[i] = 0; + break; + } + } + } + else + t->psname = strdup( "Unknown" ); + } + + /* Font family and subfamily names: preferred Apple */ + t->family = NULL; + if ((r = findname(table, n, 0, 0, 0, 1)) != -1) + t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); + if ( ! t->family && (r = findname(table, n, 3, 1, 0x0409, 1)) != -1) + t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); + if ( ! t->family && (r = findname(table, n, 1, 0, 0, 1)) != -1) + t->family = nameExtract(table, nTableSize, r, 0, NULL); + if ( ! t->family && (r = findname(table, n, 3, 1, 0x0411, 1)) != -1) + t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); + if ( ! t->family && (r = findname(table, n, 3, 0, 0x0409, 1)) != -1) + t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily); + if ( ! t->family ) + { + t->family = strdup(t->psname); + assert(t->family != 0); + } + + t->subfamily = NULL; + t->usubfamily = NULL; + if ((r = findname(table, n, 1, 0, 0, 2)) != -1) + t->subfamily = nameExtract(table, nTableSize, r, 0, &t->usubfamily); + if ( ! t->subfamily && (r = findname(table, n, 3, 1, 0x0409, 2)) != -1) + t->subfamily = nameExtract(table, nTableSize, r, 1, &t->usubfamily); + if ( ! t->subfamily ) + { + t->subfamily = strdup(""); + } + + /* #i60349# sanity check psname + * psname parctically has to be 7bit ascii and should not contains spaces + * there is a class of broken fonts which do not fullfill that at all, so let's try + * if the family name is 7bit ascii and take it instead if so + */ + /* check psname */ + for( i = 0; t->psname[i] != 0 && bPSNameOK; i++ ) + if( t->psname[ i ] < 33 || (t->psname[ i ] & 0x80) ) + bPSNameOK = sal_False; + if( bPSNameOK == sal_False ) + { + sal_Bool bReplace = sal_True; + /* check if family is a suitable replacement */ + if( t->ufamily && t->family ) + { + for( i = 0; t->ufamily[ i ] != 0 && bReplace; i++ ) + if( t->ufamily[ i ] < 33 || t->ufamily[ i ] > 127 ) + bReplace = sal_False; + if( bReplace ) + { + free( t->psname ); + t->psname = strdup( t->family ); + } + } + } +} + +enum cmapType { + CMAP_NOT_USABLE = -1, + CMAP_MS_Symbol = 10, + CMAP_MS_Unicode = 11, + CMAP_MS_ShiftJIS = 12, + CMAP_MS_Big5 = 13, + CMAP_MS_PRC = 14, + CMAP_MS_Wansung = 15, + CMAP_MS_Johab = 16 +}; + +#define MISSING_GLYPH_INDEX 0 + +/* + * getGlyph[0246]() functions and freinds are implemented by: + * @author Manpreet Singh + * getGlyph12() function and friends by: + * @author HDU + */ +static sal_uInt32 getGlyph0(const sal_uInt8* cmap, sal_uInt32 c) { + if (c <= 255) { + return *(cmap + 6 + c); + } else { + return MISSING_GLYPH_INDEX; + } +} + +typedef struct _subHeader2 { + sal_uInt16 firstCode; + sal_uInt16 entryCount; + sal_uInt16 idDelta; + sal_uInt16 idRangeOffset; +} subHeader2; + +static sal_uInt32 getGlyph2(const sal_uInt8 *cmap, sal_uInt32 c) { + sal_uInt16 *CMAP2 = (sal_uInt16 *) cmap; + sal_uInt8 theHighByte; + + sal_uInt8 theLowByte; + subHeader2* subHeader2s; + sal_uInt16* subHeader2Keys; + sal_uInt16 firstCode; + int k; + sal_uInt32 ToReturn; + + theHighByte = (sal_uInt8)((c >> 8) & 0x00ff); + theLowByte = (sal_uInt8)(c & 0x00ff); + subHeader2Keys = CMAP2 + 3; + subHeader2s = (subHeader2 *)(subHeader2Keys + 256); + k = Int16FromMOTA(subHeader2Keys[theHighByte]) / 8; + + if(k == 0) { + firstCode = Int16FromMOTA(subHeader2s[k].firstCode); + if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) { + return *((&(subHeader2s[0].idRangeOffset)) + + (Int16FromMOTA(subHeader2s[0].idRangeOffset)/2) /* + offset */ + + theLowByte /* + to_look */ + - Int16FromMOTA(subHeader2s[0].firstCode) + ); + } else { + return MISSING_GLYPH_INDEX; + } + } else if (k > 0) { + firstCode = Int16FromMOTA(subHeader2s[k].firstCode); + if(theLowByte >= firstCode && theLowByte < (firstCode + Int16FromMOTA(subHeader2s[k].entryCount))) { + ToReturn = *((&(subHeader2s[k].idRangeOffset)) + + (Int16FromMOTA(subHeader2s[k].idRangeOffset)/2) + + theLowByte - firstCode); + if(ToReturn == 0) { + return MISSING_GLYPH_INDEX; + } else { + ToReturn += Int16FromMOTA(subHeader2s[k].idDelta); + return (ToReturn & 0xFFFF); + } + } else { + return MISSING_GLYPH_INDEX; + } + } else { + return MISSING_GLYPH_INDEX; + } +} + +static sal_uInt32 getGlyph6(const sal_uInt8 *cmap, sal_uInt32 c) { + sal_uInt16 firstCode, lastCode, count; + sal_uInt16 *CMAP6 = (sal_uInt16 *) cmap; + + firstCode = Int16FromMOTA(*(CMAP6 + 3)); + count = Int16FromMOTA(*(CMAP6 + 4)); + lastCode = firstCode + count - 1; + if (c < firstCode || c > lastCode) { + return MISSING_GLYPH_INDEX; + } else { + return *((CMAP6 + 5)/*glyphIdArray*/ + (c - firstCode)); + } +} + +static sal_uInt16 GEbinsearch(sal_uInt16 *ar, sal_uInt16 length, sal_uInt16 toSearch) { + signed int low, mid, high, lastfound = 0xffff; + sal_uInt16 res; + if(length == (sal_uInt16)0 || length == (sal_uInt16)0xFFFF) { + return (sal_uInt16)0xFFFF; + } + low = 0; + high = length - 1; + while(high >= low) { + mid = (high + low)/2; + res = Int16FromMOTA(*(ar+mid)); + if(res >= toSearch) { + lastfound = mid; + high = --mid; + } else { + low = ++mid; + } + } + return (sal_uInt16)lastfound; +} + + +static sal_uInt32 getGlyph4(const sal_uInt8 *cmap, sal_uInt32 c) { + sal_uInt16 i; + int ToReturn; + sal_uInt16 segCount; + sal_uInt16 * startCode; + sal_uInt16 * endCode; + sal_uInt16 * idDelta; + /* sal_uInt16 * glyphIdArray; */ + sal_uInt16 * idRangeOffset; + sal_uInt16 * glyphIndexArray; + sal_uInt16 *CMAP4 = (sal_uInt16 *) cmap; + /* sal_uInt16 GEbinsearch(sal_uInt16 *ar, sal_uInt16 length, sal_uInt16 toSearch); */ + + segCount = Int16FromMOTA(*(CMAP4 + 3))/2; + endCode = CMAP4 + 7; + i = GEbinsearch(endCode, segCount, (sal_uInt16)c); + + if (i == (sal_uInt16) 0xFFFF) { + return MISSING_GLYPH_INDEX; + } + startCode = endCode + segCount + 1; + + if(Int16FromMOTA(startCode[i]) > c) { + return MISSING_GLYPH_INDEX; + } + idDelta = startCode + segCount; + idRangeOffset = idDelta + segCount; + glyphIndexArray = idRangeOffset + segCount; + + if(Int16FromMOTA(idRangeOffset[i]) != 0) { + c = Int16FromMOTA(*(&(idRangeOffset[i]) + (Int16FromMOTA(idRangeOffset[i])/2 + (c - Int16FromMOTA(startCode[i]))))); + } + + ToReturn = (Int16FromMOTA(idDelta[i]) + c) & 0xFFFF; + return ToReturn; +} + +static sal_uInt32 getGlyph12(const sal_uInt8 *pCmap, sal_uInt32 cChar) { + const sal_uInt32* pCMAP12 = (const sal_uInt32*)pCmap; + int nLength = Int32FromMOTA( pCMAP12[1] ); + int nGroups = Int32FromMOTA( pCMAP12[3] ); + int nLower = 0; + int nUpper = nGroups; + + if( nUpper > (nLength-16)/12 ) + nUpper = (nLength-16)/12; + + /* binary search in "segmented coverage" subtable */ + while( nLower < nUpper ) { + int nIndex = (nLower + nUpper) / 2; + const sal_uInt32* pEntry = &pCMAP12[ 4 + 3*nIndex ]; + sal_uInt32 cStart = Int32FromMOTA( pEntry[0] ); + sal_uInt32 cLast = Int32FromMOTA( pEntry[1] ); + if( cChar < cStart ) + nUpper = nIndex; + else if( cChar > cLast ) + nLower = nIndex + 1; + else { /* found matching entry! */ + sal_uInt32 nGlyph = Int32FromMOTA( pEntry[2] ); + nGlyph += cChar - cStart; + return nGlyph; + } + } + + return MISSING_GLYPH_INDEX; +} + + +static void FindCmap(TrueTypeFont *ttf) +{ + sal_uInt8 *table = getTable(ttf, O_cmap); + sal_uInt32 table_size = getTableSize(ttf, O_cmap); + sal_uInt16 ncmaps = GetUInt16(table, 2, 1); + unsigned int i; + sal_uInt32 ThreeZero = 0; /* MS Symbol */ + sal_uInt32 ThreeOne = 0; /* MS UCS-2 */ + sal_uInt32 ThreeTwo = 0; /* MS ShiftJIS */ + sal_uInt32 ThreeThree = 0; /* MS Big5 */ + sal_uInt32 ThreeFour = 0; /* MS PRC */ + sal_uInt32 ThreeFive = 0; /* MS Wansung */ + sal_uInt32 ThreeSix = 0; /* MS Johab */ + + for (i = 0; i < ncmaps; i++) { + sal_uInt32 offset; + sal_uInt16 pID, eID; + + /* sanity check, cmap entry must lie within table */ + if( i*8+4 > table_size ) + break; + + pID = GetUInt16(table, 4 + i * 8, 1); + eID = GetUInt16(table, 6 + i * 8, 1); + offset = GetUInt32(table, 8 + i * 8, 1); + + /* sanity check, cmap must lie within file */ + if( (table - ttf->ptr) + offset > (sal_uInt32)ttf->fsize ) + continue; + + /* Unicode tables in Apple fonts */ + if (pID == 0) { + ThreeOne = offset; break; + } + + if (pID == 3) { + switch (eID) { + case 0: ThreeZero = offset; break; + case 10: // UCS-4 + case 1: ThreeOne = offset; break; + case 2: ThreeTwo = offset; break; + case 3: ThreeThree = offset; break; + case 4: ThreeFour = offset; break; + case 5: ThreeFive = offset; break; + case 6: ThreeSix = offset; break; + } + } + } + + if (ThreeOne) { + ttf->cmapType = CMAP_MS_Unicode; + ttf->cmap = table + ThreeOne; + } else if (ThreeTwo) { + ttf->cmapType = CMAP_MS_ShiftJIS; + ttf->cmap = table + ThreeTwo; + } else if (ThreeThree) { + ttf->cmapType = CMAP_MS_Big5; + ttf->cmap = table + ThreeThree; + } else if (ThreeFour) { + ttf->cmapType = CMAP_MS_PRC; + ttf->cmap = table + ThreeFour; + } else if (ThreeFive) { + ttf->cmapType = CMAP_MS_Wansung; + ttf->cmap = table + ThreeFive; + } else if (ThreeSix) { + ttf->cmapType = CMAP_MS_Johab; + ttf->cmap = table + ThreeSix; + } else if (ThreeZero) { + ttf->cmapType = CMAP_MS_Symbol; + ttf->cmap = table + ThreeZero; + } else { + ttf->cmapType = CMAP_NOT_USABLE; + ttf->cmap = 0; + } + + if (ttf->cmapType != CMAP_NOT_USABLE) { + switch (GetUInt16(ttf->cmap, 0, 1)) { + case 0: ttf->mapper = getGlyph0; break; + case 2: ttf->mapper = getGlyph2; break; + case 4: ttf->mapper = getGlyph4; break; + case 6: ttf->mapper = getGlyph6; break; + case 12: ttf->mapper= getGlyph12; break; + default: +#if OSL_DEBUG_LEVEL > 1 + /*- if the cmap table is really broken */ + printf("%s: %d is not a recognized cmap format.\n", ttf->fname, GetUInt16(ttf->cmap, 0, 1)); +#endif + ttf->cmapType = CMAP_NOT_USABLE; + ttf->cmap = 0; + ttf->mapper = 0; + } + } +} + +static void GetKern(TrueTypeFont *ttf) +{ + sal_uInt8 *table = getTable(ttf, O_kern); + sal_uInt8 *ptr; + sal_uInt32 i; + /* + sal_uInt16 v1; + sal_uInt32 v2; + */ + + if (!table) goto badtable; + + if (GetUInt16(table, 0, 1) == 0) { /* Traditional Microsoft style table with USHORT version and nTables fields */ + ttf->nkern = GetUInt16(table, 2, 1); + ttf->kerntables = (sal_uInt8**)calloc(ttf->nkern, sizeof(sal_uInt8 *)); + assert(ttf->kerntables != 0); + memset(ttf->kerntables, 0, ttf->nkern * sizeof(sal_uInt8 *)); + ttf->kerntype = KT_MICROSOFT; + ptr = table + 4; + for (i=0; i < ttf->nkern; i++) { + ttf->kerntables[i] = ptr; + ptr += GetUInt16(ptr, 2, 1); + /* sanity check */ + if( ptr > ttf->ptr+ttf->fsize ) + { + free( ttf->kerntables ); + goto badtable; + } + } + return; + } + + if (GetUInt32(table, 0, 1) == 0x00010000) { /* MacOS style kern tables: fixed32 version and sal_uInt32 nTables fields */ + ttf->nkern = GetUInt32(table, 4, 1); + ttf->kerntables = (sal_uInt8**)calloc(ttf->nkern, sizeof(sal_uInt8*)); + assert(ttf->kerntables != 0); + memset(ttf->kerntables, 0, ttf->nkern * sizeof(sal_uInt8 *)); + ttf->kerntype = KT_APPLE_NEW; + ptr = table + 8; + for (i = 0; i < ttf->nkern; i++) { + ttf->kerntables[i] = ptr; + ptr += GetUInt32(ptr, 0, 1); + /* sanity check; there are some fonts that are broken in this regard */ + if( ptr > ttf->ptr+ttf->fsize ) + { + free( ttf->kerntables ); + goto badtable; + } + } + return; + } + + badtable: + ttf->kerntype = KT_NONE; + ttf->kerntables = 0; + + return; +} + +#ifdef TEST5 +/* KernGlyphsPrim?() functions expect the caller to ensure the validity of their arguments and + * that x and y elements of the kern array are initialized to zeroes + */ +static void KernGlyphsPrim1(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) +{ + (void)ttf; /* avoid warning */ + (void)glyphs; /* avoid warning */ + (void)nglyphs; /* avoid warning */ + (void)wmode; /* avoid warning */ + (void)nglyphs; /* avoid warning */ + (void)kern; /* avoid warning */ + fprintf(stderr, "MacOS kerning tables have not been implemented yet!\n"); +} + +static void KernGlyphsPrim2(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) +{ + sal_uInt32 i, j; + sal_uInt32 gpair; + + if( ! nglyphs ) + return; + + for (i = 0; i < (sal_uInt32)nglyphs - 1; i++) { + gpair = (glyphs[i] << 16) | glyphs[i+1]; +#ifdef DEBUG2 + /* All fonts with MS kern table that I've seen so far contain just one kern subtable. + * MS kern documentation is very poor and I doubt that font developers will be using + * several subtables. I expect them to be using OpenType tables instead. + * According to MS documention, format 2 subtables are not supported by Windows and OS/2. + */ + if (ttf->nkern > 1) { + fprintf(stderr, "KernGlyphsPrim2: %d kern tables found.\n", ttf->nkern); + } +#endif + for (j = 0; j < ttf->nkern; j++) { + sal_uInt16 coverage = GetUInt16(ttf->kerntables[j], 4, 1); + sal_uInt8 *ptr; + int npairs; + sal_uInt32 t; + int l, r, k; + + if (! ((coverage & 1) ^ wmode)) continue; + if ((coverage & 0xFFFE) != 0) { +#ifdef DEBUG2 + fprintf(stderr, "KernGlyphsPrim2: coverage flags are not supported: %04X.\n", coverage); +#endif + continue; + } + ptr = ttf->kerntables[j]; + npairs = GetUInt16(ptr, 6, 1); + ptr += 14; + l = 0; + r = npairs; + do { + k = (l + r) >> 1; + t = GetUInt32(ptr, k * 6, 1); + if (gpair >= t) l = k + 1; + if (gpair <= t) r = k - 1; + } while (l <= r); + if (l - r == 2) { + if (!wmode) { + kern[i].x = XUnits(ttf->unitsPerEm, GetInt16(ptr, 4 + (l-1) * 6, 1)); + } else { + kern[i].y = XUnits(ttf->unitsPerEm, GetInt16(ptr, 4 + (l-1) * 6, 1)); + } + /* !wmode ? kern[i].x : kern[i].y = GetInt16(ptr, 4 + (l-1) * 6, 1); */ + } + } + } +} +#endif + +/*- Public functions */ /*FOLD00*/ + +int CountTTCFonts(const char* fname) +{ + int nFonts = 0; + sal_uInt8 buffer[12]; + FILE* fd = fopen(fname, "rb"); + if( fd ) { + if (fread(buffer, 1, 12, fd) == 12) { + if(GetUInt32(buffer, 0, 1) == T_ttcf ) + nFonts = GetUInt32(buffer, 8, 1); + } + fclose(fd); + } + return nFonts; +} + +static void allocTrueTypeFont( TrueTypeFont** ttf ) +{ + *ttf = (TrueTypeFont*)calloc(1,sizeof(TrueTypeFont)); + if( *ttf != NULL ) + { + (*ttf)->tag = 0; + (*ttf)->fname = 0; + (*ttf)->fsize = -1; + (*ttf)->ptr = 0; + (*ttf)->nglyphs = 0xFFFFFFFF; + (*ttf)->pGSubstitution = 0; + } +} + +/* forward declariotn for the two entry points to use*/ +static int doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t ); + +#if !defined(WIN32) && !defined(OS2) +int OpenTTFontFile( const char* fname, sal_uInt32 facenum, TrueTypeFont** ttf ) +{ + int ret, fd = -1; + struct stat st; + + if (!fname || !*fname) return SF_BADFILE; + + allocTrueTypeFont( ttf ); + if( ! *ttf ) + return SF_MEMORY; + + (*ttf)->fname = strdup(fname); + if( ! (*ttf)->fname ) + { + ret = SF_MEMORY; + goto cleanup; + } + + fd = open(fname, O_RDONLY); + + if (fd == -1) { + ret = SF_BADFILE; + goto cleanup; + } + + if (fstat(fd, &st) == -1) { + ret = SF_FILEIO; + goto cleanup; + } + + (*ttf)->fsize = st.st_size; + + /* On Mac OS, most likely will happen if a Mac user renames a font file + * to be .ttf when its really a Mac resource-based font. + * Size will be 0, but fonts smaller than 4 bytes would be broken anyway. + */ + if ((*ttf)->fsize == 0) { + ret = SF_BADFILE; + goto cleanup; + } + + + if (((*ttf)->ptr = (sal_uInt8 *) mmap(0, (*ttf)->fsize, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { + ret = SF_MEMORY; + goto cleanup; + } + close(fd); + + return doOpenTTFont( facenum, *ttf ); + +cleanup: + if (fd != -1) close(fd); + /*- t and t->fname have been allocated! */ + free((*ttf)->fname); + free(*ttf); + *ttf = NULL; + return ret; +} +#endif + +int OpenTTFontBuffer(void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf) +{ + allocTrueTypeFont( ttf ); + if( *ttf == NULL ) + return SF_MEMORY; + + (*ttf)->fname = NULL; + (*ttf)->fsize = nLen; + (*ttf)->ptr = (sal_uInt8*)pBuffer; + + return doOpenTTFont( facenum, *ttf ); +} + +static int doOpenTTFont( sal_uInt32 facenum, TrueTypeFont* t ) +{ + int i; + sal_uInt32 length, tag; + sal_uInt32 tdoffset = 0; /* offset to TableDirectory in a TTC file. For TTF files is 0 */ + int indexfmt, k; + + sal_uInt32 version = GetInt32(t->ptr, 0, 1); + + if ((version == 0x00010000) || (version == T_true)) { + tdoffset = 0; + } else if (version == T_ttcf) { /*- TrueType collection */ + if (GetUInt32(t->ptr, 4, 1) != 0x00010000) { + CloseTTFont(t); + return SF_TTFORMAT; + } + if (facenum >= GetUInt32(t->ptr, 8, 1)) { + CloseTTFont(t); + return SF_FONTNO; + } + tdoffset = GetUInt32(t->ptr, 12 + 4 * facenum, 1); + } else { + CloseTTFont(t); + return SF_TTFORMAT; + } + +#ifdef DEBUG2 + fprintf(stderr, "tdoffset: %d\n", tdoffset); +#endif + + /* magic number */ + t->tag = TTFontClassTag; + + t->ntables = GetUInt16(t->ptr + tdoffset, 4, 1); + if( t->ntables >= 128 ) + return SF_TTFORMAT; + + t->tables = (sal_uInt8**)calloc(NUM_TAGS, sizeof(sal_uInt8*)); + assert(t->tables != 0); + t->tlens = (sal_uInt32*)calloc(NUM_TAGS, sizeof(sal_uInt32)); + assert(t->tlens != 0); + + memset(t->tables, 0, NUM_TAGS * sizeof(void *)); + memset(t->tlens, 0, NUM_TAGS * sizeof(sal_uInt32)); + + /* parse the tables */ + for (i=0; i<(int)t->ntables; i++) { + int nIndex; + tag = GetUInt32(t->ptr + tdoffset + 12, 16 * i, 1); + switch( tag ) { + case T_maxp: nIndex = O_maxp; break; + case T_glyf: nIndex = O_glyf; break; + case T_head: nIndex = O_head; break; + case T_loca: nIndex = O_loca; break; + case T_name: nIndex = O_name; break; + case T_hhea: nIndex = O_hhea; break; + case T_hmtx: nIndex = O_hmtx; break; + case T_cmap: nIndex = O_cmap; break; + case T_vhea: nIndex = O_vhea; break; + case T_vmtx: nIndex = O_vmtx; break; + case T_OS2 : nIndex = O_OS2; break; + case T_post: nIndex = O_post; break; + case T_kern: nIndex = O_kern; break; + case T_cvt : nIndex = O_cvt; break; + case T_prep: nIndex = O_prep; break; + case T_fpgm: nIndex = O_fpgm; break; + case T_gsub: nIndex = O_gsub; break; + default: nIndex = -1; break; + } + if( nIndex >= 0 ) { + sal_uInt32 nTableOffset = GetUInt32(t->ptr + tdoffset + 12, 16 * i + 8, 1); + length = GetUInt32(t->ptr + tdoffset + 12, 16 * i + 12, 1); + t->tables[nIndex] = t->ptr + nTableOffset; + t->tlens[nIndex] = length; + } + } + + /* Fixup offsets when only a TTC extract was provided */ + if( facenum == (sal_uInt32)~0 ) { + sal_uInt8* pHead = (sal_uInt8*)t->tables[O_head]; + if( !pHead ) + return SF_TTFORMAT; + /* limit Head candidate to TTC extract's limits */ + if( pHead > t->ptr + (t->fsize - 54) ) + pHead = t->ptr + (t->fsize - 54); + /* TODO: find better method than searching head table's magic */ + sal_uInt8* p = NULL; + for( p = pHead + 12; p > t->ptr; --p ) { + if( p[0]==0x5F && p[1]==0x0F && p[2]==0x3C && p[3]==0xF5 ) { + int nDelta = (pHead + 12) - p, j; + if( nDelta ) + for( j=0; jtables[j] ) + *(char**)&t->tables[j] -= nDelta; + break; + } + } + if( p <= t->ptr ) + return SF_TTFORMAT; + } + + /* Check the table offsets after TTC correction */ + for (i=0; itables[i] < t->ptr ) + { + t->tlens[i] = 0; + t->tables[i] = NULL; +#if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "font file %s has bad table offset (tagnum=%d)\n", t->fname, i ); +#endif + } + else if( (sal_uInt8*)t->tables[i] + t->tlens[i] > t->ptr + t->fsize ) + { + int nMaxLen = (t->ptr + t->fsize) - (sal_uInt8*)t->tables[i]; + if( nMaxLen < 0 ) + nMaxLen = 0; + t->tlens[i] = nMaxLen; +#if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "font file %s has too big table (tagnum=%d)\n", t->fname, i ); +#endif + } + } + + /* At this point TrueTypeFont is constructed, now need to verify the font format + and read the basic font properties */ + + /* The following tables are absolutely required: + * maxp, head, glyf, loca, name, cmap + */ + + if (!(getTable(t, O_maxp) && getTable(t, O_head) && getTable(t, O_glyf) && getTable(t, O_loca) && getTable(t, O_name) && getTable(t, O_cmap) )) { + CloseTTFont(t); + return SF_TTFORMAT; + } + + sal_uInt8* table = getTable(t, O_maxp); + t->nglyphs = GetUInt16(table, 4, 1); + + table = getTable(t, O_head); + t->unitsPerEm = GetUInt16(table, 18, 1); + indexfmt = GetInt16(table, 50, 1); + + if( ((indexfmt != 0) && (indexfmt != 1)) || (t->unitsPerEm <= 0) ) { + CloseTTFont(t); + return SF_TTFORMAT; + } + + k = (getTableSize(t, O_loca) / (indexfmt ? 4 : 2)) - 1; + if (k < (int)t->nglyphs) t->nglyphs = k; /* Hack for broken Chinese fonts */ + + table = getTable(t, O_loca); + + t->goffsets = (sal_uInt32 *) calloc(1+t->nglyphs, sizeof(sal_uInt32)); + assert(t->goffsets != 0); + + for (i = 0; i <= (int)t->nglyphs; i++) { + t->goffsets[i] = indexfmt ? GetUInt32(table, i << 2, 1) : (sal_uInt32)GetUInt16(table, i << 1, 1) << 1; + } + + table = getTable(t, O_hhea); + t->numberOfHMetrics = (table != 0) ? GetUInt16(table, 34, 1) : 0; + + table = getTable(t, O_vhea); + t->numOfLongVerMetrics = (table != 0) ? GetUInt16(table, 34, 1) : 0; + + GetNames(t); + FindCmap(t); + GetKern(t); + ReadGSUB( t, 0, 0 ); + + return SF_OK; +} + +void CloseTTFont(TrueTypeFont *ttf) /*FOLD01*/ +{ + if (ttf->tag != TTFontClassTag) return; + +#if !defined(WIN32) && !defined(OS2) + if( ttf->fname ) + munmap((char *) ttf->ptr, ttf->fsize); +#endif + free(ttf->fname); + free(ttf->goffsets); + free(ttf->psname); + free(ttf->family); + if( ttf->ufamily ) + free( ttf->ufamily ); + free(ttf->subfamily); + if( ttf->usubfamily ) + free( ttf->usubfamily ); + free(ttf->tables); + free(ttf->tlens); + free(ttf->kerntables); + + ReleaseGSUB(ttf); + + free(ttf); + return; +} + +int GetTTGlyphPoints(TrueTypeFont *ttf, sal_uInt32 glyphID, ControlPoint **pointArray) +{ + return GetTTGlyphOutline(ttf, glyphID, pointArray, 0, 0); +} + +int GetTTGlyphComponents(TrueTypeFont *ttf, sal_uInt32 glyphID, std::vector< sal_uInt32 >& glyphlist) +{ + sal_uInt8 *ptr, *glyf = getTable(ttf, O_glyf); + int n = 1; + + if (glyphID >= ttf->nglyphs) return 0; + ptr = glyf + ttf->goffsets[glyphID]; + + glyphlist.push_back( glyphID ); + + if (GetInt16(ptr, 0, 1) == -1) { + sal_uInt16 flags, index; + ptr += 10; + do { + flags = GetUInt16(ptr, 0, 1); + index = GetUInt16(ptr, 2, 1); + + ptr += 4; + n += GetTTGlyphComponents(ttf, index, glyphlist); + + if (flags & ARG_1_AND_2_ARE_WORDS) { + ptr += 4; + } else { + ptr += 2; + } + + if (flags & WE_HAVE_A_SCALE) { + ptr += 2; + } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { + ptr += 4; + } else if (flags & WE_HAVE_A_TWO_BY_TWO) { + ptr += 8; + } + } while (flags & MORE_COMPONENTS); + } + + return n; +} + +#ifndef NO_TYPE3 +int CreateT3FromTTGlyphs(TrueTypeFont *ttf, FILE *outf, const char *fname, /*FOLD00*/ + sal_uInt16 *glyphArray, sal_uInt8 *encoding, int nGlyphs, + int wmode) +{ + ControlPoint *pa; + PSPathElement *path; + int i, j, r, n; + sal_uInt8 *table = getTable(ttf, O_head); + TTGlyphMetrics metrics; + int UPEm = ttf->unitsPerEm; + + const char *h01 = "%%!PS-AdobeFont-%d.%d-%d.%d\n"; + const char *h02 = "%% Creator: %s %s %s\n"; + const char *h09 = "%% Original font name: %s\n"; + + const char *h10 = + "30 dict begin\n" + "/PaintType 0 def\n" + "/FontType 3 def\n" + "/StrokeWidth 0 def\n"; + + const char *h11 = "/FontName (%s) cvn def\n"; + + /* + const char *h12 = "%/UniqueID %d def\n"; + */ + const char *h13 = "/FontMatrix [.001 0 0 .001 0 0] def\n"; + const char *h14 = "/FontBBox [%d %d %d %d] def\n"; + + const char *h15= + "/Encoding 256 array def\n" + " 0 1 255 {Encoding exch /.notdef put} for\n"; + + const char *h16 = " Encoding %d /glyph%d put\n"; + const char *h17 = "/XUID [103 0 0 16#%08X %d 16#%08X 16#%08X] def\n"; + + const char *h30 = "/CharProcs %d dict def\n"; + const char *h31 = " CharProcs begin\n"; + const char *h32 = " /.notdef {} def\n"; + const char *h33 = " /glyph%d {\n"; + const char *h34 = " } bind def\n"; + const char *h35 = " end\n"; + + const char *h40 = + "/BuildGlyph {\n" + " exch /CharProcs get exch\n" + " 2 copy known not\n" + " {pop /.notdef} if\n" + " get exec\n" + "} bind def\n" + "/BuildChar {\n" + " 1 index /Encoding get exch get\n" + " 1 index /BuildGlyph get exec\n" + "} bind def\n" + "currentdict end\n"; + + const char *h41 = "(%s) cvn exch definefont pop\n"; + + + if (!((nGlyphs > 0) && (nGlyphs <= 256))) return SF_GLYPHNUM; + if (!glyphArray) return SF_BADARG; + if (!fname) fname = ttf->psname; + + fprintf(outf, h01, GetInt16(table, 0, 1), GetUInt16(table, 2, 1), GetInt16(table, 4, 1), GetUInt16(table, 6, 1)); + fprintf(outf, h02, modname, modver, modextra); + fprintf(outf, h09, ttf->psname); + + fprintf(outf, h10); + fprintf(outf, h11, fname); +/* fprintf(outf, h12, 4000000); */ + + /* XUID generation: + * 103 0 0 C1 C2 C3 C4 + * C1 - CRC-32 of the entire source TrueType font + * C2 - number of glyphs in the subset + * C3 - CRC-32 of the glyph array + * C4 - CRC-32 of the encoding array + * + * All CRC-32 numbers are presented as hexadecimal numbers + */ + + fprintf(outf, h17, rtl_crc32(0, ttf->ptr, ttf->fsize), nGlyphs, rtl_crc32(0, glyphArray, nGlyphs * 2), rtl_crc32(0, encoding, nGlyphs)); + fprintf(outf, h13); + fprintf(outf, h14, XUnits(UPEm, GetInt16(table, 36, 1)), XUnits(UPEm, GetInt16(table, 38, 1)), XUnits(UPEm, GetInt16(table, 40, 1)), XUnits(UPEm, GetInt16(table, 42, 1))); + fprintf(outf, h15); + + for (i = 0; i < nGlyphs; i++) { + fprintf(outf, h16, encoding[i], i); + } + + fprintf(outf, h30, nGlyphs+1); + fprintf(outf, h31); + fprintf(outf, h32); + + for (i = 0; i < nGlyphs; i++) { + fprintf(outf, h33, i); + r = GetTTGlyphOutline(ttf, glyphArray[i] < ttf->nglyphs ? glyphArray[i] : 0, &pa, &metrics, 0); + + if (r > 0) { + n = BSplineToPSPath(pa, r, &path); + } else { + n = 0; /* glyph might have zero contours but valid metrics ??? */ + path = 0; + if (r < 0) { /* glyph is not present in the font - pa array was not allocated, so no need to free it */ + continue; + } + } + fprintf(outf, "\t%d %d %d %d %d %d setcachedevice\n", + wmode == 0 ? XUnits(UPEm, metrics.aw) : 0, + wmode == 0 ? 0 : -XUnits(UPEm, metrics.ah), + XUnits(UPEm, metrics.xMin), + XUnits(UPEm, metrics.yMin), + XUnits(UPEm, metrics.xMax), + XUnits(UPEm, metrics.yMax)); + + for (j = 0; j < n; j++) + { + switch (path[j].type) + { + case PS_MOVETO: + fprintf(outf, "\t%d %d moveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1)); + break; + + case PS_LINETO: + fprintf(outf, "\t%d %d lineto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1)); + break; + + case PS_CURVETO: + fprintf(outf, "\t%d %d %d %d %d %d curveto\n", XUnits(UPEm, path[j].x1), XUnits(UPEm, path[j].y1), XUnits(UPEm, path[j].x2), XUnits(UPEm, path[j].y2), XUnits(UPEm, path[j].x3), XUnits(UPEm, path[j].y3)); + break; + + case PS_CLOSEPATH: + fprintf(outf, "\tclosepath\n"); + break; + case PS_NOOP: + break; + } + } + if (n > 0) fprintf(outf, "\tfill\n"); /* if glyph is not a whitespace character */ + + fprintf(outf, h34); + + free(pa); + free(path); + } + fprintf(outf, h35); + + fprintf(outf, h40); + fprintf(outf, h41, fname); + + return SF_OK; +} +#endif + +#ifndef NO_TTCR +int CreateTTFromTTGlyphs(TrueTypeFont *ttf, + const char *fname, + sal_uInt16 *glyphArray, + sal_uInt8 *encoding, + int nGlyphs, + int nNameRecs, + NameRecord *nr, + sal_uInt32 flags) +{ + TrueTypeCreator *ttcr; + TrueTypeTable *head=0, *hhea=0, *maxp=0, *cvt=0, *prep=0, *glyf=0, *fpgm=0, *cmap=0, *name=0, *post = 0, *os2 = 0; + sal_uInt8 *p; + int i; + int res; + + TrueTypeCreatorNewEmpty(T_true, &ttcr); + + /** name **/ + + if (flags & TTCF_AutoName) { + /* not implemented yet + NameRecord *names; + NameRecord newname; + int n = GetTTNameRecords(ttf, &names); + int n1 = 0, n2 = 0, n3 = 0, n4 = 0, n5 = 0, n6 = 0; + sal_uInt8 *cp1; + sal_uInt8 suffix[32]; + sal_uInt32 c1 = crc32(glyphArray, nGlyphs * 2); + sal_uInt32 c2 = crc32(encoding, nGlyphs); + int len; + snprintf(suffix, 31, "S%08X%08X-%d", c1, c2, nGlyphs); + + name = TrueTypeTableNew_name(0, 0); + for (i = 0; i < n; i++) { + if (names[i].platformID == 1 && names[i].encodingID == 0 && names[i].languageID == 0 && names[i].nameID == 1) { + + memcpy(newname, names+i, sizeof(NameRecord)); + newname.slen = name[i].slen + strlen(suffix); + */ + const sal_uInt8 ptr[] = {0,'T',0,'r',0,'u',0,'e',0,'T',0,'y',0,'p',0,'e',0,'S',0,'u',0,'b',0,'s',0,'e',0,'t'}; + NameRecord n1 = {1, 0, 0, 6, 14, (sal_uInt8*)"TrueTypeSubset"}; + NameRecord n2 = {3, 1, 1033, 6, 28, 0}; + n2.sptr = (sal_uInt8 *) ptr; + name = TrueTypeTableNew_name(0, 0); + nameAdd(name, &n1); + nameAdd(name, &n2); + } else { + if (nNameRecs == 0) { + NameRecord *names; + int n = GetTTNameRecords(ttf, &names); + name = TrueTypeTableNew_name(n, names); + DisposeNameRecords(names, n); + } else { + name = TrueTypeTableNew_name(nNameRecs, nr); + } + } + + /** maxp **/ + maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp)); + + /** hhea **/ + p = getTable(ttf, O_hhea); + if (p) { + hhea = TrueTypeTableNew_hhea(GetUInt16(p, 4, 1), GetUInt16(p, 6, 1), GetUInt16(p, 8, 1), GetUInt16(p, 18, 1), GetUInt16(p, 20, 1)); + } else { + hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0); + } + + /** head **/ + + p = getTable(ttf, O_head); + assert(p != 0); + head = TrueTypeTableNew_head(GetUInt32(p, 4, 1), + GetUInt16(p, 16, 1), + GetUInt16(p, 18, 1), + p+20, + GetUInt16(p, 44, 1), + GetUInt16(p, 46, 1), + GetInt16(p, 48, 1)); + + + /** glyf **/ + + glyf = TrueTypeTableNew_glyf(); + sal_uInt32* gID = (sal_uInt32*)scalloc(nGlyphs, sizeof(sal_uInt32)); + + for (i = 0; i < nGlyphs; i++) { + gID[i] = glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf); + } + + /** cmap **/ + cmap = TrueTypeTableNew_cmap(); + + for (i=0; i < nGlyphs; i++) { + cmapAdd(cmap, 0x010000, encoding[i], gID[i]); + } + + /** cvt **/ + if ((p = getTable(ttf, O_cvt)) != 0) { + cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p); + } + + /** prep **/ + if ((p = getTable(ttf, O_prep)) != 0) { + prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p); + } + + /** fpgm **/ + if ((p = getTable(ttf, O_fpgm)) != 0) { + fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p); + } + + /** post **/ + if ((p = getTable(ttf, O_post)) != 0) { + post = TrueTypeTableNew_post(0x00030000, + GetUInt32(p, 4, 1), + GetUInt16(p, 8, 1), + GetUInt16(p, 10, 1), + GetUInt16(p, 12, 1)); + } else { + post = TrueTypeTableNew_post(0x00030000, 0, 0, 0, 0); + } + + if (flags & TTCF_IncludeOS2) { + if ((p = getTable(ttf, O_OS2)) != 0) { + os2 = TrueTypeTableNew(T_OS2, getTableSize(ttf, O_OS2), p); + } + } + + AddTable(ttcr, name); AddTable(ttcr, maxp); AddTable(ttcr, hhea); + AddTable(ttcr, head); AddTable(ttcr, glyf); AddTable(ttcr, cmap); + AddTable(ttcr, cvt ); AddTable(ttcr, prep); AddTable(ttcr, fpgm); + AddTable(ttcr, post); AddTable(ttcr, os2); + + if ((res = StreamToFile(ttcr, fname)) != SF_OK) { +#if OSL_DEBUG_LEVEL > 1 + fprintf(stderr, "StreamToFile: error code: %d.\n", res); +#endif + } + + TrueTypeCreatorDispose(ttcr); + free(gID); + + return res; +} +#endif + + +#ifndef NO_TYPE42 +static GlyphOffsets *GlyphOffsetsNew(sal_uInt8 *sfntP) +{ + GlyphOffsets* res = (GlyphOffsets*)smalloc(sizeof(GlyphOffsets)); + sal_uInt8 *loca = NULL; + sal_uInt16 i, numTables = GetUInt16(sfntP, 4, 1); + sal_uInt32 locaLen = 0; + sal_Int16 indexToLocFormat = 0; + + for (i = 0; i < numTables; i++) { + sal_uInt32 tag = GetUInt32(sfntP + 12, 16 * i, 1); + sal_uInt32 off = GetUInt32(sfntP + 12, 16 * i + 8, 1); + sal_uInt32 len = GetUInt32(sfntP + 12, 16 * i + 12, 1); + + if (tag == T_loca) { + loca = sfntP + off; + locaLen = len; + } else if (tag == T_head) { + indexToLocFormat = GetInt16(sfntP + off, 50, 1); + } + } + + res->nGlyphs = locaLen / ((indexToLocFormat == 1) ? 4 : 2); + assert(res->nGlyphs != 0); + res->offs = (sal_uInt32*)scalloc(res->nGlyphs, sizeof(sal_uInt32)); + + for (i = 0; i < res->nGlyphs; i++) { + if (indexToLocFormat == 1) { + res->offs[i] = GetUInt32(loca, i * 4, 1); + } else { + res->offs[i] = GetUInt16(loca, i * 2, 1) << 1; + } + } + return res; +} + +static void GlyphOffsetsDispose(GlyphOffsets *_this) +{ + if (_this) { + free(_this->offs); + free(_this); + } +} + +static void DumpSfnts(FILE *outf, sal_uInt8 *sfntP) +{ + HexFmt *h = HexFmtNew(outf); + sal_uInt16 i, numTables = GetUInt16(sfntP, 4, 1); + GlyphOffsets *go = GlyphOffsetsNew(sfntP); + sal_uInt8 pad[] = {0,0,0,0}; /* zeroes */ + + assert(numTables <= 9); /* Type42 has 9 required tables */ + + sal_uInt32* offs = (sal_uInt32*)scalloc(numTables, sizeof(sal_uInt32)); +// sal_uInt32* lens = (sal_uInt32*)scalloc(numTables, sizeof(sal_uInt32)); + + fputs("/sfnts [", outf); + HexFmtOpenString(h); + HexFmtBlockWrite(h, sfntP, 12); /* stream out the Offset Table */ + HexFmtBlockWrite(h, sfntP+12, 16 * numTables); /* stream out the Table Directory */ + + for (i=0; inGlyphs - 1; j++) { + o = go->offs[j]; + l = go->offs[j + 1] - o; + HexFmtBlockWrite(h, glyf + o, l); + } + } + HexFmtBlockWrite(h, pad, (4 - (len & 3)) & 3); + } + HexFmtCloseString(h); + fputs("] def\n", outf); + GlyphOffsetsDispose(go); + HexFmtDispose(h); + free(offs); +// free(lens); +} + +int CreateT42FromTTGlyphs(TrueTypeFont *ttf, + FILE *outf, + const char *psname, + sal_uInt16 *glyphArray, + sal_uInt8 *encoding, + int nGlyphs) +{ + TrueTypeCreator *ttcr; + TrueTypeTable *head=0, *hhea=0, *maxp=0, *cvt=0, *prep=0, *glyf=0, *fpgm=0; + sal_uInt8 *p; + int i; + int res; + + sal_uInt32 ver, rev; + sal_uInt8 *headP; + + sal_uInt8 *sfntP; + sal_uInt32 sfntLen; + int UPEm = ttf->unitsPerEm; + + if (nGlyphs >= 256) return SF_GLYPHNUM; + + assert(psname != 0); + + TrueTypeCreatorNewEmpty(T_true, &ttcr); + + /* head */ + headP = p = getTable(ttf, O_head); + assert(p != 0); + head = TrueTypeTableNew_head(GetUInt32(p, 4, 1), GetUInt16(p, 16, 1), GetUInt16(p, 18, 1), p+20, GetUInt16(p, 44, 1), GetUInt16(p, 46, 1), GetInt16(p, 48, 1)); + ver = GetUInt32(p, 0, 1); + rev = GetUInt32(p, 4, 1); + + /** hhea **/ + p = getTable(ttf, O_hhea); + if (p) { + hhea = TrueTypeTableNew_hhea(GetUInt16(p, 4, 1), GetUInt16(p, 6, 1), GetUInt16(p, 8, 1), GetUInt16(p, 18, 1), GetUInt16(p, 20, 1)); + } else { + hhea = TrueTypeTableNew_hhea(0, 0, 0, 0, 0); + } + + /** maxp **/ + maxp = TrueTypeTableNew_maxp(getTable(ttf, O_maxp), getTableSize(ttf, O_maxp)); + + /** cvt **/ + if ((p = getTable(ttf, O_cvt)) != 0) { + cvt = TrueTypeTableNew(T_cvt, getTableSize(ttf, O_cvt), p); + } + + /** prep **/ + if ((p = getTable(ttf, O_prep)) != 0) { + prep = TrueTypeTableNew(T_prep, getTableSize(ttf, O_prep), p); + } + + /** fpgm **/ + if ((p = getTable(ttf, O_fpgm)) != 0) { + fpgm = TrueTypeTableNew(T_fpgm, getTableSize(ttf, O_fpgm), p); + } + + /** glyf **/ + glyf = TrueTypeTableNew_glyf(); + sal_uInt16* gID = (sal_uInt16*)scalloc(nGlyphs, sizeof(sal_uInt32)); + + for (i = 0; i < nGlyphs; i++) { + gID[i] = (sal_uInt16)glyfAdd(glyf, GetTTRawGlyphData(ttf, glyphArray[i]), ttf); + } + + AddTable(ttcr, head); AddTable(ttcr, hhea); AddTable(ttcr, maxp); AddTable(ttcr, cvt); + AddTable(ttcr, prep); AddTable(ttcr, glyf); AddTable(ttcr, fpgm); + + if ((res = StreamToMemory(ttcr, &sfntP, &sfntLen)) != SF_OK) { + TrueTypeCreatorDispose(ttcr); + free(gID); + return res; + } + + fprintf(outf, "%%!PS-TrueTypeFont-%d.%d-%d.%d\n", (int)(ver>>16), (int)(ver & 0xFFFF), (int)(rev>>16), (int)(rev & 0xFFFF)); + fprintf(outf, "%%%%Creator: %s %s %s\n", modname, modver, modextra); + fprintf(outf, "%%- Font subset generated from a source font file: '%s'\n", ttf->fname); + fprintf(outf, "%%- Original font name: %s\n", ttf->psname); + fprintf(outf, "%%- Original font family: %s\n", ttf->family); + fprintf(outf, "%%- Original font sub-family: %s\n", ttf->subfamily); + fprintf(outf, "11 dict begin\n"); + fprintf(outf, "/FontName (%s) cvn def\n", psname); + fprintf(outf, "/PaintType 0 def\n"); + fprintf(outf, "/FontMatrix [1 0 0 1 0 0] def\n"); + fprintf(outf, "/FontBBox [%d %d %d %d] def\n", XUnits(UPEm, GetInt16(headP, 36, 1)), XUnits(UPEm, GetInt16(headP, 38, 1)), XUnits(UPEm, GetInt16(headP, 40, 1)), XUnits(UPEm, GetInt16(headP, 42, 1))); + fprintf(outf, "/FontType 42 def\n"); + fprintf(outf, "/Encoding 256 array def\n"); + fprintf(outf, " 0 1 255 {Encoding exch /.notdef put} for\n"); + + for (i = 1; iptr, ttf->fsize), (unsigned int)nGlyphs, (unsigned int)rtl_crc32(0, glyphArray, nGlyphs * 2), (unsigned int)rtl_crc32(0, encoding, nGlyphs)); + + DumpSfnts(outf, sfntP); + + /* dump charstrings */ + fprintf(outf, "/CharStrings %d dict dup begin\n", nGlyphs); + fprintf(outf, "/.notdef 0 def\n"); + for (i = 1; i < (int)glyfCount(glyf); i++) { + fprintf(outf,"/glyph%d %d def\n", i, i); + } + fprintf(outf, "end readonly def\n"); + + fprintf(outf, "FontName currentdict end definefont pop\n"); + TrueTypeCreatorDispose(ttcr); + free(gID); + free(sfntP); + return SF_OK; +} +#endif + + +#ifndef NO_MAPPERS +int MapString(TrueTypeFont *ttf, sal_uInt16 *str, int nchars, sal_uInt16 *glyphArray, int bvertical) +{ + int i; + sal_uInt16 *cp; + + if (ttf->cmapType == CMAP_NOT_USABLE ) return -1; + if (!nchars) return 0; + + if (glyphArray == 0) { + cp = str; + } else { + cp = glyphArray; + } + + switch (ttf->cmapType) { + case CMAP_MS_Symbol: + if( ttf->mapper == getGlyph0 ) { + sal_uInt16 aChar; + for( i = 0; i < nchars; i++ ) { + aChar = str[i]; + if( ( aChar & 0xf000 ) == 0xf000 ) + aChar &= 0x00ff; + cp[i] = aChar; + } + } + else if( glyphArray ) + memcpy(glyphArray, str, nchars * 2); + break; + + case CMAP_MS_Unicode: + if (glyphArray != 0) { + memcpy(glyphArray, str, nchars * 2); + } + break; + + case CMAP_MS_ShiftJIS: TranslateString12(str, cp, nchars); break; + case CMAP_MS_Big5: TranslateString13(str, cp, nchars); break; + case CMAP_MS_PRC: TranslateString14(str, cp, nchars); break; + case CMAP_MS_Wansung: TranslateString15(str, cp, nchars); break; + case CMAP_MS_Johab: TranslateString16(str, cp, nchars); break; + } + + for (i = 0; i < nchars; i++) { + cp[i] = (sal_uInt16)ttf->mapper(ttf->cmap, cp[i]); + if (cp[i]!=0 && bvertical!=0) + cp[i] = (sal_uInt16)UseGSUB(ttf,cp[i],bvertical); + } + return nchars; +} + +sal_uInt16 MapChar(TrueTypeFont *ttf, sal_uInt16 ch, int bvertical) +{ + switch (ttf->cmapType) { + case CMAP_MS_Symbol: + + if( ttf->mapper == getGlyph0 && ( ch & 0xf000 ) == 0xf000 ) + ch &= 0x00ff; + return (sal_uInt16)ttf->mapper(ttf->cmap, ch ); + + case CMAP_MS_Unicode: break; + case CMAP_MS_ShiftJIS: ch = TranslateChar12(ch); break; + case CMAP_MS_Big5: ch = TranslateChar13(ch); break; + case CMAP_MS_PRC: ch = TranslateChar14(ch); break; + case CMAP_MS_Wansung: ch = TranslateChar15(ch); break; + case CMAP_MS_Johab: ch = TranslateChar16(ch); break; + default: return 0; + } + ch = (sal_uInt16)ttf->mapper(ttf->cmap, ch); + if (ch!=0 && bvertical!=0) + ch = (sal_uInt16)UseGSUB(ttf,ch,bvertical); + return ch; +} + +int DoesVerticalSubstitution( TrueTypeFont *ttf, int bvertical) +{ + int nRet = 0; + if( bvertical) + nRet = HasVerticalGSUB( ttf); + return nRet; +} + +#endif + +int GetTTGlyphCount( TrueTypeFont* ttf ) +{ + return ttf->nglyphs; +} + +TTSimpleGlyphMetrics *GetTTSimpleGlyphMetrics(TrueTypeFont *ttf, sal_uInt16 *glyphArray, int nGlyphs, int mode) +{ + sal_uInt8* pTable; + int i; + sal_uInt16 glyphID; + sal_uInt32 n; + int UPEm = ttf->unitsPerEm; + int nTableSize; + + if (mode == 0) { + n = ttf->numberOfHMetrics; + pTable = getTable( ttf, O_hmtx ); + nTableSize = getTableSize( ttf, O_hmtx ); + } else { + n = ttf->numOfLongVerMetrics; + pTable = getTable( ttf, O_vmtx ); + nTableSize = getTableSize( ttf, O_vmtx ); + } + + if (!nGlyphs || !glyphArray) return 0; /* invalid parameters */ + if (!n || !pTable) return 0; /* the font does not contain the requested metrics */ + + TTSimpleGlyphMetrics* res = (TTSimpleGlyphMetrics*)calloc(nGlyphs, sizeof(TTSimpleGlyphMetrics)); + assert(res != 0); + + for (i=0; inglyphs ) + nLsbOffset = 4 * n + 2 * (glyphID - n); + else /* font is broken -> use lsb of last hmetrics */ + nLsbOffset = nAdvOffset + 2; + } + + if( nAdvOffset >= nTableSize) + res[i].adv = 0; /* better than a crash for buggy fonts */ + else + res[i].adv = static_cast( + XUnits( UPEm, GetUInt16( pTable, nAdvOffset, 1) ) ); + + if( nLsbOffset >= nTableSize) + res[i].sb = 0; /* better than a crash for buggy fonts */ + else + res[i].sb = static_cast( + XUnits( UPEm, GetInt16( pTable, nLsbOffset, 1) ) ); + } + + return res; +} + +#ifndef NO_MAPPERS +TTSimpleGlyphMetrics *GetTTSimpleCharMetrics(TrueTypeFont * ttf, sal_uInt16 firstChar, int nChars, int mode) +{ + TTSimpleGlyphMetrics *res = 0; + int i, n; + + sal_uInt16* str = (sal_uInt16*)malloc(nChars * 2); + assert(str != 0); + + for (i=0; iunitsPerEm; + + memset(info, 0, sizeof(TTGlobalFontInfo)); + + info->family = ttf->family; + info->ufamily = ttf->ufamily; + info->subfamily = ttf->subfamily; + info->usubfamily = ttf->usubfamily; + info->psname = ttf->psname; + info->symbolEncoded = (ttf->cmapType == CMAP_MS_Symbol); + + table = getTable(ttf, O_OS2); + if (table) { + info->weight = GetUInt16(table, 4, 1); + info->width = GetUInt16(table, 6, 1); + + /* There are 3 different versions of OS/2 table: original (68 bytes long), + * Microsoft old (78 bytes long) and Microsoft new (86 bytes long,) + * Apple's documentation recommends looking at the table length. + */ + if (getTableSize(ttf, O_OS2) > 68) { + info->typoAscender = XUnits(UPEm,GetInt16(table, 68, 1)); + info->typoDescender = XUnits(UPEm, GetInt16(table, 70, 1)); + info->typoLineGap = XUnits(UPEm, GetInt16(table, 72, 1)); + info->winAscent = XUnits(UPEm, GetUInt16(table, 74, 1)); + info->winDescent = XUnits(UPEm, GetUInt16(table, 76, 1)); + /* sanity check; some fonts treat winDescent as signed + * violating the standard */ + if( info->winDescent > 5*UPEm ) + info->winDescent = XUnits(UPEm, GetInt16(table, 76,1)); + } + if (ttf->cmapType == CMAP_MS_Unicode) { + info->rangeFlag = 1; + info->ur1 = GetUInt32(table, 42, 1); + info->ur2 = GetUInt32(table, 46, 1); + info->ur3 = GetUInt32(table, 50, 1); + info->ur4 = GetUInt32(table, 54, 1); + } + memcpy(info->panose, table + 32, 10); + info->typeFlags = GetUInt16( table, 8, 1 ); + } + + table = getTable(ttf, O_post); + if (table) { + info->pitch = GetUInt32(table, 12, 1); + info->italicAngle = GetInt32(table, 4, 1); + } + + table = getTable(ttf, O_head); /* 'head' tables is always there */ + info->xMin = XUnits(UPEm, GetInt16(table, 36, 1)); + info->yMin = XUnits(UPEm, GetInt16(table, 38, 1)); + info->xMax = XUnits(UPEm, GetInt16(table, 40, 1)); + info->yMax = XUnits(UPEm, GetInt16(table, 42, 1)); + info->macStyle = GetInt16(table, 44, 1); + + table = getTable(ttf, O_hhea); + if (table) { + info->ascender = XUnits(UPEm, GetInt16(table, 4, 1)); + info->descender = XUnits(UPEm, GetInt16(table, 6, 1)); + info->linegap = XUnits(UPEm, GetInt16(table, 8, 1)); + } + + table = getTable(ttf, O_vhea); + if (table) { + info->vascent = XUnits(UPEm, GetInt16(table, 4, 1)); + info->vdescent = XUnits(UPEm, GetInt16(table, 6, 1)); + } +} + +#ifdef TEST5 +void KernGlyphs(TrueTypeFont *ttf, sal_uInt16 *glyphs, int nglyphs, int wmode, KernData *kern) +{ + int i; + + if (!nglyphs || !glyphs || !kern) return; + + for (i = 0; i < nglyphs-1; i++) kern[i].x = kern[i].y = 0; + + switch (ttf->kerntype) { + case KT_APPLE_NEW: KernGlyphsPrim1(ttf, glyphs, nglyphs, wmode, kern); return; + case KT_MICROSOFT: KernGlyphsPrim2(ttf, glyphs, nglyphs, wmode, kern); return; + default: return; + } +} +#endif + +GlyphData *GetTTRawGlyphData(TrueTypeFont *ttf, sal_uInt32 glyphID) +{ + sal_uInt8 *glyf = getTable(ttf, O_glyf); + sal_uInt8 *hmtx = getTable(ttf, O_hmtx); + sal_uInt32 length; + ControlPoint *cp; + int i, n, m; + + if( glyphID >= ttf->nglyphs ) + return 0; + + /* #127161# check the glyph offsets */ + length = getTableSize( ttf, O_glyf ); + if( length < ttf->goffsets[ glyphID+1 ] ) + return 0; + + length = ttf->goffsets[glyphID+1] - ttf->goffsets[glyphID]; + + GlyphData* d = (GlyphData*)malloc(sizeof(GlyphData)); assert(d != 0); + + if (length > 0) { + sal_uInt8 *srcptr = glyf + ttf->goffsets[glyphID]; + d->ptr = (sal_uInt8*)malloc((length + 1) & ~1); assert(d->ptr != 0); + memcpy( d->ptr, srcptr, length ); + d->compflag = (GetInt16( srcptr, 0, 1 ) < 0); + } else { + d->ptr = 0; + d->compflag = 0; + } + + d->glyphID = glyphID; + d->nbytes = (sal_uInt16)((length + 1) & ~1); + + /* now calculate npoints and ncontours */ + n = GetTTGlyphPoints(ttf, glyphID, &cp); + if (n != -1) { + m = 0; + for (i = 0; i < n; i++) { + if (cp[i].flags & 0x8000) m++; + } + d->npoints = (sal_uInt16)n; + d->ncontours = (sal_uInt16)m; + free(cp); + } else { + d->npoints = 0; + d->ncontours = 0; + } + + /* get advance width and left sidebearing */ + if (glyphID < ttf->numberOfHMetrics) { + d->aw = GetUInt16(hmtx, 4 * glyphID, 1); + d->lsb = GetInt16(hmtx, 4 * glyphID + 2, 1); + } else { + d->aw = GetUInt16(hmtx, 4 * (ttf->numberOfHMetrics - 1), 1); + d->lsb = GetInt16(hmtx + ttf->numberOfHMetrics * 4, (glyphID - ttf->numberOfHMetrics) * 2, 1); + } + + return d; +} + +int GetTTNameRecords(TrueTypeFont *ttf, NameRecord **nr) +{ + sal_uInt8 *table = getTable(ttf, O_name); + int nTableSize = getTableSize(ttf, O_name ); + sal_uInt16 n = GetUInt16(table, 2, 1); + sal_uInt8* rec_string = NULL; + int nStrBase = GetUInt16(table, 4, 1); + NameRecord *rec; + int i; + + *nr = 0; + if (n == 0) return 0; + + rec = (NameRecord*)calloc(n, sizeof(NameRecord)); + + for (i = 0; i < n; i++) { + int nStrOffset = GetUInt16(table + 6, 10 + 12 * i, 1); + rec[i].platformID = GetUInt16(table + 6, 12 * i, 1); + rec[i].encodingID = GetUInt16(table + 6, 2 + 12 * i, 1); + rec[i].languageID = GetUInt16(table + 6, 4 + 12 * i, 1); + rec[i].nameID = GetUInt16(table + 6, 6 + 12 * i, 1); + rec[i].slen = GetUInt16(table + 6, 8 + 12 * i, 1); + if (rec[i].slen) { + if( nStrBase+nStrOffset+rec[i].slen >= nTableSize ) { + rec[i].sptr = 0; + rec[i].slen = 0; + continue; + } + + rec_string = table + nStrBase + nStrOffset; + // sanity check + if( rec_string > (sal_uInt8*)ttf->ptr && rec_string < ((sal_uInt8*)ttf->ptr + ttf->fsize - rec[i].slen ) ) + { + rec[i].sptr = (sal_uInt8 *) malloc(rec[i].slen); assert(rec[i].sptr != 0); + memcpy(rec[i].sptr, rec_string, rec[i].slen); + } + else + { +#ifdef DEBUG + fprintf( stderr, "found invalid name record %d with name id %d for file %s\n", + i, rec[i].nameID, ttf->fname ); +#endif + rec[i].sptr = 0; + rec[i].slen = 0; + } + } else { + rec[i].sptr = 0; + } + // some fonts have 3.0 names => fix them to 3.1 + if( (rec[i].platformID == 3) && (rec[i].encodingID == 0) ) + rec[i].encodingID = 1; + } + + *nr = rec; + return n; +} + +void DisposeNameRecords(NameRecord* nr, int n) +{ + int i; + for (i = 0; i < n; i++) { + if (nr[i].sptr) free(nr[i].sptr); + } + free(nr); +} + +} // namespace vcl + + +#ifdef TEST1 +/* This example creates a subset of a TrueType font with two encoded characters */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int r; + + /* Array of Unicode source characters */ + sal_uInt16 chars[2]; + + /* Encoding vector maps character encoding to the ordinal number + * of the glyph in the output file */ + sal_uInt8 encoding[2]; + + /* This array is for glyph IDs that source characters map to */ + sal_uInt16 g[2]; + + + if (ac < 2) return 0; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + + /* We want to create the output file that only contains two Unicode characters: + * L'a' and L'A' */ + + chars[0] = L'a'; + chars[1] = L'A'; + + /* Figure out what glyphs do these characters map in our font */ + MapString(fnt, chars, 2, g); + + /* Encode the characters. Value of encoding[i] is the number 0..255 which maps to glyph i of the + * newly generated font */ + encoding[0] = chars[0]; + encoding[1] = chars[1]; + + + /* Generate a subset */ + CreateT3FromTTGlyphs(fnt, stdout, 0, g, encoding, 2, 0); + + /* Now call the dtor for the font */ + CloseTTFont(fnt); + return 0; +} +#endif + +#ifdef TEST2 +/* This example extracts first 224 glyphs from a TT fonts and encodes them starting at 32 */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int i, r; + + /* Array of Unicode source characters */ + sal_uInt16 glyphs[224]; + + /* Encoding vector maps character encoding to the ordinal number + * of the glyph in the output file */ + sal_uInt8 encoding[224]; + + + + for (i=0; i<224; i++) { + glyphs[i] = i; + encoding[i] = 32 + i; + } + + if (ac < 2) return 0; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + + /* Encode the characters. Value of encoding[i] is the number 0..255 which maps to glyph i of the + * newly generated font */ + + /* Generate a subset */ + CreateT3FromTTGlyphs(fnt, stdout, 0, glyphs, encoding, 224, 0); + + /* Now call the dtor for the font */ + CloseTTFont(fnt); + return 0; +} +#endif + +#ifdef TEST3 +/* Glyph metrics example */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int i, r; + sal_uInt16 glyphs[224]; + TTSimpleGlyphMetrics *m; + + for (i=0; i<224; i++) { + glyphs[i] = i; + } + + if (ac < 2) return 0; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + if ((m = GetTTSimpleGlyphMetrics(fnt, glyphs, 224, 0)) == 0) { + printf("Requested metrics is not available\n"); + } else { + for (i=0; i<224; i++) { + printf("%d. advWid: %5d, LSBear: %5d\n", i, m[i].adv, m[i].sb); + } + } + + /* Now call the dtor for the font */ + free(m); + CloseTTFont(fnt); + return 0; +} +#endif + +#ifdef TEST4 +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + TTGlobalFontInfo info; + int i, r; + + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + printf("Font file: %s\n", av[1]); + +#ifdef PRINT_KERN + switch (fnt->kerntype) { + case KT_MICROSOFT: + printf("\tkern: MICROSOFT, ntables: %d.", fnt->nkern); + if (fnt->nkern) { + printf(" ["); + for (i=0; inkern; i++) { + printf("%04X ", GetUInt16(fnt->kerntables[i], 4, 1)); + } + printf("]"); + } + printf("\n"); + break; + + case KT_APPLE_NEW: + printf("\tkern: APPLE_NEW, ntables: %d.", fnt->nkern); + if (fnt->nkern) { + printf(" ["); + for (i=0; inkern; i++) { + printf("%04X ", GetUInt16(fnt->kerntables[i], 4, 1)); + } + printf("]"); + } + printf("\n"); + break; + + case KT_NONE: + printf("\tkern: none.\n"); + break; + + default: + printf("\tkern: unrecoginzed.\n"); + break; + } + printf("\n"); +#endif + + GetTTGlobalFontInfo(fnt, &info); + printf("\tfamily name: `%s`\n", info.family); + printf("\tsubfamily name: `%s`\n", info.subfamily); + printf("\tpostscript name: `%s`\n", info.psname); + printf("\tweight: %d\n", info.weight); + printf("\twidth: %d\n", info.width); + printf("\tpitch: %d\n", info.pitch); + printf("\titalic angle: %d\n", info.italicAngle); + printf("\tbouding box: [%d %d %d %d]\n", info.xMin, info.yMin, info.xMax, info.yMax); + printf("\tascender: %d\n", info.ascender); + printf("\tdescender: %d\n", info.descender); + printf("\tlinegap: %d\n", info.linegap); + printf("\tvascent: %d\n", info.vascent); + printf("\tvdescent: %d\n", info.vdescent); + printf("\ttypoAscender: %d\n", info.typoAscender); + printf("\ttypoDescender: %d\n", info.typoDescender); + printf("\ttypoLineGap: %d\n", info.typoLineGap); + printf("\twinAscent: %d\n", info.winAscent); + printf("\twinDescent: %d\n", info.winDescent); + printf("\tUnicode ranges:\n"); + for (i = 0; i < 32; i++) { + if ((info.ur1 >> i) & 1) { + printf("\t\t\t%s\n", UnicodeRangeName(i)); + } + } + for (i = 0; i < 32; i++) { + if ((info.ur2 >> i) & 1) { + printf("\t\t\t%s\n", UnicodeRangeName(i+32)); + } + } + for (i = 0; i < 32; i++) { + if ((info.ur3 >> i) & 1) { + printf("\t\t\t%s\n", UnicodeRangeName(i+64)); + } + } + for (i = 0; i < 32; i++) { + if ((info.ur4 >> i) & 1) { + printf("\t\t\t%s\n", UnicodeRangeName(i+96)); + } + } + + CloseTTFont(fnt); + return 0; +} +#endif + +#ifdef TEST5 +/* Kerning example */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + sal_uInt16 g[224]; + KernData d[223]; + int r, i, k = 0; + + g[k++] = 11; + g[k++] = 36; + g[k++] = 11; + g[k++] = 98; + g[k++] = 11; + g[k++] = 144; + g[k++] = 41; + g[k++] = 171; + g[k++] = 51; + g[k++] = 15; + + if (ac < 2) return 0; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + KernGlyphs(fnt, g, k, 0, d); + + for (i = 0; i < k-1; i++) { + printf("%3d %3d: [%3d %3d]\n", g[i], g[i+1], d[i].x, d[i].y); + } + + CloseTTFont(fnt); + return 0; +} +#endif + + + +#ifdef TEST6 +/* This example extracts a single glyph from a font */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int r, i; + + sal_uInt16 glyphs[256]; + sal_uInt8 encoding[256]; + + for (i=0; i<256; i++) { + glyphs[i] = 512 + i; + encoding[i] = i; + } + +#if 0 + i=0; + glyphs[i++] = 2001; + glyphs[i++] = 2002; + glyphs[i++] = 2003; + glyphs[i++] = 2004; + glyphs[i++] = 2005; + glyphs[i++] = 2006; + glyphs[i++] = 2007; + glyphs[i++] = 2008; + glyphs[i++] = 2009; + glyphs[i++] = 2010; + glyphs[i++] = 2011; + glyphs[i++] = 2012; + glyphs[i++] = 2013; + glyphs[i++] = 2014; + glyphs[i++] = 2015; + glyphs[i++] = 2016; + glyphs[i++] = 2017; + glyphs[i++] = 2018; + glyphs[i++] = 2019; + glyphs[i++] = 2020; + + + r = 97; + i = 0; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; + encoding[i++] = r++; +#endif + + if (ac < 2) return 0; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + /* Generate a subset */ + CreateT3FromTTGlyphs(fnt, stdout, 0, glyphs, encoding, 256, 0); + + fprintf(stderr, "UnitsPerEm: %d.\n", fnt->unitsPerEm); + + /* Now call the dtor for the font */ + CloseTTFont(fnt); + return 0; +} +#endif + +#ifdef TEST7 +/* NameRecord extraction example */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int r, i, j, n; + NameRecord *nr; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + if ((n = GetTTNameRecords(fnt, &nr)) == 0) { + fprintf(stderr, "No name records in the font.\n"); + return 0; + } + + printf("Number of name records: %d.\n", n); + for (i = 0; i < n; i++) { + printf("%d %d %04X %d [", nr[i].platformID, nr[i].encodingID, nr[i].languageID, nr[i].nameID); + for (j=0; j TrueType subsetting */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + sal_uInt16 glyphArray[] = { 0, 98, 99, 22, 24, 25, 26, 27, 28, 29, 30, 31, 1270, 1289, 34}; + sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; + int r; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + CreateTTFromTTGlyphs(fnt, "subfont.ttf", glyphArray, encoding, 15, 0, 0, TTCF_AutoName | TTCF_IncludeOS2); + + + CloseTTFont(fnt); + + return 0; +} +#endif + +#ifdef TEST9 +/* TrueType -> Type42 subsetting */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + /* + sal_uInt16 glyphArray[] = { 0, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34}; + sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; + */ + sal_uInt16 glyphArray[] = { 0, 6711, 6724, 11133, 11144, 14360, 26, 27, 28, 29, 30, 31, 1270, 1289, 34}; + sal_uInt8 encoding[] = {32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}; + int r; + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + CreateT42FromTTGlyphs(fnt, stdout, "testfont", glyphArray, encoding, 15); + + CloseTTFont(fnt); + + return 0; +} +#endif + +#ifdef TEST10 +/* Component glyph test */ +int main(int ac, char **av) +{ + TrueTypeFont *fnt; + int r, i; + list glyphlist = listNewEmpty(); + + + if ((r = OpenTTFont(av[1], 0, &fnt)) != SF_OK) { + fprintf(stderr, "Error %d opening font file: `%s`.\n", r, av[1]); + return 0; + } + + for (i = 0; i < fnt->nglyphs; i++) { + r = GetTTGlyphComponents(fnt, i, glyphlist); + if (r > 1) { + printf("%d -> ", i); + listToFirst(glyphlist); + do { + printf("%d ", (int) listCurrent(glyphlist)); + } while (listNext(glyphlist)); + printf("\n"); + } else { + printf("%d: single glyph.\n", i); + } + listClear(glyphlist); + } + + CloseTTFont(fnt); + listDispose(glyphlist); + + return 0; +} +#endif + + diff --git a/vcl/source/fontsubset/ttcr.c b/vcl/source/fontsubset/ttcr.c deleted file mode 100644 index e8c9d8cf74e0..000000000000 --- a/vcl/source/fontsubset/ttcr.c +++ /dev/null @@ -1,1669 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ttcr.c,v $ - * $Revision: 1.11 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: ttcr.c,v 1.11 2008-04-11 10:16:51 rt Exp $ */ - -/* - * TrueTypeCreator method implementation - * - * @author: Alexander Gelfenbain - * - */ - -#include -#include -#include - -#if OSL_DEBUG_LEVEL == 0 -# ifndef NDEBUG -# define NDEBUG -# endif -#endif -#include - -#include "ttcr.h" - -/* These must be #defined so that they can be used in initializers */ -#define T_maxp 0x6D617870 -#define T_glyf 0x676C7966 -#define T_head 0x68656164 -#define T_loca 0x6C6F6361 -#define T_name 0x6E616D65 -#define T_hhea 0x68686561 -#define T_hmtx 0x686D7478 -#define T_cmap 0x636D6170 -#define T_vhea 0x76686561 -#define T_vmtx 0x766D7478 -#define T_OS2 0x4F532F32 -#define T_post 0x706F7374 -#define T_kern 0x6B65726E -#define T_cvt 0x63767420 - -typedef struct { - sal_uInt32 tag; - sal_uInt32 length; - sal_uInt8 *data; -} TableEntry; - -/* - * this is a duplicate code from sft.c but it is left here for performance reasons - */ -#ifdef __GNUC__ -#define _inline static __inline__ -#else -#define _inline static -#endif - -_inline sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) { - return (a << 24) | (b << 16) | (c << 8) | d; -} - -/*- Data access macros for data stored in big-endian or little-endian format */ -_inline sal_Int16 GetInt16(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - sal_Int16 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; - } else { - t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_uInt16 GetUInt16(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - sal_uInt16 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; - } else { - t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_Int32 GetInt32(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - sal_Int32 t; - assert(ptr != 0); - - if (bigendian) { - t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | - (ptr+offset)[2] << 8 | (ptr+offset)[3]; - } else { - t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | - (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - -_inline sal_uInt32 GetUInt32(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - sal_uInt32 t; - assert(ptr != 0); - - - if (bigendian) { - t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | - (ptr+offset)[2] << 8 | (ptr+offset)[3]; - } else { - t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | - (ptr+offset)[1] << 8 | (ptr+offset)[0]; - } - - return t; -} - - -_inline void PutInt16(sal_Int16 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - assert(ptr != 0); - - if (bigendian) { - ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset+1] = (sal_uInt8)(val & 0xFF); - } else { - ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset] = (sal_uInt8)(val & 0xFF); - } - -} - -_inline void PutUInt16(sal_uInt16 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - assert(ptr != 0); - - if (bigendian) { - ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset+1] = (sal_uInt8)(val & 0xFF); - } else { - ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset] = (sal_uInt8)(val & 0xFF); - } - -} - - -_inline void PutUInt32(sal_uInt32 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - assert(ptr != 0); - - if (bigendian) { - ptr[offset] = (sal_uInt8)((val >> 24) & 0xFF); - ptr[offset+1] = (sal_uInt8)((val >> 16) & 0xFF); - ptr[offset+2] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset+3] = (sal_uInt8)(val & 0xFF); - } else { - ptr[offset+3] = (sal_uInt8)((val >> 24) & 0xFF); - ptr[offset+2] = (sal_uInt8)((val >> 16) & 0xFF); - ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset] = (sal_uInt8)(val & 0xFF); - } - -} - - -_inline void PutInt32(sal_Int32 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) -{ - assert(ptr != 0); - - if (bigendian) { - ptr[offset] = (sal_uInt8)((val >> 24) & 0xFF); - ptr[offset+1] = (sal_uInt8)((val >> 16) & 0xFF); - ptr[offset+2] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset+3] = (sal_uInt8)(val & 0xFF); - } else { - ptr[offset+3] = (sal_uInt8)((val >> 24) & 0xFF); - ptr[offset+2] = (sal_uInt8)((val >> 16) & 0xFF); - ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); - ptr[offset] = (sal_uInt8)(val & 0xFF); - } - -} - -static int TableEntryCompareF(const void *l, const void *r) -{ - return ((const TableEntry *) l)->tag - ((const TableEntry *) r)->tag; -} - -static int NameRecordCompareF(const void *l, const void *r) -{ - NameRecord *ll = (NameRecord *) l; - NameRecord *rr = (NameRecord *) r; - - if (ll->platformID != rr->platformID) { - return ll->platformID - rr->platformID; - } else if (ll->encodingID != rr->encodingID) { - return ll->encodingID - rr->encodingID; - } else if (ll->languageID != rr->languageID) { - return ll->languageID - rr->languageID; - } else if (ll->nameID != rr->nameID) { - return ll->nameID - rr->nameID; - } - return 0; -} - - -static sal_uInt32 CheckSum(sal_uInt32 *ptr, sal_uInt32 length) -{ - sal_uInt32 sum = 0; - sal_uInt32 *endptr = ptr + ((length + 3) & (sal_uInt32) ~3) / 4; - - while (ptr < endptr) sum += *ptr++; - - return sum; -} - -_inline void *smalloc(sal_uInt32 size) -{ - void *res = malloc(size); - assert(res != 0); - return res; -} - -_inline void *scalloc(sal_uInt32 n, sal_uInt32 size) -{ - void *res = calloc(n, size); - assert(res != 0); - return res; -} - -/* - * Public functions - */ - -void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this) -{ - TrueTypeCreator *ptr = smalloc(sizeof(TrueTypeCreator)); - - ptr->tables = listNewEmpty(); - listSetElementDtor(ptr->tables, (void(*)(void*))TrueTypeTableDispose); - - ptr->tag = tag; - - *_this = ptr; -} - -void TrueTypeCreatorDispose(TrueTypeCreator *_this) -{ - listDispose(_this->tables); - free(_this); -} - -int AddTable(TrueTypeCreator *_this, TrueTypeTable *table) -{ - if (table != 0) { - listAppend(_this->tables, table); - } - return SF_OK; -} - -void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag) -{ - int done = 0; - - if (listCount(_this->tables)) { - listToFirst(_this->tables); - do { - if (((TrueTypeTable *) listCurrent(_this->tables))->tag == tag) { - listRemove(_this->tables); - } else { - if (listNext(_this->tables)) { - done = 1; - } - } - } while (!done); - } -} - -static void ProcessTables(TrueTypeCreator *); - -int StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length) -{ - sal_uInt16 numTables, searchRange=1, entrySelector=0, rangeShift; - sal_uInt32 s, offset, checkSumAdjustment = 0; - sal_uInt32 *p; - sal_uInt8 *ttf; - int i=0, n; - TableEntry *te; - sal_uInt8 *head = NULL; /* saved pointer to the head table data for checkSumAdjustment calculation */ - - if ((n = listCount(_this->tables)) == 0) return SF_TTFORMAT; - - ProcessTables(_this); - - /* ProcessTables() adds 'loca' and 'hmtx' */ - - n = listCount(_this->tables); - numTables = (sal_uInt16) n; - - - te = scalloc(n, sizeof(TableEntry)); - - listToFirst(_this->tables); - for (i = 0; i < n; i++) { - GetRawData((TrueTypeTable *) listCurrent(_this->tables), &te[i].data, &te[i].length, &te[i].tag); - listNext(_this->tables); - } - - qsort(te, n, sizeof(TableEntry), TableEntryCompareF); - - do { - searchRange *= 2; - entrySelector++; - } while (searchRange <= numTables); - - searchRange *= 8; - entrySelector--; - rangeShift = numTables * 16 - searchRange; - - s = offset = 12 + 16 * n; - - for (i = 0; i < n; i++) { - s += (te[i].length + 3) & (sal_uInt32) ~3; - /* if ((te[i].length & 3) != 0) s += (4 - (te[i].length & 3)) & 3; */ - } - - ttf = smalloc(s); - - /* Offset Table */ - PutUInt32(_this->tag, ttf, 0, 1); - PutUInt16(numTables, ttf, 4, 1); - PutUInt16(searchRange, ttf, 6, 1); - PutUInt16(entrySelector, ttf, 8, 1); - PutUInt16(rangeShift, ttf, 10, 1); - - /* Table Directory */ - for (i = 0; i < n; i++) { - PutUInt32(te[i].tag, ttf + 12, 16 * i, 1); - PutUInt32(CheckSum((sal_uInt32 *) te[i].data, te[i].length), ttf + 12, 16 * i + 4, 1); - PutUInt32(offset, ttf + 12, 16 * i + 8, 1); - PutUInt32(te[i].length, ttf + 12, 16 * i + 12, 1); - - if (te[i].tag == T_head) { - head = ttf + offset; - } - - memcpy(ttf+offset, te[i].data, (te[i].length + 3) & (sal_uInt32) ~3 ); - offset += (te[i].length + 3) & (sal_uInt32) ~3; - /* if ((te[i].length & 3) != 0) offset += (4 - (te[i].length & 3)) & 3; */ - } - - free(te); - - p = (sal_uInt32 *) ttf; - for (i = 0; i < (int)s / 4; i++) checkSumAdjustment += p[i]; - PutUInt32(0xB1B0AFBA - checkSumAdjustment, head, 8, 1); - - *ptr = ttf; - *length = s; - - return SF_OK; -} - -int StreamToFile(TrueTypeCreator *_this, const char* fname) -{ - sal_uInt8 *ptr; - sal_uInt32 length; - int r; - FILE* fd; - - if ((r = StreamToMemory(_this, &ptr, &length)) != SF_OK) return r; - if (!fname) return SF_BADFILE; - if ((fd = fopen(fname, "wb")) == NULL) return SF_BADFILE; - - if (fwrite(ptr, 1, length, fd) != length) { - r = SF_FILEIO; - } else { - r = SF_OK; - } - - fclose(fd); - free(ptr); - return r; -} - - - -/* - * TrueTypeTable private methods - */ - -#define TABLESIZE_head 54 -#define TABLESIZE_hhea 36 -#define TABLESIZE_maxp 32 - - - -/* Table data points to - * -------------------------------------------- - * generic tdata_generic struct - * 'head' TABLESIZE_head bytes of memory - * 'hhea' TABLESIZE_hhea bytes of memory - * 'loca' tdata_loca struct - * 'maxp' TABLESIZE_maxp bytes of memory - * 'glyf' list of GlyphData structs (defined in sft.h) - * 'name' list of NameRecord structs (defined in sft.h) - * 'post' tdata_post struct - * - */ - - -#define CMAP_SUBTABLE_INIT 10 -#define CMAP_SUBTABLE_INCR 10 -#define CMAP_PAIR_INIT 500 -#define CMAP_PAIR_INCR 500 - -typedef struct { - sal_uInt32 id; /* subtable ID (platform/encoding ID) */ - sal_uInt32 n; /* number of used translation pairs */ - sal_uInt32 m; /* number of allocated translation pairs */ - sal_uInt32 *xc; /* character array */ - sal_uInt32 *xg; /* glyph array */ -} CmapSubTable; - -typedef struct { - sal_uInt32 n; /* number of used CMAP sub-tables */ - sal_uInt32 m; /* number of allocated CMAP sub-tables */ - CmapSubTable *s; /* sotred array of sub-tables */ -} table_cmap; - -typedef struct { - sal_uInt32 tag; - sal_uInt32 nbytes; - sal_uInt8 *ptr; -} tdata_generic; - -typedef struct { - sal_uInt32 nbytes; /* number of bytes in loca table */ - sal_uInt8 *ptr; /* pointer to the data */ -} tdata_loca; - -typedef struct { - sal_uInt32 format; - sal_uInt32 italicAngle; - sal_Int16 underlinePosition; - sal_Int16 underlineThickness; - sal_uInt32 isFixedPitch; - void *ptr; /* format-specific pointer */ -} tdata_post; - - -/* allocate memory for a TT table */ -static sal_uInt8 *ttmalloc(sal_uInt32 nbytes) -{ - sal_uInt32 n; - sal_uInt8 *res; - - n = (nbytes + 3) & (sal_uInt32) ~3; - res = malloc(n); - assert(res != 0); - memset(res, 0, n); - - return res; -} - -static void FreeGlyphData(void *ptr) -{ - GlyphData *p = (GlyphData *) ptr; - if (p->ptr) free(p->ptr); - free(p); -} - -static void TrueTypeTableDispose_generic(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) { - tdata_generic *pdata = (tdata_generic *) _this->data; - if (pdata->nbytes) free(pdata->ptr); - free(_this->data); - } - free(_this); - } -} - -static void TrueTypeTableDispose_head(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) free(_this->data); - free(_this); - } -} - -static void TrueTypeTableDispose_hhea(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) free(_this->data); - free(_this); - } -} - -static void TrueTypeTableDispose_loca(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) { - tdata_loca *p = (tdata_loca *) _this->data; - if (p->ptr) free(p->ptr); - free(_this->data); - } - free(_this); - } -} - -static void TrueTypeTableDispose_maxp(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) free(_this->data); - free(_this); - } -} - -static void TrueTypeTableDispose_glyf(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) listDispose((list) _this->data); - free(_this); - } -} - -static void TrueTypeTableDispose_cmap(TrueTypeTable *_this) -{ - table_cmap *t; - CmapSubTable *s; - sal_uInt32 i; - - if (_this) { - t = (table_cmap *) _this->data; - if (t) { - s = t->s; - if (s) { - for (i = 0; i < t->m; i++) { - if (s[i].xc) free(s[i].xc); - if (s[i].xg) free(s[i].xg); - } - free(s); - } - free(t); - } - free(_this); - } -} - -static void TrueTypeTableDispose_name(TrueTypeTable *_this) -{ - if (_this) { - if (_this->data) listDispose((list) _this->data); - free(_this); - } -} - -static void TrueTypeTableDispose_post(TrueTypeTable *_this) -{ - if (_this) { - tdata_post *p = (tdata_post *) _this->data; - if (p) { - if (p->format == 0x00030000) { - /* do nothing */ - } else { - fprintf(stderr, "Unsupported format of a 'post' table: %08X.\n", (int)p->format); - } - free(p); - } - free(_this); - } -} - -/* destructor vtable */ - -static struct { - sal_uInt32 tag; - void (*f)(TrueTypeTable *); -} vtable1[] = -{ - {0, TrueTypeTableDispose_generic}, - {T_head, TrueTypeTableDispose_head}, - {T_hhea, TrueTypeTableDispose_hhea}, - {T_loca, TrueTypeTableDispose_loca}, - {T_maxp, TrueTypeTableDispose_maxp}, - {T_glyf, TrueTypeTableDispose_glyf}, - {T_cmap, TrueTypeTableDispose_cmap}, - {T_name, TrueTypeTableDispose_name}, - {T_post, TrueTypeTableDispose_post} - -}; - -static int GetRawData_generic(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - assert(_this != 0); - assert(_this->data != 0); - - *ptr = ((tdata_generic *) _this->data)->ptr; - *len = ((tdata_generic *) _this->data)->nbytes; - *tag = ((tdata_generic *) _this->data)->tag; - - return TTCR_OK; -} - - -static int GetRawData_head(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - *len = TABLESIZE_head; - *ptr = (sal_uInt8 *) _this->data; - *tag = T_head; - - return TTCR_OK; -} - -static int GetRawData_hhea(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - *len = TABLESIZE_hhea; - *ptr = (sal_uInt8 *) _this->data; - *tag = T_hhea; - - return TTCR_OK; -} - -static int GetRawData_loca(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - tdata_loca *p; - - assert(_this->data != 0); - - p = (tdata_loca *) _this->data; - - if (p->nbytes == 0) return TTCR_ZEROGLYPHS; - - *ptr = p->ptr; - *len = p->nbytes; - *tag = T_loca; - - return TTCR_OK; -} - -static int GetRawData_maxp(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - *len = TABLESIZE_maxp; - *ptr = (sal_uInt8 *) _this->data; - *tag = T_maxp; - - return TTCR_OK; -} - -static int GetRawData_glyf(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - sal_uInt32 n, nbytes = 0; - list l = (list) _this->data; - /* sal_uInt16 curID = 0; */ /* to check if glyph IDs are sequential and start from zero */ - sal_uInt8 *p; - - *ptr = 0; - *len = 0; - *tag = 0; - - if (listCount(l) == 0) return TTCR_ZEROGLYPHS; - - listToFirst(l); - do { - /* if (((GlyphData *) listCurrent(l))->glyphID != curID++) return TTCR_GLYPHSEQ; */ - nbytes += ((GlyphData *) listCurrent(l))->nbytes; - } while (listNext(l)); - - p = _this->rawdata = ttmalloc(nbytes); - - listToFirst(l); - do { - n = ((GlyphData *) listCurrent(l))->nbytes; - if (n != 0) { - memcpy(p, ((GlyphData *) listCurrent(l))->ptr, n); - p += n; - } - } while (listNext(l)); - - *len = nbytes; - *ptr = _this->rawdata; - *tag = T_glyf; - - return TTCR_OK; -} - -/* cmap packers */ -static sal_uInt8 *PackCmapType0(CmapSubTable *s, sal_uInt32 *length) -{ - sal_uInt8 *ptr = smalloc(262); - sal_uInt8 *p = ptr + 6; - sal_uInt32 i, j; - sal_uInt16 g; - - PutUInt16(0, ptr, 0, 1); - PutUInt16(262, ptr, 2, 1); - PutUInt16(0, ptr, 4, 1); - - for (i = 0; i < 256; i++) { - g = 0; - for (j = 0; j < s->n; j++) { - if (s->xc[j] == i) { - g = (sal_uInt16) s->xg[j]; - } - } - p[i] = (sal_uInt8) g; - } - *length = 262; - return ptr; -} - -static sal_uInt8 *PackCmapType6(CmapSubTable *s, sal_uInt32 *length) -{ - sal_uInt8 *ptr = smalloc(s->n*2 + 10); - sal_uInt8 *p = ptr + 10; - sal_uInt32 i, j; - sal_uInt16 g; - - PutUInt16(6, ptr, 0, 1); - PutUInt16((sal_uInt16)(s->n*2+10), ptr, 2, 1); - PutUInt16(0, ptr, 4, 1); - PutUInt16(0, ptr, 6, 1); - PutUInt16((sal_uInt16)(s->n), ptr, 8, 1 ); - - for (i = 0; i < s->n; i++) { - g = 0; - for (j = 0; j < s->n; j++) { - if (s->xc[j] == i) { - g = (sal_uInt16) s->xg[j]; - } - } - PutUInt16( g, p, 2*i, 1 ); - } - *length = s->n*2+10; - return ptr; -} - - - -/* XXX it only handles Format 0 encoding tables */ -static sal_uInt8 *PackCmap(CmapSubTable *s, sal_uInt32 *length) -{ - if( s->xg[s->n-1] > 0xff ) - return PackCmapType6(s, length); - else - return PackCmapType0(s, length); -} - -static int GetRawData_cmap(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - table_cmap *t; - sal_uInt8 **subtables; - sal_uInt32 *sizes; /* of subtables */ - sal_uInt32 i; - sal_uInt32 tlen = 0; - sal_uInt32 l; - sal_uInt32 cmapsize; - sal_uInt8 *cmap; - sal_uInt32 coffset; - - assert(_this != 0); - t = (table_cmap *) _this->data; - assert(t != 0); - assert(t->n != 0); - - subtables = scalloc(t->n, sizeof(sal_uInt8 *)); - sizes = scalloc(t->n, sizeof(sal_uInt32)); - - for (i = 0; i < t->n; i++) { - subtables[i] = PackCmap(t->s+i, &l); - sizes[i] = l; - tlen += l; - } - - cmapsize = tlen + 4 + 8 * t->n; - _this->rawdata = cmap = ttmalloc(cmapsize); - - PutUInt16(0, cmap, 0, 1); - PutUInt16((sal_uInt16)t->n, cmap, 2, 1); - coffset = 4 + t->n * 8; - - for (i = 0; i < t->n; i++) { - PutUInt16((sal_uInt16)(t->s[i].id >> 16), cmap + 4, i * 8, 1); - PutUInt16((sal_uInt16)(t->s[i].id & 0xFF), cmap + 4, 2 + i * 8, 1); - PutUInt32(coffset, cmap + 4, 4 + i * 8, 1); - memcpy(cmap + coffset, subtables[i], sizes[i]); - free(subtables[i]); - coffset += sizes[i]; - } - - free(subtables); - free(sizes); - - *ptr = cmap; - *len = cmapsize; - *tag = T_cmap; - - return TTCR_OK; -} - - -static int GetRawData_name(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - list l; - NameRecord *nr; - sal_Int16 i=0, n; /* number of Name Records */ - sal_uInt8 *name; - sal_uInt16 nameLen; - int stringLen = 0; - sal_uInt8 *p1, *p2; - - *ptr = 0; - *len = 0; - *tag = 0; - - assert(_this != 0); - l = (list) _this->data; - assert(l != 0); - - if ((n = (sal_Int16)listCount(l)) == 0) return TTCR_NONAMES; - - nr = scalloc(n, sizeof(NameRecord)); - - listToFirst(l); - - do { - memcpy(nr+i, listCurrent(l), sizeof(NameRecord)); - stringLen += nr[i].slen; - i++; - } while (listNext(l)); - - if (stringLen > 65535) { - free(nr); - return TTCR_NAMETOOLONG; - } - - qsort(nr, n, sizeof(NameRecord), NameRecordCompareF); - - nameLen = (sal_uInt16)(stringLen + 12 * n + 6); - name = ttmalloc(nameLen); - - PutUInt16(0, name, 0, 1); - PutUInt16(n, name, 2, 1); - PutUInt16((sal_uInt16)(6 + 12 * n), name, 4, 1); - - p1 = name + 6; - p2 = p1 + 12 * n; - - for (i = 0; i < n; i++) { - PutUInt16(nr[i].platformID, p1, 0, 1); - PutUInt16(nr[i].encodingID, p1, 2, 1); - PutUInt16(nr[i].languageID, p1, 4, 1); - PutUInt16(nr[i].nameID, p1, 6, 1); - PutUInt16(nr[i].slen, p1, 8, 1); - PutUInt16((sal_uInt16)(p2 - (name + 6 + 12 * n)), p1, 10, 1); - memcpy(p2, nr[i].sptr, nr[i].slen); - /* {int j; for(j=0; jrawdata = name; - - *ptr = name; - *len = nameLen; - *tag = T_name; - - /*{int j; for(j=0; jdata; - sal_uInt8 *post = 0; - sal_uInt32 postLen = 0; - int ret; - - if (_this->rawdata) free(_this->rawdata); - - if (p->format == 0x00030000) { - postLen = 32; - post = ttmalloc(postLen); - PutUInt32(0x00030000, post, 0, 1); - PutUInt32(p->italicAngle, post, 4, 1); - PutUInt16(p->underlinePosition, post, 8, 1); - PutUInt16(p->underlineThickness, post, 10, 1); - PutUInt16((sal_uInt16)p->isFixedPitch, post, 12, 1); - ret = TTCR_OK; - } else { - fprintf(stderr, "Unrecognized format of a post table: %08X.\n", (int)p->format); - ret = TTCR_POSTFORMAT; - } - - *ptr = _this->rawdata = post; - *len = postLen; - *tag = T_post; - - return ret; -} - - - - - -static struct { - sal_uInt32 tag; - int (*f)(TrueTypeTable *, sal_uInt8 **, sal_uInt32 *, sal_uInt32 *); -} vtable2[] = -{ - {0, GetRawData_generic}, - {T_head, GetRawData_head}, - {T_hhea, GetRawData_hhea}, - {T_loca, GetRawData_loca}, - {T_maxp, GetRawData_maxp}, - {T_glyf, GetRawData_glyf}, - {T_cmap, GetRawData_cmap}, - {T_name, GetRawData_name}, - {T_post, GetRawData_post} - - -}; - -/* - * TrueTypeTable public methods - */ - -/* Note: Type42 fonts only need these tables: - * head, hhea, loca, maxp, cvt, prep, glyf, hmtx, fpgm - * - * Microsoft required tables - * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post, OS/2 - * - * Apple required tables - * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post - * - */ - -TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag, - sal_uInt32 nbytes, - sal_uInt8 *ptr) -{ - TrueTypeTable *table; - tdata_generic *pdata; - - table = smalloc(sizeof(TrueTypeTable)); - pdata = (tdata_generic *) smalloc(sizeof(tdata_generic)); - pdata->nbytes = nbytes; - pdata->tag = tag; - if (nbytes) { - pdata->ptr = ttmalloc(nbytes); - memcpy(pdata->ptr, ptr, nbytes); - } else { - pdata->ptr = 0; - } - - table->tag = 0; - table->data = pdata; - table->rawdata = 0; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision, - sal_uInt16 flags, - sal_uInt16 unitsPerEm, - sal_uInt8 *created, - sal_uInt16 macStyle, - sal_uInt16 lowestRecPPEM, - sal_Int16 fontDirectionHint) -{ - TrueTypeTable *table; - sal_uInt8 *ptr; - - assert(created != 0); - - table = smalloc(sizeof(TrueTypeTable)); - ptr = ttmalloc(TABLESIZE_head); - - - PutUInt32(0x00010000, ptr, 0, 1); /* version */ - PutUInt32(fontRevision, ptr, 4, 1); - PutUInt32(0x5F0F3CF5, ptr, 12, 1); /* magic number */ - PutUInt16(flags, ptr, 16, 1); - PutUInt16(unitsPerEm, ptr, 18, 1); - memcpy(ptr+20, created, 8); /* Created Long Date */ - memset(ptr+28, 0, 8); /* Modified Long Date */ - PutUInt16(macStyle, ptr, 44, 1); - PutUInt16(lowestRecPPEM, ptr, 46, 1); - PutUInt16(fontDirectionHint, ptr, 48, 1); - PutUInt16(0, ptr, 52, 1); /* glyph data format: 0 */ - - table->data = (void *) ptr; - table->tag = T_head; - table->rawdata = 0; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender, - sal_Int16 descender, - sal_Int16 linegap, - sal_Int16 caretSlopeRise, - sal_Int16 caretSlopeRun) -{ - TrueTypeTable *table; - sal_uInt8 *ptr; - - table = smalloc(sizeof(TrueTypeTable)); - ptr = ttmalloc(TABLESIZE_hhea); - - PutUInt32(0x00010000, ptr, 0, 1); /* version */ - PutUInt16(ascender, ptr, 4, 1); - PutUInt16(descender, ptr, 6, 1); - PutUInt16(linegap, ptr, 8, 1); - PutUInt16(caretSlopeRise, ptr, 18, 1); - PutUInt16(caretSlopeRun, ptr, 20, 1); - PutUInt16(0, ptr, 22, 1); /* reserved 1 */ - PutUInt16(0, ptr, 24, 1); /* reserved 2 */ - PutUInt16(0, ptr, 26, 1); /* reserved 3 */ - PutUInt16(0, ptr, 28, 1); /* reserved 4 */ - PutUInt16(0, ptr, 30, 1); /* reserved 5 */ - PutUInt16(0, ptr, 32, 1); /* metricDataFormat */ - - table->data = (void *) ptr; - table->tag = T_hhea; - table->rawdata = 0; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_loca(void) -{ - TrueTypeTable *table = smalloc(sizeof(TrueTypeTable)); - table->data = smalloc(sizeof(tdata_loca)); - - ((tdata_loca *)table->data)->nbytes = 0; - ((tdata_loca *)table->data)->ptr = 0; - - table->tag = T_loca; - table->rawdata = 0; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_maxp(sal_uInt8 *maxp, int size) -{ - TrueTypeTable *table = smalloc(sizeof(TrueTypeTable)); - table->data = ttmalloc(TABLESIZE_maxp); - - if (maxp && size == TABLESIZE_maxp) { - memcpy(table->data, maxp, TABLESIZE_maxp); - } - - table->tag = T_maxp; - table->rawdata = 0; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_glyf(void) -{ - TrueTypeTable *table = smalloc(sizeof(TrueTypeTable)); - list l = listNewEmpty(); - - assert(l != 0); - - listSetElementDtor(l, FreeGlyphData); - - table->data = l; - table->rawdata = 0; - table->tag = T_glyf; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_cmap(void) -{ - TrueTypeTable *table = smalloc(sizeof(TrueTypeTable)); - table_cmap *cmap = smalloc(sizeof(table_cmap)); - - cmap->n = 0; - cmap->m = CMAP_SUBTABLE_INIT; - cmap->s = (CmapSubTable *) scalloc(CMAP_SUBTABLE_INIT, sizeof(CmapSubTable)); - memset(cmap->s, 0, sizeof(CmapSubTable) * CMAP_SUBTABLE_INIT); - - table->data = (table_cmap *) cmap; - - table->rawdata = 0; - table->tag = T_cmap; - - return table; -} - -static void DisposeNameRecord(void *ptr) -{ - if (ptr != 0) { - NameRecord *nr = (NameRecord *) ptr; - if (nr->sptr) free(nr->sptr); - free(ptr); - } -} - -static NameRecord* NameRecordNewCopy(NameRecord *nr) -{ - NameRecord *p = smalloc(sizeof(NameRecord)); - - memcpy(p, nr, sizeof(NameRecord)); - - if (p->slen) { - p->sptr = smalloc(p->slen); - memcpy(p->sptr, nr->sptr, p->slen); - } - - return p; -} - -TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord *nr) -{ - TrueTypeTable *table = smalloc(sizeof(TrueTypeTable)); - list l = listNewEmpty(); - - assert(l != 0); - - listSetElementDtor(l, DisposeNameRecord); - - if (n != 0) { - int i; - for (i = 0; i < n; i++) { - listAppend(l, NameRecordNewCopy(nr+i)); - } - } - - table->data = l; - table->rawdata = 0; - table->tag = T_name; - - return table; -} - -TrueTypeTable *TrueTypeTableNew_post(sal_uInt32 format, - sal_uInt32 italicAngle, - sal_Int16 underlinePosition, - sal_Int16 underlineThickness, - sal_uInt32 isFixedPitch) -{ - TrueTypeTable *table; - tdata_post *post; - - assert(format == 0x00030000); /* Only format 3.0 is supported at this time */ - table = smalloc(sizeof(TrueTypeTable)); - post = smalloc(sizeof(tdata_post)); - - post->format = format; - post->italicAngle = italicAngle; - post->underlinePosition = underlinePosition; - post->underlineThickness = underlineThickness; - post->isFixedPitch = isFixedPitch; - post->ptr = 0; - - table->data = post; - table->rawdata = 0; - table->tag = T_post; - - return table; -} - - - -void TrueTypeTableDispose(TrueTypeTable *_this) -{ - /* XXX do a binary search */ - unsigned int i; - - assert(_this != 0); - - if (_this->rawdata) free(_this->rawdata); - - for(i=0; i < sizeof(vtable1)/sizeof(*vtable1); i++) { - if (_this->tag == vtable1[i].tag) { - vtable1[i].f(_this); - return; - } - } - assert(!"Unknown TrueType table.\n"); -} - -int GetRawData(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) -{ - /* XXX do a binary search */ - unsigned int i; - - assert(_this != 0); - assert(ptr != 0); - assert(len != 0); - assert(tag != 0); - - *ptr = 0; *len = 0; *tag = 0; - - if (_this->rawdata) { - free(_this->rawdata); - _this->rawdata = 0; - } - - for(i=0; i < sizeof(vtable2)/sizeof(*vtable2); i++) { - if (_this->tag == vtable2[i].tag) { - return vtable2[i].f(_this, ptr, len, tag); - } - } - - assert(!"Unknwon TrueType table.\n"); - return TTCR_UNKNOWN; -} - -void cmapAdd(TrueTypeTable *table, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g) -{ - sal_uInt32 i, found; - table_cmap *t; - CmapSubTable *s; - - assert(table != 0); - assert(table->tag == T_cmap); - t = (table_cmap *) table->data; assert(t != 0); - s = t->s; assert(s != 0); - - found = 0; - - for (i = 0; i < t->n; i++) { - if (s[i].id == id) { - found = 1; - break; - } - } - - if (!found) { - if (t->n == t->m) { - CmapSubTable *tmp; - tmp = scalloc(t->m + CMAP_SUBTABLE_INCR, sizeof(CmapSubTable)); - memset(tmp, 0, t->m + CMAP_SUBTABLE_INCR * sizeof(CmapSubTable)); - memcpy(tmp, s, sizeof(CmapSubTable) * t->m); - t->m += CMAP_SUBTABLE_INCR; - free(s); - s = tmp; - t->s = s; - } - - for (i = 0; i < t->n; i++) { - if (s[i].id > id) break; - } - - if (i < t->n) { - memmove(s+i+1, s+i, t->n-i); - } - - t->n++; - - s[i].id = id; - s[i].n = 0; - s[i].m = CMAP_PAIR_INIT; - s[i].xc = scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)); - s[i].xg = scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)); - } - - if (s[i].n == s[i].m) { - sal_uInt32 *tmp1 = scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)); - sal_uInt32 *tmp2 = scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)); - assert(tmp1 != 0); - assert(tmp2 != 0); - memcpy(tmp1, s[i].xc, sizeof(sal_uInt32) * s[i].m); - memcpy(tmp2, s[i].xg, sizeof(sal_uInt32) * s[i].m); - s[i].m += CMAP_PAIR_INCR; - free(s[i].xc); - free(s[i].xg); - s[i].xc = tmp1; - s[i].xg = tmp2; - } - - s[i].xc[s[i].n] = c; - s[i].xg[s[i].n] = g; - s[i].n++; -} - -sal_uInt32 glyfAdd(TrueTypeTable *table, GlyphData *glyphdata, TrueTypeFont *fnt) -{ - list l; - sal_uInt32 currentID; - int ret, n, ncomponents; - list glyphlist; - GlyphData *gd; - - assert(table != 0); - assert(table->tag == T_glyf); - - if (!glyphdata) return (sal_uInt32)~0; - - glyphlist = listNewEmpty(); - - ncomponents = GetTTGlyphComponents(fnt, glyphdata->glyphID, glyphlist); - - l = (list) table->data; - if (listCount(l) > 0) { - listToLast(l); - ret = n = ((GlyphData *) listCurrent(l))->newID + 1; - } else { - ret = n = 0; - } - glyphdata->newID = n++; - listAppend(l, glyphdata); - - if (ncomponents > 1) { - listPositionAt(glyphlist, 1); /* glyphData->glyphID is always the first glyph on the list */ - do { - int found = 0; - currentID = (sal_uIntPtr) listCurrent(glyphlist); - /* XXX expensive! should be rewritten with sorted arrays! */ - listToFirst(l); - do { - if (((GlyphData *) listCurrent(l))->glyphID == currentID) { - found = 1; - break; - } - } while (listNext(l)); - - if (!found) { - gd = GetTTRawGlyphData(fnt, currentID); - gd->newID = n++; - listAppend(l, gd); - } - } while (listNext(glyphlist)); - } - - listDispose(glyphlist); - return ret; -} - -sal_uInt32 glyfCount(const TrueTypeTable *table) -{ - assert(table != 0); - assert(table->tag == T_glyf); - return listCount((list) table->data); -} - - -void nameAdd(TrueTypeTable *table, NameRecord *nr) -{ - list l; - - assert(table != 0); - assert(table->tag == T_name); - - l = (list) table->data; - - listAppend(l, NameRecordNewCopy(nr)); -} - -static TrueTypeTable *FindTable(TrueTypeCreator *tt, sal_uInt32 tag) -{ - if (listIsEmpty(tt->tables)) return 0; - - listToFirst(tt->tables); - - do { - if (((TrueTypeTable *) listCurrent(tt->tables))->tag == tag) { - return listCurrent(tt->tables); - } - } while (listNext(tt->tables)); - - return 0; -} - -/* This function processes all the tables and synchronizes them before creating - * the output TrueType stream. - * - * *** It adds two TrueType tables to the font: 'loca' and 'hmtx' *** - * - * It does: - * - * - Re-numbers glyph IDs and creates 'glyf', 'loca', and 'hmtx' tables. - * - Calculates xMin, yMin, xMax, and yMax and stores values in 'head' table. - * - Stores indexToLocFormat in 'head' - * - updates 'maxp' table - * - Calculates advanceWidthMax, minLSB, minRSB, xMaxExtent and numberOfHMetrics - * in 'hhea' table - * - */ -static void ProcessTables(TrueTypeCreator *tt) -{ - TrueTypeTable *glyf, *loca, *head, *maxp, *hhea; - list glyphlist; - sal_uInt32 nGlyphs, locaLen = 0, glyfLen = 0; - sal_Int16 xMin = 0, yMin = 0, xMax = 0, yMax = 0; - sal_uInt32 i = 0; - sal_Int16 indexToLocFormat; - sal_uInt8 *glyfPtr, *locaPtr, *hmtxPtr, *hheaPtr; - sal_uInt32 hmtxSize; - sal_uInt8 *p1, *p2; - sal_uInt16 maxPoints = 0, maxContours = 0, maxCompositePoints = 0, maxCompositeContours = 0; - TTSimpleGlyphMetrics *met; - int nlsb = 0; - sal_uInt32 *gid; /* array of old glyphIDs */ - - glyf = FindTable(tt, T_glyf); - glyphlist = (list) glyf->data; - nGlyphs = listCount(glyphlist); - assert(nGlyphs != 0); - gid = scalloc(nGlyphs, sizeof(sal_uInt32)); - - RemoveTable(tt, T_loca); - RemoveTable(tt, T_hmtx); - - /* XXX Need to make sure that composite glyphs do not break during glyph renumbering */ - - listToFirst(glyphlist); - do { - GlyphData *gd = (GlyphData *) listCurrent(glyphlist); - sal_Int16 z; - glyfLen += gd->nbytes; - /* XXX if (gd->nbytes & 1) glyfLen++; */ - - - assert(gd->newID == i); - gid[i++] = gd->glyphID; - /* gd->glyphID = i++; */ - - /* printf("IDs: %d %d.\n", gd->glyphID, gd->newID); */ - - if (gd->nbytes != 0) { - z = GetInt16(gd->ptr, 2, 1); - if (z < xMin) xMin = z; - - z = GetInt16(gd->ptr, 4, 1); - if (z < yMin) yMin = z; - - z = GetInt16(gd->ptr, 6, 1); - if (z > xMax) xMax = z; - - z = GetInt16(gd->ptr, 8, 1); - if (z > yMax) yMax = z; - } - - if (gd->compflag == 0) { /* non-composite glyph */ - if (gd->npoints > maxPoints) maxPoints = gd->npoints; - if (gd->ncontours > maxContours) maxContours = gd->ncontours; - } else { /* composite glyph */ - if (gd->npoints > maxCompositePoints) maxCompositePoints = gd->npoints; - if (gd->ncontours > maxCompositeContours) maxCompositeContours = gd->ncontours; - } - - } while (listNext(glyphlist)); - - indexToLocFormat = (glyfLen / 2 > 0xFFFF) ? 1 : 0; - locaLen = indexToLocFormat ? (nGlyphs + 1) << 2 : (nGlyphs + 1) << 1; - - glyfPtr = ttmalloc(glyfLen); - locaPtr = ttmalloc(locaLen); - met = scalloc(nGlyphs, sizeof(TTSimpleGlyphMetrics)); - i = 0; - - listToFirst(glyphlist); - p1 = glyfPtr; - p2 = locaPtr; - do { - GlyphData *gd = (GlyphData *) listCurrent(glyphlist); - - if (gd->compflag) { /* re-number all components */ - sal_uInt16 flags, index; - sal_uInt8 *ptr = gd->ptr + 10; - do { - sal_uInt32 j; - flags = GetUInt16(ptr, 0, 1); - index = GetUInt16(ptr, 2, 1); - /* XXX use the sorted array of old to new glyphID mapping and do a binary search */ - for (j = 0; j < nGlyphs; j++) { - if (gid[j] == index) { - break; - } - } - /* printf("X: %d -> %d.\n", index, j); */ - - PutUInt16((sal_uInt16) j, ptr, 2, 1); - - ptr += 4; - - if (flags & ARG_1_AND_2_ARE_WORDS) { - ptr += 4; - } else { - ptr += 2; - } - - if (flags & WE_HAVE_A_SCALE) { - ptr += 2; - } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { - ptr += 4; - } else if (flags & WE_HAVE_A_TWO_BY_TWO) { - ptr += 8; - } - } while (flags & MORE_COMPONENTS); - } - - if (gd->nbytes != 0) { - memcpy(p1, gd->ptr, gd->nbytes); - } - if (indexToLocFormat == 1) { - PutUInt32(p1 - glyfPtr, p2, 0, 1); - p2 += 4; - } else { - PutUInt16((sal_uInt16)((p1 - glyfPtr) >> 1), p2, 0, 1); - p2 += 2; - } - p1 += gd->nbytes; - - /* fill the array of metrics */ - met[i].adv = gd->aw; - met[i].sb = gd->lsb; - i++; - } while (listNext(glyphlist)); - - free(gid); - - if (indexToLocFormat == 1) { - PutUInt32(p1 - glyfPtr, p2, 0, 1); - } else { - PutUInt16((sal_uInt16)((p1 - glyfPtr) >> 1), p2, 0, 1); - } - - glyf->rawdata = glyfPtr; - - loca = TrueTypeTableNew_loca(); assert(loca != 0); - ((tdata_loca *) loca->data)->ptr = locaPtr; - ((tdata_loca *) loca->data)->nbytes = locaLen; - - AddTable(tt, loca); - - head = FindTable(tt, T_head); - PutInt16(xMin, head->data, 36, 1); - PutInt16(yMin, head->data, 38, 1); - PutInt16(xMax, head->data, 40, 1); - PutInt16(yMax, head->data, 42, 1); - PutInt16(indexToLocFormat, head->data, 50, 1); - - maxp = FindTable(tt, T_maxp); - - PutUInt16((sal_uInt16)nGlyphs, maxp->data, 4, 1); - PutUInt16(maxPoints, maxp->data, 6, 1); - PutUInt16(maxContours, maxp->data, 8, 1); - PutUInt16(maxCompositePoints, maxp->data, 10, 1); - PutUInt16(maxCompositeContours, maxp->data, 12, 1); - -#if 0 - /* XXX do not overwrite the existing data. Fix: re-calculate these numbers here */ - PutUInt16(2, maxp->data, 14, 1); /* maxZones is always 2 */ - PutUInt16(0, maxp->data, 16, 1); /* maxTwilightPoints */ - PutUInt16(0, maxp->data, 18, 1); /* maxStorage */ - PutUInt16(0, maxp->data, 20, 1); /* maxFunctionDefs */ - PutUint16(0, maxp->data, 22, 1); /* maxInstructionDefs */ - PutUint16(0, maxp->data, 24, 1); /* maxStackElements */ - PutUint16(0, maxp->data, 26, 1); /* maxSizeOfInstructions */ - PutUint16(0, maxp->data, 28, 1); /* maxComponentElements */ - PutUint16(0, maxp->data, 30, 1); /* maxComponentDepth */ -#endif - - /* - * Generate an htmx table and update hhea table - */ - hhea = FindTable(tt, T_hhea); assert(hhea != 0); - hheaPtr = (sal_uInt8 *) hhea->data; - if (nGlyphs > 2) { - for (i = nGlyphs - 1; i > 0; i--) { - if (met[i].adv != met[i-1].adv) break; - } - nlsb = nGlyphs - 1 - i; - } - hmtxSize = (nGlyphs - nlsb) * 4 + nlsb * 2; - hmtxPtr = ttmalloc(hmtxSize); - p1 = hmtxPtr; - - for (i = 0; i < nGlyphs; i++) { - if (i < nGlyphs - nlsb) { - PutUInt16(met[i].adv, p1, 0, 1); - PutUInt16(met[i].sb, p1, 2, 1); - p1 += 4; - } else { - PutUInt16(met[i].sb, p1, 0, 1); - p1 += 2; - } - } - - AddTable(tt, TrueTypeTableNew(T_hmtx, hmtxSize, hmtxPtr)); - PutUInt16((sal_uInt16)(nGlyphs - nlsb), hheaPtr, 34, 1); - free(hmtxPtr); - free(met); -} - -#ifdef TEST_TTCR -int main(void) -{ - TrueTypeCreator *ttcr; - sal_uInt8 *t1, *t2, *t3, *t4, *t5, *t6, *t7; - - TrueTypeCreatorNewEmpty(mkTag('t','r','u','e'), &ttcr); - - t1 = malloc(1000); memset(t1, 'a', 1000); - t2 = malloc(2000); memset(t2, 'b', 2000); - t3 = malloc(3000); memset(t3, 'c', 3000); - t4 = malloc(4000); memset(t4, 'd', 4000); - t5 = malloc(5000); memset(t5, 'e', 5000); - t6 = malloc(6000); memset(t6, 'f', 6000); - t7 = malloc(7000); memset(t7, 'g', 7000); - - AddTable(ttcr, TrueTypeTableNew(0x6D617870, 1000, t1)); - AddTable(ttcr, TrueTypeTableNew(0x4F532F32, 2000, t2)); - AddTable(ttcr, TrueTypeTableNew(0x636D6170, 3000, t3)); - AddTable(ttcr, TrueTypeTableNew(0x6C6F6361, 4000, t4)); - AddTable(ttcr, TrueTypeTableNew(0x68686561, 5000, t5)); - AddTable(ttcr, TrueTypeTableNew(0x676C7966, 6000, t6)); - AddTable(ttcr, TrueTypeTableNew(0x6B65726E, 7000, t7)); - - free(t1); - free(t2); - free(t3); - free(t4); - free(t5); - free(t6); - free(t7); - - - StreamToFile(ttcr, "ttcrout.ttf"); - - TrueTypeCreatorDispose(ttcr); - return 0; -} -#endif diff --git a/vcl/source/fontsubset/ttcr.cxx b/vcl/source/fontsubset/ttcr.cxx new file mode 100644 index 000000000000..7f9ae796142b --- /dev/null +++ b/vcl/source/fontsubset/ttcr.cxx @@ -0,0 +1,1669 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/* + * TrueTypeCreator method implementation + * + * @author: Alexander Gelfenbain + * + */ + +#include +#include +#include + +#if OSL_DEBUG_LEVEL == 0 +# ifndef NDEBUG +# define NDEBUG +# endif +#endif +#include + +#include "ttcr.hxx" +#include "list.h" + + + +namespace vcl +{ + +/* + * Private Data Types + */ + + struct _TrueTypeCreator { + sal_uInt32 tag; /**< TrueType file tag */ + list tables; /**< List of table tags and pointers */ + }; + +/* These must be #defined so that they can be used in initializers */ +#define T_maxp 0x6D617870 +#define T_glyf 0x676C7966 +#define T_head 0x68656164 +#define T_loca 0x6C6F6361 +#define T_name 0x6E616D65 +#define T_hhea 0x68686561 +#define T_hmtx 0x686D7478 +#define T_cmap 0x636D6170 +#define T_vhea 0x76686561 +#define T_vmtx 0x766D7478 +#define T_OS2 0x4F532F32 +#define T_post 0x706F7374 +#define T_kern 0x6B65726E +#define T_cvt 0x63767420 + +typedef struct { + sal_uInt32 tag; + sal_uInt32 length; + sal_uInt8 *data; +} TableEntry; + +/* + * this is a duplicate code from sft.c but it is left here for performance reasons + */ +#ifdef __GNUC__ +#define _inline static __inline__ +#else +#define _inline static +#endif + +_inline sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) { + return (a << 24) | (b << 16) | (c << 8) | d; +} + +/*- Data access macros for data stored in big-endian or little-endian format */ +_inline sal_Int16 GetInt16(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + sal_Int16 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; + } else { + t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_uInt16 GetUInt16(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + sal_uInt16 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 8 | (ptr+offset)[1]; + } else { + t = (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_Int32 GetInt32(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + sal_Int32 t; + assert(ptr != 0); + + if (bigendian) { + t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | + (ptr+offset)[2] << 8 | (ptr+offset)[3]; + } else { + t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | + (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + +_inline sal_uInt32 GetUInt32(const sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + sal_uInt32 t; + assert(ptr != 0); + + + if (bigendian) { + t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 | + (ptr+offset)[2] << 8 | (ptr+offset)[3]; + } else { + t = (ptr+offset)[3] << 24 | (ptr+offset)[2] << 16 | + (ptr+offset)[1] << 8 | (ptr+offset)[0]; + } + + return t; +} + + +_inline void PutInt16(sal_Int16 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + assert(ptr != 0); + + if (bigendian) { + ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset+1] = (sal_uInt8)(val & 0xFF); + } else { + ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset] = (sal_uInt8)(val & 0xFF); + } +} + +_inline void PutUInt16(sal_uInt16 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + assert(ptr != 0); + + if (bigendian) { + ptr[offset] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset+1] = (sal_uInt8)(val & 0xFF); + } else { + ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset] = (sal_uInt8)(val & 0xFF); + } +} + +_inline void PutUInt32(sal_uInt32 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + assert(ptr != 0); + + if (bigendian) { + ptr[offset] = (sal_uInt8)((val >> 24) & 0xFF); + ptr[offset+1] = (sal_uInt8)((val >> 16) & 0xFF); + ptr[offset+2] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset+3] = (sal_uInt8)(val & 0xFF); + } else { + ptr[offset+3] = (sal_uInt8)((val >> 24) & 0xFF); + ptr[offset+2] = (sal_uInt8)((val >> 16) & 0xFF); + ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset] = (sal_uInt8)(val & 0xFF); + } + +} + + +_inline void PutInt32(sal_Int32 val, sal_uInt8 *ptr, sal_uInt32 offset, int bigendian) +{ + assert(ptr != 0); + + if (bigendian) { + ptr[offset] = (sal_uInt8)((val >> 24) & 0xFF); + ptr[offset+1] = (sal_uInt8)((val >> 16) & 0xFF); + ptr[offset+2] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset+3] = (sal_uInt8)(val & 0xFF); + } else { + ptr[offset+3] = (sal_uInt8)((val >> 24) & 0xFF); + ptr[offset+2] = (sal_uInt8)((val >> 16) & 0xFF); + ptr[offset+1] = (sal_uInt8)((val >> 8) & 0xFF); + ptr[offset] = (sal_uInt8)(val & 0xFF); + } + +} + +static int TableEntryCompareF(const void *l, const void *r) +{ + return ((const TableEntry *) l)->tag - ((const TableEntry *) r)->tag; +} + +static int NameRecordCompareF(const void *l, const void *r) +{ + NameRecord *ll = (NameRecord *) l; + NameRecord *rr = (NameRecord *) r; + + if (ll->platformID != rr->platformID) { + return ll->platformID - rr->platformID; + } else if (ll->encodingID != rr->encodingID) { + return ll->encodingID - rr->encodingID; + } else if (ll->languageID != rr->languageID) { + return ll->languageID - rr->languageID; + } else if (ll->nameID != rr->nameID) { + return ll->nameID - rr->nameID; + } + return 0; +} + + +static sal_uInt32 CheckSum(sal_uInt32 *ptr, sal_uInt32 length) +{ + sal_uInt32 sum = 0; + sal_uInt32 *endptr = ptr + ((length + 3) & (sal_uInt32) ~3) / 4; + + while (ptr < endptr) sum += *ptr++; + + return sum; +} + +_inline void *smalloc(sal_uInt32 size) +{ + void *res = malloc(size); + assert(res != 0); + return res; +} + +_inline void *scalloc(sal_uInt32 n, sal_uInt32 size) +{ + void *res = calloc(n, size); + assert(res != 0); + return res; +} + +/* + * Public functions + */ + +void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this) +{ + TrueTypeCreator* ptr = (TrueTypeCreator*)smalloc(sizeof(TrueTypeCreator)); + + ptr->tables = listNewEmpty(); + listSetElementDtor(ptr->tables, (list_destructor)TrueTypeTableDispose); + + ptr->tag = tag; + + *_this = ptr; +} + +int AddTable(TrueTypeCreator *_this, TrueTypeTable *table) +{ + if (table != 0) { + listAppend(_this->tables, table); + } + return SF_OK; +} + +void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag) +{ + int done = 0; + + if (listCount(_this->tables)) { + listToFirst(_this->tables); + do { + if (((TrueTypeTable *) listCurrent(_this->tables))->tag == tag) { + listRemove(_this->tables); + } else { + if (listNext(_this->tables)) { + done = 1; + } + } + } while (!done); + } +} + +static void ProcessTables(TrueTypeCreator *); + +int StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length) +{ + sal_uInt16 numTables, searchRange=1, entrySelector=0, rangeShift; + sal_uInt32 s, offset, checkSumAdjustment = 0; + sal_uInt32 *p; + int i=0, n; + sal_uInt8 *head = NULL; /* saved pointer to the head table data for checkSumAdjustment calculation */ + + if ((n = listCount(_this->tables)) == 0) return SF_TTFORMAT; + + ProcessTables(_this); + + /* ProcessTables() adds 'loca' and 'hmtx' */ + + n = listCount(_this->tables); + numTables = (sal_uInt16) n; + + + TableEntry* te = (TableEntry*)scalloc(n, sizeof(TableEntry)); + + listToFirst(_this->tables); + for (i = 0; i < n; i++) { + GetRawData((TrueTypeTable *) listCurrent(_this->tables), &te[i].data, &te[i].length, &te[i].tag); + listNext(_this->tables); + } + + qsort(te, n, sizeof(TableEntry), TableEntryCompareF); + + do { + searchRange *= 2; + entrySelector++; + } while (searchRange <= numTables); + + searchRange *= 8; + entrySelector--; + rangeShift = numTables * 16 - searchRange; + + s = offset = 12 + 16 * n; + + for (i = 0; i < n; i++) { + s += (te[i].length + 3) & (sal_uInt32) ~3; + /* if ((te[i].length & 3) != 0) s += (4 - (te[i].length & 3)) & 3; */ + } + + sal_uInt8* ttf = (sal_uInt8*)smalloc(s); + + /* Offset Table */ + PutUInt32(_this->tag, ttf, 0, 1); + PutUInt16(numTables, ttf, 4, 1); + PutUInt16(searchRange, ttf, 6, 1); + PutUInt16(entrySelector, ttf, 8, 1); + PutUInt16(rangeShift, ttf, 10, 1); + + /* Table Directory */ + for (i = 0; i < n; i++) { + PutUInt32(te[i].tag, ttf + 12, 16 * i, 1); + PutUInt32(CheckSum((sal_uInt32 *) te[i].data, te[i].length), ttf + 12, 16 * i + 4, 1); + PutUInt32(offset, ttf + 12, 16 * i + 8, 1); + PutUInt32(te[i].length, ttf + 12, 16 * i + 12, 1); + + if (te[i].tag == T_head) { + head = ttf + offset; + } + + memcpy(ttf+offset, te[i].data, (te[i].length + 3) & (sal_uInt32) ~3 ); + offset += (te[i].length + 3) & (sal_uInt32) ~3; + /* if ((te[i].length & 3) != 0) offset += (4 - (te[i].length & 3)) & 3; */ + } + + free(te); + + p = (sal_uInt32 *) ttf; + for (i = 0; i < (int)s / 4; i++) checkSumAdjustment += p[i]; + PutUInt32(0xB1B0AFBA - checkSumAdjustment, head, 8, 1); + + *ptr = ttf; + *length = s; + + return SF_OK; +} + +int StreamToFile(TrueTypeCreator *_this, const char* fname) +{ + sal_uInt8 *ptr; + sal_uInt32 length; + int r; + FILE* fd; + + if ((r = StreamToMemory(_this, &ptr, &length)) != SF_OK) return r; + if (!fname) return SF_BADFILE; + if ((fd = fopen(fname, "wb")) == NULL) return SF_BADFILE; + + if (fwrite(ptr, 1, length, fd) != length) { + r = SF_FILEIO; + } else { + r = SF_OK; + } + + fclose(fd); + free(ptr); + return r; +} + + + +/* + * TrueTypeTable private methods + */ + +#define TABLESIZE_head 54 +#define TABLESIZE_hhea 36 +#define TABLESIZE_maxp 32 + + + +/* Table data points to + * -------------------------------------------- + * generic tdata_generic struct + * 'head' TABLESIZE_head bytes of memory + * 'hhea' TABLESIZE_hhea bytes of memory + * 'loca' tdata_loca struct + * 'maxp' TABLESIZE_maxp bytes of memory + * 'glyf' list of GlyphData structs (defined in sft.h) + * 'name' list of NameRecord structs (defined in sft.h) + * 'post' tdata_post struct + * + */ + + +#define CMAP_SUBTABLE_INIT 10 +#define CMAP_SUBTABLE_INCR 10 +#define CMAP_PAIR_INIT 500 +#define CMAP_PAIR_INCR 500 + +typedef struct { + sal_uInt32 id; /* subtable ID (platform/encoding ID) */ + sal_uInt32 n; /* number of used translation pairs */ + sal_uInt32 m; /* number of allocated translation pairs */ + sal_uInt32 *xc; /* character array */ + sal_uInt32 *xg; /* glyph array */ +} CmapSubTable; + +typedef struct { + sal_uInt32 n; /* number of used CMAP sub-tables */ + sal_uInt32 m; /* number of allocated CMAP sub-tables */ + CmapSubTable *s; /* sotred array of sub-tables */ +} table_cmap; + +typedef struct { + sal_uInt32 tag; + sal_uInt32 nbytes; + sal_uInt8 *ptr; +} tdata_generic; + +typedef struct { + sal_uInt32 nbytes; /* number of bytes in loca table */ + sal_uInt8 *ptr; /* pointer to the data */ +} tdata_loca; + +typedef struct { + sal_uInt32 format; + sal_uInt32 italicAngle; + sal_Int16 underlinePosition; + sal_Int16 underlineThickness; + sal_uInt32 isFixedPitch; + void *ptr; /* format-specific pointer */ +} tdata_post; + + +/* allocate memory for a TT table */ +static sal_uInt8 *ttmalloc(sal_uInt32 nbytes) +{ + sal_uInt32 n; + + n = (nbytes + 3) & (sal_uInt32) ~3; + sal_uInt8* res = (sal_uInt8*)malloc(n); + assert(res != 0); + memset(res, 0, n); + + return res; +} + +static void FreeGlyphData(void *ptr) +{ + GlyphData *p = (GlyphData *) ptr; + if (p->ptr) free(p->ptr); + free(p); +} + +static void TrueTypeTableDispose_generic(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) { + tdata_generic *pdata = (tdata_generic *) _this->data; + if (pdata->nbytes) free(pdata->ptr); + free(_this->data); + } + free(_this); + } +} + +static void TrueTypeTableDispose_head(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) free(_this->data); + free(_this); + } +} + +static void TrueTypeTableDispose_hhea(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) free(_this->data); + free(_this); + } +} + +static void TrueTypeTableDispose_loca(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) { + tdata_loca *p = (tdata_loca *) _this->data; + if (p->ptr) free(p->ptr); + free(_this->data); + } + free(_this); + } +} + +static void TrueTypeTableDispose_maxp(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) free(_this->data); + free(_this); + } +} + +static void TrueTypeTableDispose_glyf(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) listDispose((list) _this->data); + free(_this); + } +} + +static void TrueTypeTableDispose_cmap(TrueTypeTable *_this) +{ + table_cmap *t; + CmapSubTable *s; + sal_uInt32 i; + + if (_this) { + t = (table_cmap *) _this->data; + if (t) { + s = t->s; + if (s) { + for (i = 0; i < t->m; i++) { + if (s[i].xc) free(s[i].xc); + if (s[i].xg) free(s[i].xg); + } + free(s); + } + free(t); + } + free(_this); + } +} + +static void TrueTypeTableDispose_name(TrueTypeTable *_this) +{ + if (_this) { + if (_this->data) listDispose((list) _this->data); + free(_this); + } +} + +static void TrueTypeTableDispose_post(TrueTypeTable *_this) +{ + if (_this) { + tdata_post *p = (tdata_post *) _this->data; + if (p) { + if (p->format == 0x00030000) { + /* do nothing */ + } else { + fprintf(stderr, "Unsupported format of a 'post' table: %08X.\n", (int)p->format); + } + free(p); + } + free(_this); + } +} + +/* destructor vtable */ + +static struct { + sal_uInt32 tag; + void (*f)(TrueTypeTable *); +} vtable1[] = +{ + {0, TrueTypeTableDispose_generic}, + {T_head, TrueTypeTableDispose_head}, + {T_hhea, TrueTypeTableDispose_hhea}, + {T_loca, TrueTypeTableDispose_loca}, + {T_maxp, TrueTypeTableDispose_maxp}, + {T_glyf, TrueTypeTableDispose_glyf}, + {T_cmap, TrueTypeTableDispose_cmap}, + {T_name, TrueTypeTableDispose_name}, + {T_post, TrueTypeTableDispose_post} + +}; + +static int GetRawData_generic(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + assert(_this != 0); + assert(_this->data != 0); + + *ptr = ((tdata_generic *) _this->data)->ptr; + *len = ((tdata_generic *) _this->data)->nbytes; + *tag = ((tdata_generic *) _this->data)->tag; + + return TTCR_OK; +} + + +static int GetRawData_head(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + *len = TABLESIZE_head; + *ptr = (sal_uInt8 *) _this->data; + *tag = T_head; + + return TTCR_OK; +} + +static int GetRawData_hhea(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + *len = TABLESIZE_hhea; + *ptr = (sal_uInt8 *) _this->data; + *tag = T_hhea; + + return TTCR_OK; +} + +static int GetRawData_loca(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + tdata_loca *p; + + assert(_this->data != 0); + + p = (tdata_loca *) _this->data; + + if (p->nbytes == 0) return TTCR_ZEROGLYPHS; + + *ptr = p->ptr; + *len = p->nbytes; + *tag = T_loca; + + return TTCR_OK; +} + +static int GetRawData_maxp(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + *len = TABLESIZE_maxp; + *ptr = (sal_uInt8 *) _this->data; + *tag = T_maxp; + + return TTCR_OK; +} + +static int GetRawData_glyf(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + sal_uInt32 n, nbytes = 0; + list l = (list) _this->data; + /* sal_uInt16 curID = 0; */ /* to check if glyph IDs are sequential and start from zero */ + sal_uInt8 *p; + + *ptr = 0; + *len = 0; + *tag = 0; + + if (listCount(l) == 0) return TTCR_ZEROGLYPHS; + + listToFirst(l); + do { + /* if (((GlyphData *) listCurrent(l))->glyphID != curID++) return TTCR_GLYPHSEQ; */ + nbytes += ((GlyphData *) listCurrent(l))->nbytes; + } while (listNext(l)); + + p = _this->rawdata = ttmalloc(nbytes); + + listToFirst(l); + do { + n = ((GlyphData *) listCurrent(l))->nbytes; + if (n != 0) { + memcpy(p, ((GlyphData *) listCurrent(l))->ptr, n); + p += n; + } + } while (listNext(l)); + + *len = nbytes; + *ptr = _this->rawdata; + *tag = T_glyf; + + return TTCR_OK; +} + +/* cmap packers */ +static sal_uInt8 *PackCmapType0(CmapSubTable *s, sal_uInt32 *length) +{ + sal_uInt8* ptr = (sal_uInt8*)smalloc(262); + sal_uInt8 *p = ptr + 6; + sal_uInt32 i, j; + sal_uInt16 g; + + PutUInt16(0, ptr, 0, 1); + PutUInt16(262, ptr, 2, 1); + PutUInt16(0, ptr, 4, 1); + + for (i = 0; i < 256; i++) { + g = 0; + for (j = 0; j < s->n; j++) { + if (s->xc[j] == i) { + g = (sal_uInt16) s->xg[j]; + } + } + p[i] = (sal_uInt8) g; + } + *length = 262; + return ptr; +} + +static sal_uInt8 *PackCmapType6(CmapSubTable *s, sal_uInt32 *length) +{ + sal_uInt8* ptr = (sal_uInt8*)smalloc(s->n*2 + 10); + sal_uInt8 *p = ptr + 10; + sal_uInt32 i, j; + sal_uInt16 g; + + PutUInt16(6, ptr, 0, 1); + PutUInt16((sal_uInt16)(s->n*2+10), ptr, 2, 1); + PutUInt16(0, ptr, 4, 1); + PutUInt16(0, ptr, 6, 1); + PutUInt16((sal_uInt16)(s->n), ptr, 8, 1 ); + + for (i = 0; i < s->n; i++) { + g = 0; + for (j = 0; j < s->n; j++) { + if (s->xc[j] == i) { + g = (sal_uInt16) s->xg[j]; + } + } + PutUInt16( g, p, 2*i, 1 ); + } + *length = s->n*2+10; + return ptr; +} + + + +/* XXX it only handles Format 0 encoding tables */ +static sal_uInt8 *PackCmap(CmapSubTable *s, sal_uInt32 *length) +{ + if( s->xg[s->n-1] > 0xff ) + return PackCmapType6(s, length); + else + return PackCmapType0(s, length); +} + +static int GetRawData_cmap(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + table_cmap *t; + sal_uInt32 i; + sal_uInt32 tlen = 0; + sal_uInt32 l; + sal_uInt32 cmapsize; + sal_uInt8 *cmap; + sal_uInt32 coffset; + + assert(_this != 0); + t = (table_cmap *) _this->data; + assert(t != 0); + assert(t->n != 0); + + sal_uInt8** subtables = (sal_uInt8**)scalloc(t->n, sizeof(sal_uInt8 *)); + sal_uInt32* sizes = (sal_uInt32*)scalloc(t->n, sizeof(sal_uInt32)); + + for (i = 0; i < t->n; i++) { + subtables[i] = PackCmap(t->s+i, &l); + sizes[i] = l; + tlen += l; + } + + cmapsize = tlen + 4 + 8 * t->n; + _this->rawdata = cmap = ttmalloc(cmapsize); + + PutUInt16(0, cmap, 0, 1); + PutUInt16((sal_uInt16)t->n, cmap, 2, 1); + coffset = 4 + t->n * 8; + + for (i = 0; i < t->n; i++) { + PutUInt16((sal_uInt16)(t->s[i].id >> 16), cmap + 4, i * 8, 1); + PutUInt16((sal_uInt16)(t->s[i].id & 0xFF), cmap + 4, 2 + i * 8, 1); + PutUInt32(coffset, cmap + 4, 4 + i * 8, 1); + memcpy(cmap + coffset, subtables[i], sizes[i]); + free(subtables[i]); + coffset += sizes[i]; + } + + free(subtables); + free(sizes); + + *ptr = cmap; + *len = cmapsize; + *tag = T_cmap; + + return TTCR_OK; +} + + +static int GetRawData_name(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + list l; + sal_Int16 i=0, n; /* number of Name Records */ + int stringLen = 0; + sal_uInt8 *p1, *p2; + + *ptr = 0; + *len = 0; + *tag = 0; + + assert(_this != 0); + l = (list) _this->data; + assert(l != 0); + + if ((n = (sal_Int16)listCount(l)) == 0) return TTCR_NONAMES; + + NameRecord* nr = (NameRecord*)scalloc(n, sizeof(NameRecord)); + + listToFirst(l); + + do { + memcpy(nr+i, listCurrent(l), sizeof(NameRecord)); + stringLen += nr[i].slen; + i++; + } while (listNext(l)); + + if (stringLen > 65535) { + free(nr); + return TTCR_NAMETOOLONG; + } + + qsort(nr, n, sizeof(NameRecord), NameRecordCompareF); + + int nameLen = stringLen + 12 * n + 6; + sal_uInt8* name = (sal_uInt8*)ttmalloc(nameLen); + + PutUInt16(0, name, 0, 1); + PutUInt16(n, name, 2, 1); + PutUInt16((sal_uInt16)(6 + 12 * n), name, 4, 1); + + p1 = name + 6; + p2 = p1 + 12 * n; + + for (i = 0; i < n; i++) { + PutUInt16(nr[i].platformID, p1, 0, 1); + PutUInt16(nr[i].encodingID, p1, 2, 1); + PutUInt16(nr[i].languageID, p1, 4, 1); + PutUInt16(nr[i].nameID, p1, 6, 1); + PutUInt16(nr[i].slen, p1, 8, 1); + PutUInt16((sal_uInt16)(p2 - (name + 6 + 12 * n)), p1, 10, 1); + memcpy(p2, nr[i].sptr, nr[i].slen); + /* {int j; for(j=0; jrawdata = name; + + *ptr = name; + *len = (sal_uInt16)nameLen; + *tag = T_name; + + /*{int j; for(j=0; jdata; + sal_uInt8 *post = 0; + sal_uInt32 postLen = 0; + int ret; + + if (_this->rawdata) free(_this->rawdata); + + if (p->format == 0x00030000) { + postLen = 32; + post = ttmalloc(postLen); + PutUInt32(0x00030000, post, 0, 1); + PutUInt32(p->italicAngle, post, 4, 1); + PutUInt16(p->underlinePosition, post, 8, 1); + PutUInt16(p->underlineThickness, post, 10, 1); + PutUInt16((sal_uInt16)p->isFixedPitch, post, 12, 1); + ret = TTCR_OK; + } else { + fprintf(stderr, "Unrecognized format of a post table: %08X.\n", (int)p->format); + ret = TTCR_POSTFORMAT; + } + + *ptr = _this->rawdata = post; + *len = postLen; + *tag = T_post; + + return ret; +} + + + + + +static struct { + sal_uInt32 tag; + int (*f)(TrueTypeTable *, sal_uInt8 **, sal_uInt32 *, sal_uInt32 *); +} vtable2[] = +{ + {0, GetRawData_generic}, + {T_head, GetRawData_head}, + {T_hhea, GetRawData_hhea}, + {T_loca, GetRawData_loca}, + {T_maxp, GetRawData_maxp}, + {T_glyf, GetRawData_glyf}, + {T_cmap, GetRawData_cmap}, + {T_name, GetRawData_name}, + {T_post, GetRawData_post} + + +}; + +/* + * TrueTypeTable public methods + */ + +/* Note: Type42 fonts only need these tables: + * head, hhea, loca, maxp, cvt, prep, glyf, hmtx, fpgm + * + * Microsoft required tables + * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post, OS/2 + * + * Apple required tables + * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post + * + */ + +TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag, + sal_uInt32 nbytes, + sal_uInt8 *ptr) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + tdata_generic* pdata = (tdata_generic*)smalloc(sizeof(tdata_generic)); + pdata->nbytes = nbytes; + pdata->tag = tag; + if (nbytes) { + pdata->ptr = ttmalloc(nbytes); + memcpy(pdata->ptr, ptr, nbytes); + } else { + pdata->ptr = 0; + } + + table->tag = 0; + table->data = pdata; + table->rawdata = 0; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision, + sal_uInt16 flags, + sal_uInt16 unitsPerEm, + sal_uInt8 *created, + sal_uInt16 macStyle, + sal_uInt16 lowestRecPPEM, + sal_Int16 fontDirectionHint) +{ + assert(created != 0); + + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + sal_uInt8* ptr = (sal_uInt8*)ttmalloc(TABLESIZE_head); + + + PutUInt32(0x00010000, ptr, 0, 1); /* version */ + PutUInt32(fontRevision, ptr, 4, 1); + PutUInt32(0x5F0F3CF5, ptr, 12, 1); /* magic number */ + PutUInt16(flags, ptr, 16, 1); + PutUInt16(unitsPerEm, ptr, 18, 1); + memcpy(ptr+20, created, 8); /* Created Long Date */ + memset(ptr+28, 0, 8); /* Modified Long Date */ + PutUInt16(macStyle, ptr, 44, 1); + PutUInt16(lowestRecPPEM, ptr, 46, 1); + PutUInt16(fontDirectionHint, ptr, 48, 1); + PutUInt16(0, ptr, 52, 1); /* glyph data format: 0 */ + + table->data = (void *) ptr; + table->tag = T_head; + table->rawdata = 0; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender, + sal_Int16 descender, + sal_Int16 linegap, + sal_Int16 caretSlopeRise, + sal_Int16 caretSlopeRun) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + sal_uInt8* ptr = (sal_uInt8*)ttmalloc(TABLESIZE_hhea); + + PutUInt32(0x00010000, ptr, 0, 1); /* version */ + PutUInt16(ascender, ptr, 4, 1); + PutUInt16(descender, ptr, 6, 1); + PutUInt16(linegap, ptr, 8, 1); + PutUInt16(caretSlopeRise, ptr, 18, 1); + PutUInt16(caretSlopeRun, ptr, 20, 1); + PutUInt16(0, ptr, 22, 1); /* reserved 1 */ + PutUInt16(0, ptr, 24, 1); /* reserved 2 */ + PutUInt16(0, ptr, 26, 1); /* reserved 3 */ + PutUInt16(0, ptr, 28, 1); /* reserved 4 */ + PutUInt16(0, ptr, 30, 1); /* reserved 5 */ + PutUInt16(0, ptr, 32, 1); /* metricDataFormat */ + + table->data = (void *) ptr; + table->tag = T_hhea; + table->rawdata = 0; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_loca(void) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + table->data = smalloc(sizeof(tdata_loca)); + + ((tdata_loca *)table->data)->nbytes = 0; + ((tdata_loca *)table->data)->ptr = 0; + + table->tag = T_loca; + table->rawdata = 0; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_maxp(sal_uInt8 *maxp, int size) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + table->data = ttmalloc(TABLESIZE_maxp); + + if (maxp && size == TABLESIZE_maxp) { + memcpy(table->data, maxp, TABLESIZE_maxp); + } + + table->tag = T_maxp; + table->rawdata = 0; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_glyf(void) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + list l = listNewEmpty(); + + assert(l != 0); + + listSetElementDtor(l, (list_destructor)FreeGlyphData); + + table->data = l; + table->rawdata = 0; + table->tag = T_glyf; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_cmap(void) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + table_cmap* cmap = (table_cmap*)smalloc(sizeof(table_cmap)); + + cmap->n = 0; + cmap->m = CMAP_SUBTABLE_INIT; + cmap->s = (CmapSubTable *) scalloc(CMAP_SUBTABLE_INIT, sizeof(CmapSubTable)); + memset(cmap->s, 0, sizeof(CmapSubTable) * CMAP_SUBTABLE_INIT); + + table->data = (table_cmap *) cmap; + + table->rawdata = 0; + table->tag = T_cmap; + + return table; +} + +static void DisposeNameRecord(void *ptr) +{ + if (ptr != 0) { + NameRecord *nr = (NameRecord *) ptr; + if (nr->sptr) free(nr->sptr); + free(ptr); + } +} + +static NameRecord* NameRecordNewCopy(NameRecord *nr) +{ + NameRecord* p = (NameRecord*)smalloc(sizeof(NameRecord)); + + memcpy(p, nr, sizeof(NameRecord)); + + if (p->slen) { + p->sptr = (sal_uInt8*)smalloc(p->slen); + memcpy(p->sptr, nr->sptr, p->slen); + } + + return p; +} + +TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord *nr) +{ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + list l = listNewEmpty(); + + assert(l != 0); + + listSetElementDtor(l, (list_destructor)DisposeNameRecord); + + if (n != 0) { + int i; + for (i = 0; i < n; i++) { + listAppend(l, NameRecordNewCopy(nr+i)); + } + } + + table->data = l; + table->rawdata = 0; + table->tag = T_name; + + return table; +} + +TrueTypeTable *TrueTypeTableNew_post(sal_uInt32 format, + sal_uInt32 italicAngle, + sal_Int16 underlinePosition, + sal_Int16 underlineThickness, + sal_uInt32 isFixedPitch) +{ + assert(format == 0x00030000); /* Only format 3.0 is supported at this time */ + TrueTypeTable* table = (TrueTypeTable*)smalloc(sizeof(TrueTypeTable)); + tdata_post* post = (tdata_post*)smalloc(sizeof(tdata_post)); + + post->format = format; + post->italicAngle = italicAngle; + post->underlinePosition = underlinePosition; + post->underlineThickness = underlineThickness; + post->isFixedPitch = isFixedPitch; + post->ptr = 0; + + table->data = post; + table->rawdata = 0; + table->tag = T_post; + + return table; +} + +int GetRawData(TrueTypeTable *_this, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag) +{ + /* XXX do a binary search */ + unsigned int i; + + assert(_this != 0); + assert(ptr != 0); + assert(len != 0); + assert(tag != 0); + + *ptr = 0; *len = 0; *tag = 0; + + if (_this->rawdata) { + free(_this->rawdata); + _this->rawdata = 0; + } + + for(i=0; i < sizeof(vtable2)/sizeof(*vtable2); i++) { + if (_this->tag == vtable2[i].tag) { + return vtable2[i].f(_this, ptr, len, tag); + } + } + + assert(!"Unknwon TrueType table.\n"); + return TTCR_UNKNOWN; +} + +void cmapAdd(TrueTypeTable *table, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g) +{ + sal_uInt32 i, found; + table_cmap *t; + CmapSubTable *s; + + assert(table != 0); + assert(table->tag == T_cmap); + t = (table_cmap *) table->data; assert(t != 0); + s = t->s; assert(s != 0); + + found = 0; + + for (i = 0; i < t->n; i++) { + if (s[i].id == id) { + found = 1; + break; + } + } + + if (!found) { + if (t->n == t->m) { + CmapSubTable* tmp = (CmapSubTable*)scalloc(t->m + CMAP_SUBTABLE_INCR, sizeof(CmapSubTable)); + memset(tmp, 0, t->m + CMAP_SUBTABLE_INCR * sizeof(CmapSubTable)); + memcpy(tmp, s, sizeof(CmapSubTable) * t->m); + t->m += CMAP_SUBTABLE_INCR; + free(s); + s = tmp; + t->s = s; + } + + for (i = 0; i < t->n; i++) { + if (s[i].id > id) break; + } + + if (i < t->n) { + memmove(s+i+1, s+i, t->n-i); + } + + t->n++; + + s[i].id = id; + s[i].n = 0; + s[i].m = CMAP_PAIR_INIT; + s[i].xc = (sal_uInt32*)scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)); + s[i].xg = (sal_uInt32*)scalloc(CMAP_PAIR_INIT, sizeof(sal_uInt32)); + } + + if (s[i].n == s[i].m) { + sal_uInt32* tmp1 = (sal_uInt32*)scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)); + sal_uInt32* tmp2 = (sal_uInt32*)scalloc(s[i].m + CMAP_PAIR_INCR, sizeof(sal_uInt32)); + assert(tmp1 != 0); + assert(tmp2 != 0); + memcpy(tmp1, s[i].xc, sizeof(sal_uInt32) * s[i].m); + memcpy(tmp2, s[i].xg, sizeof(sal_uInt32) * s[i].m); + s[i].m += CMAP_PAIR_INCR; + free(s[i].xc); + free(s[i].xg); + s[i].xc = tmp1; + s[i].xg = tmp2; + } + + s[i].xc[s[i].n] = c; + s[i].xg[s[i].n] = g; + s[i].n++; +} + +sal_uInt32 glyfAdd(TrueTypeTable *table, GlyphData *glyphdata, TrueTypeFont *fnt) +{ + list l; + sal_uInt32 currentID; + int ret, n, ncomponents; + GlyphData *gd; + + assert(table != 0); + assert(table->tag == T_glyf); + + if (!glyphdata) return (sal_uInt32)~0; + + std::vector< sal_uInt32 > glyphlist; + + ncomponents = GetTTGlyphComponents(fnt, glyphdata->glyphID, glyphlist); + + l = (list) table->data; + if (listCount(l) > 0) { + listToLast(l); + ret = n = ((GlyphData *) listCurrent(l))->newID + 1; + } else { + ret = n = 0; + } + glyphdata->newID = n++; + listAppend(l, glyphdata); + + if (ncomponents > 1 && glyphlist.size() > 1 ) + { + std::vector< sal_uInt32 >::const_iterator it = glyphlist.begin(); + ++it; + /* glyphData->glyphID is always the first glyph on the list */ + do + { + int found = 0; + currentID = *it; + /* XXX expensive! should be rewritten with sorted arrays! */ + listToFirst(l); + do { + if (((GlyphData *) listCurrent(l))->glyphID == currentID) { + found = 1; + break; + } + } while (listNext(l)); + + if (!found) { + gd = GetTTRawGlyphData(fnt, currentID); + gd->newID = n++; + listAppend(l, gd); + } + } while( ++it != glyphlist.end() ); + } + + return ret; +} + +sal_uInt32 glyfCount(const TrueTypeTable *table) +{ + assert(table != 0); + assert(table->tag == T_glyf); + return listCount((list) table->data); +} + + +void nameAdd(TrueTypeTable *table, NameRecord *nr) +{ + list l; + + assert(table != 0); + assert(table->tag == T_name); + + l = (list) table->data; + + listAppend(l, NameRecordNewCopy(nr)); +} + +static TrueTypeTable *FindTable(TrueTypeCreator *tt, sal_uInt32 tag) +{ + if (listIsEmpty(tt->tables)) return 0; + + listToFirst(tt->tables); + + do { + if (((TrueTypeTable *) listCurrent(tt->tables))->tag == tag) { + return (TrueTypeTable*)listCurrent(tt->tables); + } + } while (listNext(tt->tables)); + + return 0; +} + +/* This function processes all the tables and synchronizes them before creating + * the output TrueType stream. + * + * *** It adds two TrueType tables to the font: 'loca' and 'hmtx' *** + * + * It does: + * + * - Re-numbers glyph IDs and creates 'glyf', 'loca', and 'hmtx' tables. + * - Calculates xMin, yMin, xMax, and yMax and stores values in 'head' table. + * - Stores indexToLocFormat in 'head' + * - updates 'maxp' table + * - Calculates advanceWidthMax, minLSB, minRSB, xMaxExtent and numberOfHMetrics + * in 'hhea' table + * + */ +static void ProcessTables(TrueTypeCreator *tt) +{ + TrueTypeTable *glyf, *loca, *head, *maxp, *hhea; + list glyphlist; + sal_uInt32 nGlyphs, locaLen = 0, glyfLen = 0; + sal_Int16 xMin = 0, yMin = 0, xMax = 0, yMax = 0; + sal_uInt32 i = 0; + sal_Int16 indexToLocFormat; + sal_uInt8 *hmtxPtr, *hheaPtr; + sal_uInt32 hmtxSize; + sal_uInt8 *p1, *p2; + sal_uInt16 maxPoints = 0, maxContours = 0, maxCompositePoints = 0, maxCompositeContours = 0; + int nlsb = 0; + sal_uInt32 *gid; /* array of old glyphIDs */ + + glyf = FindTable(tt, T_glyf); + glyphlist = (list) glyf->data; + nGlyphs = listCount(glyphlist); + assert(nGlyphs != 0); + gid = (sal_uInt32*)scalloc(nGlyphs, sizeof(sal_uInt32)); + + RemoveTable(tt, T_loca); + RemoveTable(tt, T_hmtx); + + /* XXX Need to make sure that composite glyphs do not break during glyph renumbering */ + + listToFirst(glyphlist); + do { + GlyphData *gd = (GlyphData *) listCurrent(glyphlist); + sal_Int16 z; + glyfLen += gd->nbytes; + /* XXX if (gd->nbytes & 1) glyfLen++; */ + + + assert(gd->newID == i); + gid[i++] = gd->glyphID; + /* gd->glyphID = i++; */ + + /* printf("IDs: %d %d.\n", gd->glyphID, gd->newID); */ + + if (gd->nbytes != 0) { + z = GetInt16(gd->ptr, 2, 1); + if (z < xMin) xMin = z; + + z = GetInt16(gd->ptr, 4, 1); + if (z < yMin) yMin = z; + + z = GetInt16(gd->ptr, 6, 1); + if (z > xMax) xMax = z; + + z = GetInt16(gd->ptr, 8, 1); + if (z > yMax) yMax = z; + } + + if (gd->compflag == 0) { /* non-composite glyph */ + if (gd->npoints > maxPoints) maxPoints = gd->npoints; + if (gd->ncontours > maxContours) maxContours = gd->ncontours; + } else { /* composite glyph */ + if (gd->npoints > maxCompositePoints) maxCompositePoints = gd->npoints; + if (gd->ncontours > maxCompositeContours) maxCompositeContours = gd->ncontours; + } + + } while (listNext(glyphlist)); + + indexToLocFormat = (glyfLen / 2 > 0xFFFF) ? 1 : 0; + locaLen = indexToLocFormat ? (nGlyphs + 1) << 2 : (nGlyphs + 1) << 1; + + sal_uInt8* glyfPtr = ttmalloc(glyfLen); + sal_uInt8* locaPtr = ttmalloc(locaLen); + TTSimpleGlyphMetrics* met = (TTSimpleGlyphMetrics*)scalloc(nGlyphs, sizeof(TTSimpleGlyphMetrics)); + i = 0; + + listToFirst(glyphlist); + p1 = glyfPtr; + p2 = locaPtr; + do { + GlyphData *gd = (GlyphData *) listCurrent(glyphlist); + + if (gd->compflag) { /* re-number all components */ + sal_uInt16 flags, index; + sal_uInt8 *ptr = gd->ptr + 10; + do { + sal_uInt32 j; + flags = GetUInt16(ptr, 0, 1); + index = GetUInt16(ptr, 2, 1); + /* XXX use the sorted array of old to new glyphID mapping and do a binary search */ + for (j = 0; j < nGlyphs; j++) { + if (gid[j] == index) { + break; + } + } + /* printf("X: %d -> %d.\n", index, j); */ + + PutUInt16((sal_uInt16) j, ptr, 2, 1); + + ptr += 4; + + if (flags & ARG_1_AND_2_ARE_WORDS) { + ptr += 4; + } else { + ptr += 2; + } + + if (flags & WE_HAVE_A_SCALE) { + ptr += 2; + } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { + ptr += 4; + } else if (flags & WE_HAVE_A_TWO_BY_TWO) { + ptr += 8; + } + } while (flags & MORE_COMPONENTS); + } + + if (gd->nbytes != 0) { + memcpy(p1, gd->ptr, gd->nbytes); + } + if (indexToLocFormat == 1) { + PutUInt32(p1 - glyfPtr, p2, 0, 1); + p2 += 4; + } else { + PutUInt16((sal_uInt16)((p1 - glyfPtr) >> 1), p2, 0, 1); + p2 += 2; + } + p1 += gd->nbytes; + + /* fill the array of metrics */ + met[i].adv = gd->aw; + met[i].sb = gd->lsb; + i++; + } while (listNext(glyphlist)); + + free(gid); + + if (indexToLocFormat == 1) { + PutUInt32(p1 - glyfPtr, p2, 0, 1); + } else { + PutUInt16((sal_uInt16)((p1 - glyfPtr) >> 1), p2, 0, 1); + } + + glyf->rawdata = glyfPtr; + + loca = TrueTypeTableNew_loca(); assert(loca != 0); + ((tdata_loca *) loca->data)->ptr = locaPtr; + ((tdata_loca *) loca->data)->nbytes = locaLen; + + AddTable(tt, loca); + + head = FindTable(tt, T_head); + sal_uInt8* const pHeadData = (sal_uInt8*)head->data; + PutInt16(xMin, pHeadData, 36, 1); + PutInt16(yMin, pHeadData, 38, 1); + PutInt16(xMax, pHeadData, 40, 1); + PutInt16(yMax, pHeadData, 42, 1); + PutInt16(indexToLocFormat, pHeadData, 50, 1); + + maxp = FindTable(tt, T_maxp); + + sal_uInt8* const pMaxpData = (sal_uInt8*)maxp->data; + PutUInt16((sal_uInt16)nGlyphs, pMaxpData, 4, 1); + PutUInt16(maxPoints, pMaxpData, 6, 1); + PutUInt16(maxContours, pMaxpData, 8, 1); + PutUInt16(maxCompositePoints, pMaxpData, 10, 1); + PutUInt16(maxCompositeContours, pMaxpData, 12, 1); + +#if 0 + /* XXX do not overwrite the existing data. Fix: re-calculate these numbers here */ + PutUInt16(2, maxp->data, 14, 1); /* maxZones is always 2 */ + PutUInt16(0, maxp->data, 16, 1); /* maxTwilightPoints */ + PutUInt16(0, maxp->data, 18, 1); /* maxStorage */ + PutUInt16(0, maxp->data, 20, 1); /* maxFunctionDefs */ + PutUint16(0, maxp->data, 22, 1); /* maxInstructionDefs */ + PutUint16(0, maxp->data, 24, 1); /* maxStackElements */ + PutUint16(0, maxp->data, 26, 1); /* maxSizeOfInstructions */ + PutUint16(0, maxp->data, 28, 1); /* maxComponentElements */ + PutUint16(0, maxp->data, 30, 1); /* maxComponentDepth */ +#endif + + /* + * Generate an htmx table and update hhea table + */ + hhea = FindTable(tt, T_hhea); assert(hhea != 0); + hheaPtr = (sal_uInt8 *) hhea->data; + if (nGlyphs > 2) { + for (i = nGlyphs - 1; i > 0; i--) { + if (met[i].adv != met[i-1].adv) break; + } + nlsb = nGlyphs - 1 - i; + } + hmtxSize = (nGlyphs - nlsb) * 4 + nlsb * 2; + hmtxPtr = ttmalloc(hmtxSize); + p1 = hmtxPtr; + + for (i = 0; i < nGlyphs; i++) { + if (i < nGlyphs - nlsb) { + PutUInt16(met[i].adv, p1, 0, 1); + PutUInt16(met[i].sb, p1, 2, 1); + p1 += 4; + } else { + PutUInt16(met[i].sb, p1, 0, 1); + p1 += 2; + } + } + + AddTable(tt, TrueTypeTableNew(T_hmtx, hmtxSize, hmtxPtr)); + PutUInt16((sal_uInt16)(nGlyphs - nlsb), hheaPtr, 34, 1); + free(hmtxPtr); + free(met); +} + +} // namespace vcl + +extern "C" +{ + /** + * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it. + */ + void TrueTypeCreatorDispose(vcl::TrueTypeCreator *_this) + { + listDispose(_this->tables); + free(_this); + } + + + /** + * Destructor for the TrueTypeTable object. + */ + void TrueTypeTableDispose(vcl::TrueTypeTable *_this) + { + /* XXX do a binary search */ + unsigned int i; + + assert(_this != 0); + + if (_this->rawdata) free(_this->rawdata); + + for(i=0; i < sizeof(vcl::vtable1)/sizeof(*vcl::vtable1); i++) { + if (_this->tag == vcl::vtable1[i].tag) { + vcl::vtable1[i].f(_this); + return; + } + } + assert(!"Unknown TrueType table.\n"); + } +} + + +#ifdef TEST_TTCR +int main(void) +{ + TrueTypeCreator *ttcr; + sal_uInt8 *t1, *t2, *t3, *t4, *t5, *t6, *t7; + + TrueTypeCreatorNewEmpty(mkTag('t','r','u','e'), &ttcr); + + t1 = malloc(1000); memset(t1, 'a', 1000); + t2 = malloc(2000); memset(t2, 'b', 2000); + t3 = malloc(3000); memset(t3, 'c', 3000); + t4 = malloc(4000); memset(t4, 'd', 4000); + t5 = malloc(5000); memset(t5, 'e', 5000); + t6 = malloc(6000); memset(t6, 'f', 6000); + t7 = malloc(7000); memset(t7, 'g', 7000); + + AddTable(ttcr, TrueTypeTableNew(0x6D617870, 1000, t1)); + AddTable(ttcr, TrueTypeTableNew(0x4F532F32, 2000, t2)); + AddTable(ttcr, TrueTypeTableNew(0x636D6170, 3000, t3)); + AddTable(ttcr, TrueTypeTableNew(0x6C6F6361, 4000, t4)); + AddTable(ttcr, TrueTypeTableNew(0x68686561, 5000, t5)); + AddTable(ttcr, TrueTypeTableNew(0x676C7966, 6000, t6)); + AddTable(ttcr, TrueTypeTableNew(0x6B65726E, 7000, t7)); + + free(t1); + free(t2); + free(t3); + free(t4); + free(t5); + free(t6); + free(t7); + + + StreamToFile(ttcr, "ttcrout.ttf"); + + TrueTypeCreatorDispose(ttcr); + return 0; +} +#endif diff --git a/vcl/source/fontsubset/ttcr.h b/vcl/source/fontsubset/ttcr.h deleted file mode 100644 index 95aa1a6c9e99..000000000000 --- a/vcl/source/fontsubset/ttcr.h +++ /dev/null @@ -1,280 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ttcr.h,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: ttcr.h,v 1.4 2008-04-11 10:17:09 rt Exp $ */ - -/** - * - * @file ttcr.h - * @brief TrueType font creator - * @author Alexander Gelfenbain - */ - -#ifndef __TTCR_H -#define __TTCR_H - -#include "sft.h" -#include "list.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - - typedef struct _TrueTypeCreator TrueTypeCreator; - -/* TrueType data types */ - typedef struct { - sal_uInt16 aw; - sal_Int16 lsb; - } longHorMetrics; - -/* A generic base class for all TrueType tables */ - typedef struct { - sal_uInt32 tag; /* table tag */ - sal_uInt8 *rawdata; /* raw data allocated by GetRawData_*() */ - void *data; /* table specific data */ - } TrueTypeTable; - -/** Error codes for most functions */ - enum TTCRErrCodes { - TTCR_OK = 0, /**< no error */ - TTCR_ZEROGLYPHS = 1, /**< At least one glyph should be defined */ - TTCR_UNKNOWN = 2, /**< Unknown TrueType table */ - TTCR_GLYPHSEQ = 3, /**< Glyph IDs are not sequential in the glyf table */ - TTCR_NONAMES = 4, /**< 'name' table does not contain any names */ - TTCR_NAMETOOLONG = 5, /**< 'name' table is too long (string data > 64K) */ - TTCR_POSTFORMAT = 6 /**< unsupported format of a 'post' table */ - }; - -/* ============================================================================ - * - * TrueTypeCreator methods - * - * ============================================================================ */ - -/** - * TrueTypeCreator constructor. - * Allocates all internal structures. - */ - void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this); - -/** - * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it. - */ - void TrueTypeCreatorDispose(TrueTypeCreator *_this); - -/** - * Adds a TrueType table to the TrueType creator. - * SF_TABLEFORMAT value. - * @return value of SFErrCodes type - */ - int AddTable(TrueTypeCreator *_this, TrueTypeTable *table); - -/** - * Removes a TrueType table from the TrueType creator if it is stored there. - * It also calls a TrueTypeTable destructor. - * Note: all generic tables (with tag 0) will be removed if this function is - * called with the second argument of 0. - * @return value of SFErrCodes type - */ - void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag); - - - -/** - * Writes a TrueType font generated by the TrueTypeCreator to a segment of - * memory that this method allocates. When it is not needed anymore the caller - * is supposed to call free() on it. - * @return value of SFErrCodes type - */ - int StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length); - -/** - * Writes a TrueType font generated by the TrueTypeCreator to a file - * @return value of SFErrCodes type - */ - int StreamToFile(TrueTypeCreator *_this, const char* fname); - - -/* ============================================================================ - * - * TrueTypeTable methods - * - * ============================================================================ */ - -/** - * Destructor for the TrueTypeTable object. - */ - void TrueTypeTableDispose(TrueTypeTable *); - -/** - * This function converts the data of a TrueType table to a raw array of bytes. - * It may allocates the memory for it and returns the size of the raw data in bytes. - * If memory is allocated it does not need to be freed by the caller of this function, - * since the pointer to it is stored in the TrueTypeTable and it is freed by the destructor - * @return TTCRErrCode - * - */ - - int GetRawData(TrueTypeTable *, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag); - -/** - * - * Creates a new raw TrueType table. The difference between this constructor and - * TrueTypeTableNew_tag constructors is that the latter create structured tables - * while this constructor just copies memory pointed to by ptr to its buffer - * and stores its length. This constructor is suitable for data that is not - * supposed to be processed in any way, just written to the resulting TTF file. - */ - TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag, - sal_uInt32 nbytes, - sal_uInt8 *ptr); - -/** - * Creates a new 'head' table for a TrueType font. - * Allocates memory for it. Since a lot of values in the 'head' table depend on the - * rest of the tables in the TrueType font this table should be the last one added - * to the font. - */ - TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision, - sal_uInt16 flags, - sal_uInt16 unitsPerEm, - sal_uInt8 *created, - sal_uInt16 macStyle, - sal_uInt16 lowestRecPPEM, - sal_Int16 fontDirectionHint); - -/** - * Creates a new 'hhea' table for a TrueType font. - * Allocates memory for it and stores it in the hhea pointer. - */ - TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender, - sal_Int16 descender, - sal_Int16 linegap, - sal_Int16 caretSlopeRise, - sal_Int16 caretSlopeRun); - -/** - * Creates a new empty 'loca' table for a TrueType font. - * - * INTERNAL: gets called only from ProcessTables(); - */ - TrueTypeTable *TrueTypeTableNew_loca(void); - -/** - * Creates a new 'maxp' table based on an existing maxp table. - * If maxp is 0, a new empty maxp table is created - * size specifies the size of existing maxp table for - * error-checking purposes - */ - TrueTypeTable *TrueTypeTableNew_maxp(sal_uInt8 *maxp, int size); - -/** - * Creates a new empty 'glyf' table. - */ - TrueTypeTable *TrueTypeTableNew_glyf(void); - -/** - * Creates a new empty 'cmap' table. - */ - TrueTypeTable *TrueTypeTableNew_cmap(void); - -/** - * Creates a new 'name' table. If n != 0 the table gets populated by - * the Name Records stored in the nr array. This function allocates - * memory for its own copy of NameRecords, so nr array has to - * be explicitly deallocated when it is not needed. - */ - TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord *nr); - -/** - * Creates a new 'post' table of one of the supported formats - */ - TrueTypeTable *TrueTypeTableNew_post(sal_uInt32 format, - sal_uInt32 italicAngle, - sal_Int16 underlinePosition, - sal_Int16 underlineThickness, - sal_uInt32 isFixedPitch); - - -/*------------------------------------------------------------------------------ - * - * Table manipulation functions - * - *------------------------------------------------------------------------------*/ - - -/** - * Add a character/glyph pair to a cmap table - */ - void cmapAdd(TrueTypeTable *, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g); - -/** - * Add a glyph to a glyf table. - * - * @return glyphID of the glyph in the new font - * - * NOTE: This function does not duplicate GlyphData, so memory will be - * deallocated in the table destructor - */ - sal_uInt32 glyfAdd(TrueTypeTable *, GlyphData *glyphdata, TrueTypeFont *fnt); - -/** - * Query the number of glyphs currently stored in the 'glyf' table - * - */ - sal_uInt32 glyfCount(const TrueTypeTable *); - -/** - * Add a Name Record to a name table. - * NOTE: This function duplicates NameRecord, so the argument - * has to be deallocated by the caller (unlike glyfAdd) - */ - void nameAdd(TrueTypeTable *, NameRecord *nr); - - - -/* - * Private Data Types - */ - - struct _TrueTypeCreator { - sal_uInt32 tag; /**< TrueType file tag */ - list tables; /**< List of table tags and pointers */ - }; - - - -#ifdef __cplusplus -} -#endif - -#endif /* __TTCR_H */ diff --git a/vcl/source/fontsubset/ttcr.hxx b/vcl/source/fontsubset/ttcr.hxx new file mode 100644 index 000000000000..5b47f09d552a --- /dev/null +++ b/vcl/source/fontsubset/ttcr.hxx @@ -0,0 +1,261 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/** + * + * @file ttcr.h + * @brief TrueType font creator + * @author Alexander Gelfenbain + */ + +#ifndef __TTCR_H +#define __TTCR_H + +#include "sft.hxx" + +namespace vcl +{ + typedef struct _TrueTypeCreator TrueTypeCreator; + +/* TrueType data types */ + typedef struct { + sal_uInt16 aw; + sal_Int16 lsb; + } longHorMetrics; + +/* A generic base class for all TrueType tables */ + struct TrueTypeTable { + sal_uInt32 tag; /* table tag */ + sal_uInt8 *rawdata; /* raw data allocated by GetRawData_*() */ + void *data; /* table specific data */ + }; + +/** Error codes for most functions */ + enum TTCRErrCodes { + TTCR_OK = 0, /**< no error */ + TTCR_ZEROGLYPHS = 1, /**< At least one glyph should be defined */ + TTCR_UNKNOWN = 2, /**< Unknown TrueType table */ + TTCR_GLYPHSEQ = 3, /**< Glyph IDs are not sequential in the glyf table */ + TTCR_NONAMES = 4, /**< 'name' table does not contain any names */ + TTCR_NAMETOOLONG = 5, /**< 'name' table is too long (string data > 64K) */ + TTCR_POSTFORMAT = 6 /**< unsupported format of a 'post' table */ + }; + +/* ============================================================================ + * + * TrueTypeCreator methods + * + * ============================================================================ */ + +/** + * TrueTypeCreator constructor. + * Allocates all internal structures. + */ + void TrueTypeCreatorNewEmpty(sal_uInt32 tag, TrueTypeCreator **_this); + +/** + * Adds a TrueType table to the TrueType creator. + * SF_TABLEFORMAT value. + * @return value of SFErrCodes type + */ + int AddTable(TrueTypeCreator *_this, TrueTypeTable *table); + +/** + * Removes a TrueType table from the TrueType creator if it is stored there. + * It also calls a TrueTypeTable destructor. + * Note: all generic tables (with tag 0) will be removed if this function is + * called with the second argument of 0. + * @return value of SFErrCodes type + */ + void RemoveTable(TrueTypeCreator *_this, sal_uInt32 tag); + + + +/** + * Writes a TrueType font generated by the TrueTypeCreator to a segment of + * memory that this method allocates. When it is not needed anymore the caller + * is supposed to call free() on it. + * @return value of SFErrCodes type + */ + int StreamToMemory(TrueTypeCreator *_this, sal_uInt8 **ptr, sal_uInt32 *length); + +/** + * Writes a TrueType font generated by the TrueTypeCreator to a file + * @return value of SFErrCodes type + */ + int StreamToFile(TrueTypeCreator *_this, const char* fname); + + +/* ============================================================================ + * + * TrueTypeTable methods + * + * ============================================================================ */ + + +/** + * This function converts the data of a TrueType table to a raw array of bytes. + * It may allocates the memory for it and returns the size of the raw data in bytes. + * If memory is allocated it does not need to be freed by the caller of this function, + * since the pointer to it is stored in the TrueTypeTable and it is freed by the destructor + * @return TTCRErrCode + * + */ + + int GetRawData(TrueTypeTable *, sal_uInt8 **ptr, sal_uInt32 *len, sal_uInt32 *tag); + +/** + * + * Creates a new raw TrueType table. The difference between this constructor and + * TrueTypeTableNew_tag constructors is that the latter create structured tables + * while this constructor just copies memory pointed to by ptr to its buffer + * and stores its length. This constructor is suitable for data that is not + * supposed to be processed in any way, just written to the resulting TTF file. + */ + TrueTypeTable *TrueTypeTableNew(sal_uInt32 tag, + sal_uInt32 nbytes, + sal_uInt8 *ptr); + +/** + * Creates a new 'head' table for a TrueType font. + * Allocates memory for it. Since a lot of values in the 'head' table depend on the + * rest of the tables in the TrueType font this table should be the last one added + * to the font. + */ + TrueTypeTable *TrueTypeTableNew_head(sal_uInt32 fontRevision, + sal_uInt16 flags, + sal_uInt16 unitsPerEm, + sal_uInt8 *created, + sal_uInt16 macStyle, + sal_uInt16 lowestRecPPEM, + sal_Int16 fontDirectionHint); + +/** + * Creates a new 'hhea' table for a TrueType font. + * Allocates memory for it and stores it in the hhea pointer. + */ + TrueTypeTable *TrueTypeTableNew_hhea(sal_Int16 ascender, + sal_Int16 descender, + sal_Int16 linegap, + sal_Int16 caretSlopeRise, + sal_Int16 caretSlopeRun); + +/** + * Creates a new empty 'loca' table for a TrueType font. + * + * INTERNAL: gets called only from ProcessTables(); + */ + TrueTypeTable *TrueTypeTableNew_loca(void); + +/** + * Creates a new 'maxp' table based on an existing maxp table. + * If maxp is 0, a new empty maxp table is created + * size specifies the size of existing maxp table for + * error-checking purposes + */ + TrueTypeTable *TrueTypeTableNew_maxp(sal_uInt8 *maxp, int size); + +/** + * Creates a new empty 'glyf' table. + */ + TrueTypeTable *TrueTypeTableNew_glyf(void); + +/** + * Creates a new empty 'cmap' table. + */ + TrueTypeTable *TrueTypeTableNew_cmap(void); + +/** + * Creates a new 'name' table. If n != 0 the table gets populated by + * the Name Records stored in the nr array. This function allocates + * memory for its own copy of NameRecords, so nr array has to + * be explicitly deallocated when it is not needed. + */ + TrueTypeTable *TrueTypeTableNew_name(int n, NameRecord *nr); + +/** + * Creates a new 'post' table of one of the supported formats + */ + TrueTypeTable *TrueTypeTableNew_post(sal_uInt32 format, + sal_uInt32 italicAngle, + sal_Int16 underlinePosition, + sal_Int16 underlineThickness, + sal_uInt32 isFixedPitch); + + +/*------------------------------------------------------------------------------ + * + * Table manipulation functions + * + *------------------------------------------------------------------------------*/ + + +/** + * Add a character/glyph pair to a cmap table + */ + void cmapAdd(TrueTypeTable *, sal_uInt32 id, sal_uInt32 c, sal_uInt32 g); + +/** + * Add a glyph to a glyf table. + * + * @return glyphID of the glyph in the new font + * + * NOTE: This function does not duplicate GlyphData, so memory will be + * deallocated in the table destructor + */ + sal_uInt32 glyfAdd(TrueTypeTable *, GlyphData *glyphdata, TrueTypeFont *fnt); + +/** + * Query the number of glyphs currently stored in the 'glyf' table + * + */ + sal_uInt32 glyfCount(const TrueTypeTable *); + +/** + * Add a Name Record to a name table. + * NOTE: This function duplicates NameRecord, so the argument + * has to be deallocated by the caller (unlike glyfAdd) + */ + void nameAdd(TrueTypeTable *, NameRecord *nr); + +} // namespace + + +extern "C" +{ +/** + * Destructor for the TrueTypeTable object. + */ + void TrueTypeTableDispose(vcl::TrueTypeTable *); + +/** + * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it. + */ + void TrueTypeCreatorDispose(vcl::TrueTypeCreator *_this); +} + +#endif /* __TTCR_H */ diff --git a/vcl/source/fontsubset/u2big5.inc b/vcl/source/fontsubset/u2big5.inc index 2883e9d99094..951b65cffc25 100644 --- a/vcl/source/fontsubset/u2big5.inc +++ b/vcl/source/fontsubset/u2big5.inc @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: u2big5.inc,v $ - * $Revision: 1.4 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,6 +25,8 @@ * ************************************************************************/ +// TODO: use generic RTL_TEXTENCODING_BIG5 to get rid of this file + sal_uInt16pair xlat_1_3[13798] = { {0x0020, 0x0020},{0x0021, 0x0021},{0x0022, 0x0022},{0x0023, 0x0023},{0x0024, 0x0024},{0x0025, 0x0025},{0x0026, 0x0026},{0x0027, 0x0027}, {0x0028, 0x0028},{0x0029, 0x0029},{0x002A, 0x002A},{0x002B, 0x002B},{0x002C, 0x002C},{0x002D, 0x002D},{0x002E, 0x002E},{0x002F, 0x002F}, diff --git a/vcl/source/fontsubset/u2johab.inc b/vcl/source/fontsubset/u2johab.inc index ae07cc571fb8..f7a75afaf503 100644 --- a/vcl/source/fontsubset/u2johab.inc +++ b/vcl/source/fontsubset/u2johab.inc @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: u2johab.inc,v $ - * $Revision: 1.4 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,6 +25,8 @@ * ************************************************************************/ +// use generic RTL_TEXTENCODING_JOHAB to get rid of this file + sal_uInt16pair xlat_1_6[17141] = { {0x0020, 0x0020},{0x0021, 0x0021},{0x0022, 0x0022},{0x0023, 0x0023},{0x0024, 0x0024},{0x0025, 0x0025},{0x0026, 0x0026},{0x0027, 0x0027}, {0x0028, 0x0028},{0x0029, 0x0029},{0x002A, 0x002A},{0x002B, 0x002B},{0x002C, 0x002C},{0x002D, 0x002D},{0x002E, 0x002E},{0x002F, 0x002F}, diff --git a/vcl/source/fontsubset/u2prc.inc b/vcl/source/fontsubset/u2prc.inc index 2479d23ebe6f..445461b59653 100644 --- a/vcl/source/fontsubset/u2prc.inc +++ b/vcl/source/fontsubset/u2prc.inc @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: u2prc.inc,v $ - * $Revision: 1.4 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,6 +25,8 @@ * ************************************************************************/ +// use generic RTL_TEXTENCODING_ to get rid of this file + sal_uInt16pair xlat_1_4[24035] = { {0x0020, 0x0020},{0x0021, 0x0021},{0x0022, 0x0022},{0x0023, 0x0023},{0x0024, 0x0024},{0x0025, 0x0025},{0x0026, 0x0026},{0x0027, 0x0027}, {0x0028, 0x0028},{0x0029, 0x0029},{0x002A, 0x002A},{0x002B, 0x002B},{0x002C, 0x002C},{0x002D, 0x002D},{0x002E, 0x002E},{0x002F, 0x002F}, diff --git a/vcl/source/fontsubset/u2shiftjis.inc b/vcl/source/fontsubset/u2shiftjis.inc index fb130feaebe2..ebc6f1676784 100644 --- a/vcl/source/fontsubset/u2shiftjis.inc +++ b/vcl/source/fontsubset/u2shiftjis.inc @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: u2shiftjis.inc,v $ - * $Revision: 1.4 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,6 +25,8 @@ * ************************************************************************/ +// TODO: use generic RTL_TEXTENCODING_SHIFTJIS to get rid of this file + sal_uInt16pair xlat_1_2[7484] = { {0x0020, 0x0020},{0x0021, 0x0021},{0x0022, 0x0022},{0x0023, 0x0023},{0x0024, 0x0024},{0x0025, 0x0025},{0x0026, 0x0026},{0x0027, 0x0027}, {0x0028, 0x0028},{0x0029, 0x0029},{0x002A, 0x002A},{0x002B, 0x002B},{0x002C, 0x002C},{0x002D, 0x002D},{0x002E, 0x002E},{0x002F, 0x002F}, diff --git a/vcl/source/fontsubset/u2wansung.inc b/vcl/source/fontsubset/u2wansung.inc index 0cb8867f1c2a..b321c9e58bfa 100644 --- a/vcl/source/fontsubset/u2wansung.inc +++ b/vcl/source/fontsubset/u2wansung.inc @@ -6,9 +6,6 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: u2wansung.inc,v $ - * $Revision: 1.4 $ - * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify @@ -28,6 +25,8 @@ * ************************************************************************/ +// TODO: use generic RTL_TEXTENCODING_WANSUNG to get rid of this file + sal_uInt16pair xlat_1_5[8319] = { {0x0020, 0x0020},{0x0021, 0x0021},{0x0022, 0x0022},{0x0023, 0x0023},{0x0024, 0x0024},{0x0025, 0x0025},{0x0026, 0x0026},{0x0027, 0x0027}, {0x0028, 0x0028},{0x0029, 0x0029},{0x002A, 0x002A},{0x002B, 0x002B},{0x002C, 0x002C},{0x002D, 0x002D},{0x002E, 0x002E},{0x002F, 0x002F}, diff --git a/vcl/source/fontsubset/xlat.c b/vcl/source/fontsubset/xlat.c deleted file mode 100644 index 840850a020da..000000000000 --- a/vcl/source/fontsubset/xlat.c +++ /dev/null @@ -1,187 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xlat.c,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: xlat.c,v 1.4 2008-04-11 10:19:41 rt Exp $ - * - * Data translation from Unicode to MS encodings - * If the host system provides this functionality - * this file should be rewritten to use it and - * the large translation arrays should be removed - * - * Author: Alexander Gelfenbain - * - */ - -#include "xlat.h" - -#include "u2big5.inc" -#include "u2johab.inc" -#include "u2prc.inc" -#include "u2shiftjis.inc" -#include "u2wansung.inc" - -#define MISSING_CODE 0 - -static sal_uInt16 xlat(sal_uInt16pair p[], sal_uInt32 n, sal_uInt16 src) -{ - int l = 0, r = n - 1, i; - sal_uInt16 t, res = MISSING_CODE; - - do { - i = (l + r) >> 1; - t = p[i].s; - if (src >= t) l = i + 1; - if (src <= t) r = i - 1; - } while (l <= r); - - if (l - r == 2) { - res = p[l-1].d; - } - - return res; -} - -sal_uInt16 TranslateChar12(sal_uInt16 src) -{ - return xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), src); -} - -sal_uInt16 TranslateChar13(sal_uInt16 src) -{ - return xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), src); -} - -sal_uInt16 TranslateChar14(sal_uInt16 src) -{ - return xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), src); -} - -sal_uInt16 TranslateChar15(sal_uInt16 src) -{ - return xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), src); -} - -sal_uInt16 TranslateChar16(sal_uInt16 src) -{ - return xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_5[0]), src); -} - -void TranslateString12(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) -{ - sal_uInt32 i; - sal_uInt16 lastS, lastD; - - if (n == 0) return; - - lastD = dst[0] = xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), lastS = src[0]); - - for (i=1; i < n; i++) { - if (src[i] == lastS) { - dst[i] = lastD; - } else { - lastD = dst[i] = xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), lastS = src[i]); - } - } -} - -void TranslateString13(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) -{ - sal_uInt32 i; - sal_uInt16 lastS, lastD; - - if (n == 0) return; - - lastD = dst[0] = xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), lastS = src[0]); - - for (i=1; i < n; i++) { - if (src[i] == lastS) { - dst[i] = lastD; - } else { - lastD = dst[i] = xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), lastS = src[i]); - } - } -} - -void TranslateString14(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) -{ - sal_uInt32 i; - sal_uInt16 lastS, lastD; - - if (n == 0) return; - - lastD = dst[0] = xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), lastS = src[0]); - - for (i=1; i < n; i++) { - if (src[i] == lastS) { - dst[i] = lastD; - } else { - lastD = dst[i] = xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), lastS = src[i]); - } - } -} - -void TranslateString15(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) -{ - sal_uInt32 i; - sal_uInt16 lastS, lastD; - - if (n == 0) return; - - lastD = dst[0] = xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), lastS = src[0]); - - for (i=1; i < n; i++) { - if (src[i] == lastS) { - dst[i] = lastD; - } else { - lastD = dst[i] = xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), lastS = src[i]); - } - } -} - -void TranslateString16(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) -{ - sal_uInt32 i; - sal_uInt16 lastS, lastD; - - if (n == 0) return; - - lastD = dst[0] = xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_6[0]), lastS = src[0]); - - for (i=1; i < n; i++) { - if (src[i] == lastS) { - dst[i] = lastD; - } else { - lastD = dst[i] = xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_6[0]), lastS = src[i]); - } - } -} - - - diff --git a/vcl/source/fontsubset/xlat.cxx b/vcl/source/fontsubset/xlat.cxx new file mode 100644 index 000000000000..27b2f517f4a1 --- /dev/null +++ b/vcl/source/fontsubset/xlat.cxx @@ -0,0 +1,188 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/* + * + * Data translation from Unicode to MS encodings + * If the host system provides this functionality + * this file should be rewritten to use it and + * the large translation arrays should be removed + * + * Author: Alexander Gelfenbain + * + */ + +#include "xlat.hxx" + +namespace vcl +{ + +// TODO: use generic encoding converters and get rid of the include files below +#include "u2big5.inc" +#include "u2johab.inc" +#include "u2prc.inc" +#include "u2shiftjis.inc" +#include "u2wansung.inc" + +#define MISSING_CODE 0 + +static sal_uInt16 xlat(sal_uInt16pair p[], sal_uInt32 n, sal_uInt16 src) +{ + int l = 0, r = n - 1, i; + sal_uInt16 t, res = MISSING_CODE; + + do { + i = (l + r) >> 1; + t = p[i].s; + if (src >= t) l = i + 1; + if (src <= t) r = i - 1; + } while (l <= r); + + if (l - r == 2) { + res = p[l-1].d; + } + + return res; +} + +sal_uInt16 TranslateChar12(sal_uInt16 src) +{ + return xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), src); +} + +sal_uInt16 TranslateChar13(sal_uInt16 src) +{ + return xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), src); +} + +sal_uInt16 TranslateChar14(sal_uInt16 src) +{ + return xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), src); +} + +sal_uInt16 TranslateChar15(sal_uInt16 src) +{ + return xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), src); +} + +sal_uInt16 TranslateChar16(sal_uInt16 src) +{ + return xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_5[0]), src); +} + +void TranslateString12(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) +{ + sal_uInt32 i; + sal_uInt16 lastS, lastD; + + if (n == 0) return; + + lastD = dst[0] = xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), lastS = src[0]); + + for (i=1; i < n; i++) { + if (src[i] == lastS) { + dst[i] = lastD; + } else { + lastD = dst[i] = xlat(xlat_1_2, sizeof(xlat_1_2) / sizeof(xlat_1_2[0]), lastS = src[i]); + } + } +} + +void TranslateString13(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) +{ + sal_uInt32 i; + sal_uInt16 lastS, lastD; + + if (n == 0) return; + + lastD = dst[0] = xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), lastS = src[0]); + + for (i=1; i < n; i++) { + if (src[i] == lastS) { + dst[i] = lastD; + } else { + lastD = dst[i] = xlat(xlat_1_3, sizeof(xlat_1_3) / sizeof(xlat_1_3[0]), lastS = src[i]); + } + } +} + +void TranslateString14(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) +{ + sal_uInt32 i; + sal_uInt16 lastS, lastD; + + if (n == 0) return; + + lastD = dst[0] = xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), lastS = src[0]); + + for (i=1; i < n; i++) { + if (src[i] == lastS) { + dst[i] = lastD; + } else { + lastD = dst[i] = xlat(xlat_1_4, sizeof(xlat_1_4) / sizeof(xlat_1_4[0]), lastS = src[i]); + } + } +} + +void TranslateString15(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) +{ + sal_uInt32 i; + sal_uInt16 lastS, lastD; + + if (n == 0) return; + + lastD = dst[0] = xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), lastS = src[0]); + + for (i=1; i < n; i++) { + if (src[i] == lastS) { + dst[i] = lastD; + } else { + lastD = dst[i] = xlat(xlat_1_5, sizeof(xlat_1_5) / sizeof(xlat_1_5[0]), lastS = src[i]); + } + } +} + +void TranslateString16(sal_uInt16 *src, sal_uInt16 *dst, sal_uInt32 n) +{ + sal_uInt32 i; + sal_uInt16 lastS, lastD; + + if (n == 0) return; + + lastD = dst[0] = xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_6[0]), lastS = src[0]); + + for (i=1; i < n; i++) { + if (src[i] == lastS) { + dst[i] = lastD; + } else { + lastD = dst[i] = xlat(xlat_1_6, sizeof(xlat_1_6) / sizeof(xlat_1_6[0]), lastS = src[i]); + } + } +} + +} // namespace vcl + diff --git a/vcl/source/fontsubset/xlat.h b/vcl/source/fontsubset/xlat.h deleted file mode 100644 index 86eca1691574..000000000000 --- a/vcl/source/fontsubset/xlat.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xlat.h,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -/* $Id: xlat.h,v 1.4 2008-04-11 10:19:58 rt Exp $ */ - -/*[]---------------------------------------------------[]*/ -/*| |*/ -/*| xlat.h |*/ -/*| |*/ -/*| Author: Alexander Gelfenbain |*/ -/*[]---------------------------------------------------[]*/ - - -#ifndef __XLAT_H -#define __XLAT_H - -#ifdef __cplusplus -extern "C" { -#endif - - -#include "sft.h" - - sal_uInt16 TranslateChar12(sal_uInt16); - sal_uInt16 TranslateChar13(sal_uInt16); - sal_uInt16 TranslateChar14(sal_uInt16); - sal_uInt16 TranslateChar15(sal_uInt16); - sal_uInt16 TranslateChar16(sal_uInt16); - - void TranslateString12(sal_uInt16 *, sal_uInt16 *, sal_uInt32); - void TranslateString13(sal_uInt16 *, sal_uInt16 *, sal_uInt32); - void TranslateString14(sal_uInt16 *, sal_uInt16 *, sal_uInt32); - void TranslateString15(sal_uInt16 *, sal_uInt16 *, sal_uInt32); - void TranslateString16(sal_uInt16 *, sal_uInt16 *, sal_uInt32); - -#ifdef __cplusplus -} -#endif - - -#endif /* __XLAT_H */ diff --git a/vcl/source/fontsubset/xlat.hxx b/vcl/source/fontsubset/xlat.hxx new file mode 100644 index 000000000000..c3bd076f6fbd --- /dev/null +++ b/vcl/source/fontsubset/xlat.hxx @@ -0,0 +1,54 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +/*| Author: Alexander Gelfenbain |*/ + + +#ifndef __XLAT_H +#define __XLAT_H + +#include "sft.hxx" + +namespace vcl +{ +// TODO: sal_UCS4 + + sal_uInt16 TranslateChar12(sal_uInt16); + sal_uInt16 TranslateChar13(sal_uInt16); + sal_uInt16 TranslateChar14(sal_uInt16); + sal_uInt16 TranslateChar15(sal_uInt16); + sal_uInt16 TranslateChar16(sal_uInt16); + + void TranslateString12(sal_uInt16 *, sal_uInt16 *, sal_uInt32); + void TranslateString13(sal_uInt16 *, sal_uInt16 *, sal_uInt32); + void TranslateString14(sal_uInt16 *, sal_uInt16 *, sal_uInt32); + void TranslateString15(sal_uInt16 *, sal_uInt16 *, sal_uInt32); + void TranslateString16(sal_uInt16 *, sal_uInt16 *, sal_uInt32); +} + +#endif /* __XLAT_H */ + diff --git a/vcl/source/gdi/font.cxx b/vcl/source/gdi/font.cxx index 820b053a4211..3bbdba5dad5f 100644 --- a/vcl/source/gdi/font.cxx +++ b/vcl/source/gdi/font.cxx @@ -31,7 +31,7 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#include "sft.h" +#include "sft.hxx" #include "tools/stream.hxx" #include "tools/vcompat.hxx" @@ -43,6 +43,8 @@ #include +using namespace vcl; + // ======================================================================= DBG_NAME( Font ) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index 0754f5c5b3dc..05067ee2d024 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -6680,6 +6680,7 @@ void PDFWriterImpl::drawHorizontalGlyphs( appendHex( rGlyphs[nPos].m_nMappedGlyphId, aUnkernedLine ); // check for adjustment double fTheoreticalGlyphWidth = rGlyphs[nPos].m_aPos.X() - rGlyphs[nPos-1].m_aPos.X(); + fTheoreticalGlyphWidth = fabs( fTheoreticalGlyphWidth ); // #i100522# workaround until #i87686# gets fixed fTheoreticalGlyphWidth = 1000.0 * fTheoreticalGlyphWidth / fXScale / double(nPixelFontHeight); sal_Int32 nAdjustment = rGlyphs[nPos-1].m_nNativeWidth - sal_Int32(fTheoreticalGlyphWidth+0.5); if( nAdjustment != 0 ) @@ -6902,10 +6903,16 @@ void PDFWriterImpl::drawLayout( SalLayout& rLayout, const String& rText, bool bT if( aAlignOffset.X() || aAlignOffset.Y() ) aAlignOffset = aRotScale.transform( aAlignOffset ); - if( bVertical ) - drawVerticalGlyphs( aGlyphs, aLine, aAlignOffset, aRotScale, fAngle, fXScale, fSkew, nFontHeight ); - else - drawHorizontalGlyphs( aGlyphs, aLine, aAlignOffset, fAngle, fXScale, fSkew, nFontHeight, nPixelFontHeight ); + /* #159153# do not emit an empty glyph vector; this can happen if e.g. the original + string contained only on of the UTF16 BOMs + */ + if( ! aGlyphs.empty() ) + { + if( bVertical ) + drawVerticalGlyphs( aGlyphs, aLine, aAlignOffset, aRotScale, fAngle, fXScale, fSkew, nFontHeight ); + else + drawHorizontalGlyphs( aGlyphs, aLine, aAlignOffset, fAngle, fXScale, fSkew, nFontHeight, nPixelFontHeight ); + } // end textobject aLine.append( "ET\n" ); @@ -9297,14 +9304,24 @@ void PDFWriterImpl::drawJPGBitmap( SvStream& rDCTData, bool bIsTrueColor, const delete pStream; aLine.append( "q " ); - m_aPages.back().appendMappedLength( (sal_Int32)rTargetArea.GetWidth(), aLine, false ); + sal_Int32 nCheckWidth = 0; + m_aPages.back().appendMappedLength( (sal_Int32)rTargetArea.GetWidth(), aLine, false, &nCheckWidth ); aLine.append( " 0 0 " ); - m_aPages.back().appendMappedLength( (sal_Int32)rTargetArea.GetHeight(), aLine, true ); + sal_Int32 nCheckHeight = 0; + m_aPages.back().appendMappedLength( (sal_Int32)rTargetArea.GetHeight(), aLine, true, &nCheckHeight ); aLine.append( ' ' ); m_aPages.back().appendPoint( rTargetArea.BottomLeft(), aLine ); aLine.append( " cm\n/Im" ); aLine.append( it->m_nObject ); aLine.append( " Do Q\n" ); + if( nCheckWidth == 0 || nCheckHeight == 0 ) + { + // #i97512# avoid invalid current matrix + aLine.setLength( 0 ); + aLine.append( "\n%jpeg image /Im" ); + aLine.append( it->m_nObject ); + aLine.append( " scaled to zero size, omitted\n" ); + } writeBuffer( aLine.getStr(), aLine.getLength() ); OStringBuffer aObjName( 16 ); @@ -9325,14 +9342,24 @@ void PDFWriterImpl::drawBitmap( const Point& rDestPoint, const Size& rDestSize, appendNonStrokingColor( rFillColor, aLine ); aLine.append( ' ' ); } - m_aPages.back().appendMappedLength( (sal_Int32)rDestSize.Width(), aLine, false ); + sal_Int32 nCheckWidth = 0; + m_aPages.back().appendMappedLength( (sal_Int32)rDestSize.Width(), aLine, false, &nCheckWidth ); aLine.append( " 0 0 " ); - m_aPages.back().appendMappedLength( (sal_Int32)rDestSize.Height(), aLine, true ); + sal_Int32 nCheckHeight = 0; + m_aPages.back().appendMappedLength( (sal_Int32)rDestSize.Height(), aLine, true, &nCheckHeight ); aLine.append( ' ' ); m_aPages.back().appendPoint( rDestPoint + Point( 0, rDestSize.Height()-1 ), aLine ); aLine.append( " cm\n/Im" ); aLine.append( rBitmap.m_nObject ); aLine.append( " Do Q\n" ); + if( nCheckWidth == 0 || nCheckHeight == 0 ) + { + // #i97512# avoid invalid current matrix + aLine.setLength( 0 ); + aLine.append( "\n%bitmap image /Im" ); + aLine.append( rBitmap.m_nObject ); + aLine.append( " scaled to zero size, omitted\n" ); + } writeBuffer( aLine.getStr(), aLine.getLength() ); } diff --git a/vcl/source/gdi/sallayout.cxx b/vcl/source/gdi/sallayout.cxx index 89a47a9f4077..a96d4dc64b89 100755 --- a/vcl/source/gdi/sallayout.cxx +++ b/vcl/source/gdi/sallayout.cxx @@ -1773,7 +1773,7 @@ void MultiSalLayout::AdjustLayout( ImplLayoutArgs& rArgs ) int nStartNew[ MAX_FALLBACK ]; int nCharPos[ MAX_FALLBACK ]; sal_Int32 nGlyphAdv[ MAX_FALLBACK ]; - int nValid[ MAX_FALLBACK ]; + int nValid[ MAX_FALLBACK ] = {0}; sal_GlyphId nDummy; Point aPos; diff --git a/vcl/source/helper/smartid.cxx b/vcl/source/helper/smartid.cxx index 7ac7abe0d18b..73ad6f89a21c 100755 --- a/vcl/source/helper/smartid.cxx +++ b/vcl/source/helper/smartid.cxx @@ -262,6 +262,6 @@ BOOL SmartId::operator < ( const SmartId& rRight ) const if ( HasString() ) return rRight.HasString() && rRight.HasNumeric(); else - return rRight.HasString() || !HasNumeric() && rRight.HasNumeric(); + return rRight.HasString() || (!HasNumeric() && rRight.HasNumeric()); } } diff --git a/vcl/source/window/decoview.cxx b/vcl/source/window/decoview.cxx index 4dd2bca2d6fa..8c6bb2b76463 100644 --- a/vcl/source/window/decoview.cxx +++ b/vcl/source/window/decoview.cxx @@ -944,9 +944,16 @@ static void ImplDrawFrame( OutputDevice* pDev, Rectangle& rRect, Color aColor = bRound ? rStyleSettings.GetShadowColor() : pDev->GetSettings().GetStyleSettings().GetMonoColor(); // when the MonoColor wasn't set, check face color - if ( ( ( bRound && aColor.IsDark() ) || ( aColor == Color( COL_BLACK ) && - ( pDev->GetSettings().GetStyleSettings().GetFaceColor().IsDark() ) ) ) ) + if ( + (bRound && aColor.IsDark()) || + ( + (aColor == Color(COL_BLACK)) && + (pDev->GetSettings().GetStyleSettings().GetFaceColor().IsDark()) + ) + ) + { aColor = Color( COL_WHITE ); + } ImplDrawDPILineRect( pDev, rRect, &aColor, bRound ); } else @@ -1183,7 +1190,7 @@ static void ImplDrawButton( OutputDevice* pDev, Rectangle& rRect, aFillRect.Right(), aFillRect.Top() ) ); aFillRect.Top()++; } - if ( ((nStyle & (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) == (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) && + if ( (( (nStyle & BUTTON_DRAW_NOBOTTOMSHADOWBORDER) | BUTTON_DRAW_FLAT) == (BUTTON_DRAW_NOBOTTOMSHADOWBORDER | BUTTON_DRAW_FLAT)) && !(nStyle & (BUTTON_DRAW_PRESSED | BUTTON_DRAW_CHECKED | BUTTON_DRAW_HIGHLIGHT)) ) { pDev->SetFillColor( rStyleSettings.GetDarkShadowColor() ); diff --git a/vcl/source/window/menu.cxx b/vcl/source/window/menu.cxx index 1318f4fa8415..adbc2a8de06e 100644 --- a/vcl/source/window/menu.cxx +++ b/vcl/source/window/menu.cxx @@ -2323,6 +2323,8 @@ Size Menu::ImplCalcSize( Window* pWin ) if ( !bIsMenuBar && ( ( pData->eType == MENUITEM_IMAGE ) || ( pData->eType == MENUITEM_STRINGIMAGE ) ) ) { Size aImgSz = pData->aImage.GetSizePixel(); + aImgSz.Height() += 4; // add a border for native marks + aImgSz.Width() += 4; // add a border for native marks if ( aImgSz.Width() > aMaxImgSz.Width() ) aMaxImgSz.Width() = aImgSz.Width(); if ( aImgSz.Height() > aMaxImgSz.Height() ) @@ -2336,7 +2338,11 @@ Size Menu::ImplCalcSize( Window* pWin ) { nCheckWidth = nMaxCheckWidth; if (nMenuFlags & MENU_FLAG_SHOWCHECKIMAGES) - nWidth += nCheckWidth + nExtra * 2; + { + // checks / images take the same place + if( ! ( ( pData->eType == MENUITEM_IMAGE ) || ( pData->eType == MENUITEM_STRINGIMAGE ) ) ) + nWidth += nCheckWidth + nExtra * 2; + } } // Text: @@ -2397,16 +2403,14 @@ Size Menu::ImplCalcSize( Window* pWin ) nCheckPos = (USHORT)nExtra; if (nMenuFlags & MENU_FLAG_SHOWCHECKIMAGES) { - // non-NWF case has an implicit little extra space around - // the symbol; NWF case has not, so image pos needs to - // be distinct in this case + long nImgOrChkWidth = 0; + nImagePos = nCheckPos; if( nMax > 0 ) // NWF case - nImagePos = (USHORT)(nCheckPos + nMax + nExtra ); + nImgOrChkWidth = nMax + nExtra; else // non NWF case - nImagePos = (USHORT)(nCheckPos + nFontHeight/2 + gfxExtra ); - nTextPos = (USHORT)(nImagePos+aMaxImgSz.Width()); - if ( aMaxImgSz.Width() ) - nTextPos = nTextPos + gfxExtra; + nImgOrChkWidth = nFontHeight/2 + gfxExtra; + nImgOrChkWidth = Max( nImgOrChkWidth, aMaxImgSz.Width() + gfxExtra ); + nTextPos = (USHORT)(nImagePos + nImgOrChkWidth); } else { @@ -2464,6 +2468,45 @@ Size Menu::ImplCalcSize( Window* pWin ) return aSz; } +static void ImplPaintCheckBackground( Window* i_pWindow, const Rectangle& i_rRect, bool i_bHighlight ) +{ + BOOL bNativeOk = FALSE; + if( i_pWindow->IsNativeControlSupported( CTRL_TOOLBAR, PART_BUTTON ) ) + { + ImplControlValue aControlValue; + Region aCtrlRegion( i_rRect ); + ControlState nState = CTRL_STATE_PRESSED | CTRL_STATE_ENABLED; + + aControlValue.setTristateVal( BUTTONVALUE_ON ); + + bNativeOk = i_pWindow->DrawNativeControl( CTRL_TOOLBAR, PART_BUTTON, + aCtrlRegion, nState, aControlValue, + rtl::OUString() ); + } + + if( ! bNativeOk ) + { + const StyleSettings& rSettings = i_pWindow->GetSettings().GetStyleSettings(); + if( i_bHighlight ) + { + i_pWindow->Push( PUSH_ALL ); + Color aCol = rSettings.GetMenuHighlightTextColor(); + i_pWindow->SetFillColor( rSettings.GetMenuHighlightTextColor() ); + if( aCol.IsDark() ) + aCol.IncreaseLuminance( 128 ); + else + aCol.DecreaseLuminance( 128 ); + i_pWindow->SetLineColor( aCol ); + Polygon aPoly( i_rRect ); + PolyPolygon aPolyPoly( aPoly ); + i_pWindow->DrawTransparent( aPolyPoly, 20 ); + i_pWindow->Pop(); + } + else + i_pWindow->DrawSelectionBackground( i_rRect, 1, FALSE, TRUE, FALSE ); + } +} + void Menu::ImplPaint( Window* pWin, USHORT nBorder, long nStartY, MenuItemData* pThisItemOnly, BOOL bHighlighted, bool bLayout ) const { // Fuer Symbole: nFontHeight x nFontHeight @@ -2537,15 +2580,89 @@ void Menu::ImplPaint( Window* pWin, USHORT nBorder, long nStartY, MenuItemData* pWin->SetLineColor(); } + Rectangle aOuterCheckRect( Point( aPos.X()+nCheckPos, aPos.Y() ), Size( pData->aSz.Height(), pData->aSz.Height() ) ); + aOuterCheckRect.Left() += 1; + aOuterCheckRect.Right() -= 1; + aOuterCheckRect.Top() += 1; + aOuterCheckRect.Bottom() -= 1; + + // CheckMark + if ( !bLayout && !bIsMenuBar && pData->HasCheck() ) + { + // draw selection transparent marker if checked + // onto that either a checkmark or the item image + // will be painted + // however do not do this if native checks will be painted since + // the selection color too often does not fit the theme's check and/or radio + + if( ! ( ( pData->eType == MENUITEM_IMAGE ) || ( pData->eType == MENUITEM_STRINGIMAGE ) ) ) + { + if ( pWin->IsNativeControlSupported( CTRL_MENU_POPUP, + (pData->nBits & MIB_RADIOCHECK) + ? PART_MENU_ITEM_CHECK_MARK + : PART_MENU_ITEM_RADIO_MARK ) ) + { + ControlPart nPart = ((pData->nBits & MIB_RADIOCHECK) + ? PART_MENU_ITEM_RADIO_MARK + : PART_MENU_ITEM_CHECK_MARK); + + ControlState nState = 0; + + if ( pData->bChecked ) + nState |= CTRL_STATE_PRESSED; + + if ( pData->bEnabled ) + nState |= CTRL_STATE_ENABLED; + + if ( bHighlighted ) + nState |= CTRL_STATE_SELECTED; + + long nCtrlHeight = (pData->nBits & MIB_RADIOCHECK) ? nCheckHeight : nRadioHeight; + aTmpPos.X() = aOuterCheckRect.Left() + (aOuterCheckRect.GetWidth() - nCtrlHeight)/2; + aTmpPos.Y() = aOuterCheckRect.Top() + (aOuterCheckRect.GetHeight() - nCtrlHeight)/2; + + Rectangle aCheckRect( aTmpPos, Size( nCtrlHeight, nCtrlHeight ) ); + pWin->DrawNativeControl( CTRL_MENU_POPUP, nPart, + Region( aCheckRect ), + nState, + ImplControlValue(), + OUString() ); + } + else if ( pData->bChecked ) // by default do nothing for unchecked items + { + ImplPaintCheckBackground( pWin, aOuterCheckRect, pThisItemOnly && bHighlighted ); + + SymbolType eSymbol; + Size aSymbolSize; + if ( pData->nBits & MIB_RADIOCHECK ) + { + eSymbol = SYMBOL_RADIOCHECKMARK; + aSymbolSize = Size( nFontHeight/2, nFontHeight/2 ); + } + else + { + eSymbol = SYMBOL_CHECKMARK; + aSymbolSize = Size( (nFontHeight*25)/40, nFontHeight/2 ); + } + aTmpPos.X() = aOuterCheckRect.Left() + (aOuterCheckRect.GetWidth() - aSymbolSize.Width())/2; + aTmpPos.Y() = aOuterCheckRect.Top() + (aOuterCheckRect.GetHeight() - aSymbolSize.Height())/2; + Rectangle aRect( aTmpPos, aSymbolSize ); + aDecoView.DrawSymbol( aRect, eSymbol, pWin->GetTextColor(), nSymbolStyle ); + } + } + } + // Image: if ( !bLayout && !bIsMenuBar && ( ( pData->eType == MENUITEM_IMAGE ) || ( pData->eType == MENUITEM_STRINGIMAGE ) ) ) { // Don't render an image for a check thing if ((nMenuFlags & MENU_FLAG_SHOWCHECKIMAGES) || !pData->HasCheck() ) { - aTmpPos.Y() = aPos.Y(); - aTmpPos.X() = aPos.X() + nImagePos; - aTmpPos.Y() += (pData->aSz.Height()-pData->aImage.GetSizePixel().Height())/2; + if( pData->bChecked ) + ImplPaintCheckBackground( pWin, aOuterCheckRect, pThisItemOnly && bHighlighted ); + aTmpPos = aOuterCheckRect.TopLeft(); + aTmpPos.X() += (aOuterCheckRect.GetWidth()-pData->aImage.GetSizePixel().Width())/2; + aTmpPos.Y() += (aOuterCheckRect.GetHeight()-pData->aImage.GetSizePixel().Height())/2; pWin->DrawImage( aTmpPos, pData->aImage, nImageStyle ); } } @@ -2598,65 +2715,6 @@ void Menu::ImplPaint( Window* pWin, USHORT nBorder, long nStartY, MenuItemData* pWin->DrawCtrlText( aTmpPos, aAccText, 0, aAccText.Len(), nTextStyle ); } - // CheckMark - if ( !bLayout && !bIsMenuBar && pData->HasCheck() ) - { - if ( pWin->IsNativeControlSupported( CTRL_MENU_POPUP, - (pData->nBits & MIB_RADIOCHECK) - ? PART_MENU_ITEM_CHECK_MARK - : PART_MENU_ITEM_RADIO_MARK ) ) - { - ControlPart nPart = ((pData->nBits & MIB_RADIOCHECK) - ? PART_MENU_ITEM_RADIO_MARK - : PART_MENU_ITEM_CHECK_MARK); - - ControlState nState = 0; - - if ( pData->bChecked ) - nState |= CTRL_STATE_PRESSED; - - if ( pData->bEnabled ) - nState |= CTRL_STATE_ENABLED; - - if ( bHighlighted ) - nState |= CTRL_STATE_SELECTED; - - aTmpPos.X() = aPos.X() + nCheckPos; - aTmpPos.Y() = aPos.Y() + nCheckPos; - - long nCtrlHeight = (pData->nBits & MIB_RADIOCHECK) ? nCheckHeight : nRadioHeight; - Rectangle aCheckRect( aTmpPos, Size( nCtrlHeight, nCtrlHeight ) ); - pWin->DrawNativeControl( CTRL_MENU_POPUP, nPart, - Region( aCheckRect ), - nState, - ImplControlValue(), - OUString() ); - } - else if ( pData->bChecked ) // by default do nothing for unchecked items - { - Rectangle aRect; - SymbolType eSymbol; - aTmpPos.Y() = aPos.Y(); - aTmpPos.Y() += nExtra/2; - aTmpPos.Y() += pData->aSz.Height() / 2; - if ( pData->nBits & MIB_RADIOCHECK ) - { - aTmpPos.X() = aPos.X() + nCheckPos; - eSymbol = SYMBOL_RADIOCHECKMARK; - aTmpPos.Y() -= nFontHeight/4; - aRect = Rectangle( aTmpPos, Size( nFontHeight/2, nFontHeight/2 ) ); - } - else - { - aTmpPos.X() = aPos.X() + nCheckPos; - eSymbol = SYMBOL_CHECKMARK; - aTmpPos.Y() -= nFontHeight/4; - aRect = Rectangle( aTmpPos, Size( (nFontHeight*25)/40, nFontHeight/2 ) ); - } - aDecoView.DrawSymbol( aRect, eSymbol, pWin->GetTextColor(), nSymbolStyle ); - } - } - // SubMenu? if ( !bLayout && !bIsMenuBar && pData->pSubMenu ) { diff --git a/vcl/source/window/winproc.cxx b/vcl/source/window/winproc.cxx index d41a861717e9..8c69c2a45daf 100644 --- a/vcl/source/window/winproc.cxx +++ b/vcl/source/window/winproc.cxx @@ -1622,8 +1622,10 @@ void ImplHandleResize( Window* pWindow, long nNewWidth, long nNewHeight ) ImplDestroyHelpWindow( true ); } - if ( ((nNewWidth > 0) && (nNewHeight > 0)) || - pWindow->ImplGetWindow()->ImplGetWindowImpl()->mbAllResize ) + if ( + (nNewWidth > 0 && nNewHeight > 0) || + pWindow->ImplGetWindow()->ImplGetWindowImpl()->mbAllResize + ) { if ( (nNewWidth != pWindow->GetOutputWidthPixel()) || (nNewHeight != pWindow->GetOutputHeightPixel()) ) { @@ -1849,11 +1851,15 @@ static void ImplHandleGetFocus( Window* pWindow ) // nicht alles flackert, wenn diese den Focus bekommen if ( !pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId ) { + bool bCallDirect = ImplGetSVData()->mbIsTestTool; pWindow->ImplGetWindowImpl()->mpFrameData->mbStartFocusState = !pWindow->ImplGetWindowImpl()->mpFrameData->mbHasFocus; - Application::PostUserEvent( pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId, LINK( pWindow, Window, ImplAsyncFocusHdl ) ); + if( ! bCallDirect ) + Application::PostUserEvent( pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId, LINK( pWindow, Window, ImplAsyncFocusHdl ) ); Window* pFocusWin = pWindow->ImplGetWindowImpl()->mpFrameData->mpFocusWin; if ( pFocusWin && pFocusWin->ImplGetWindowImpl()->mpCursor ) pFocusWin->ImplGetWindowImpl()->mpCursor->ImplShow(); + if( bCallDirect ) + pWindow->ImplAsyncFocusHdl( NULL ); } } @@ -1887,15 +1893,19 @@ static void ImplHandleLoseFocus( Window* pWindow ) // Focus-Events zeitverzoegert ausfuehren, damit bei SystemChildFenstern // nicht alles flackert, wenn diese den Focus bekommen + bool bCallDirect = ImplGetSVData()->mbIsTestTool; if ( !pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId ) { pWindow->ImplGetWindowImpl()->mpFrameData->mbStartFocusState = !pWindow->ImplGetWindowImpl()->mpFrameData->mbHasFocus; - Application::PostUserEvent( pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId, LINK( pWindow, Window, ImplAsyncFocusHdl ) ); + if( ! bCallDirect ) + Application::PostUserEvent( pWindow->ImplGetWindowImpl()->mpFrameData->mnFocusId, LINK( pWindow, Window, ImplAsyncFocusHdl ) ); } Window* pFocusWin = pWindow->ImplGetWindowImpl()->mpFrameData->mpFocusWin; if ( pFocusWin && pFocusWin->ImplGetWindowImpl()->mpCursor ) pFocusWin->ImplGetWindowImpl()->mpCursor->ImplHide(); + if( bCallDirect ) + pWindow->ImplAsyncFocusHdl( NULL ); } // ----------------------------------------------------------------------- diff --git a/vcl/unx/gtk/a11y/atktext.cxx b/vcl/unx/gtk/a11y/atktext.cxx index 60975174096a..1c839ed58839 100644 --- a/vcl/unx/gtk/a11y/atktext.cxx +++ b/vcl/unx/gtk/a11y/atktext.cxx @@ -322,9 +322,11 @@ text_wrapper_get_text_at_offset (AtkText *text, * which is the same index as the first character of the next line. In atk the magic offset * '-2' is used to cover this special case. */ - if( -2 == offset && - (ATK_TEXT_BOUNDARY_LINE_START == boundary_type) || - (ATK_TEXT_BOUNDARY_LINE_END == boundary_type) ) + if ( + -2 == offset && + (ATK_TEXT_BOUNDARY_LINE_START == boundary_type || + ATK_TEXT_BOUNDARY_LINE_END == boundary_type) + ) { accessibility::XAccessibleMultiLineText* pMultiLineText = getMultiLineText( text ); if( pMultiLineText ) diff --git a/vcl/unx/gtk/app/gtkinst.cxx b/vcl/unx/gtk/app/gtkinst.cxx index b06a601d177e..2692177c765a 100644 --- a/vcl/unx/gtk/app/gtkinst.cxx +++ b/vcl/unx/gtk/app/gtkinst.cxx @@ -174,21 +174,7 @@ extern "C" pSalData->Init(); pSalData->initNWF(); - const char* pGtkModules = getenv( "GTK_MODULES" ); - if( pGtkModules ) - { - rtl::OString aModules( pGtkModules ); - sal_Int32 nIndex = 0; - while( nIndex >= 0 ) - { - rtl::OString aToken = aModules.getToken( 0, ':', nIndex ); - if( aToken.equals( "gail" ) || aToken.equals( "atk-bridge" ) ) - { - InitAtkBridge(); - break; - } - } - } + InitAtkBridge(); return pInstance; } diff --git a/vcl/unx/gtk/window/gtkframe.cxx b/vcl/unx/gtk/window/gtkframe.cxx index a47b9bf31b01..8aef97904769 100644 --- a/vcl/unx/gtk/window/gtkframe.cxx +++ b/vcl/unx/gtk/window/gtkframe.cxx @@ -783,6 +783,11 @@ void GtkSalFrame::Init( SalFrame* pParent, ULONG nStyle ) ( ! (nStyle & SAL_FRAME_STYLE_FLOAT) || (nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION) ); + /* #i100116# metacity has a peculiar behavior regarding WM_HINT accept focus and _NET_WM_USER_TIME + at some point that may be fixed in metacity and we will have to revisit this + */ + bool bMetaCityToolWindowHack = getDisplay()->getWMAdaptor()->getWindowManagerName().EqualsAscii("Metacity") && + (nStyle & SAL_FRAME_STYLE_TOOLWINDOW ); if( bDecoHandling ) { bool bNoDecor = ! (nStyle & (SAL_FRAME_STYLE_MOVEABLE | SAL_FRAME_STYLE_SIZEABLE | SAL_FRAME_STYLE_CLOSEABLE ) ); @@ -798,7 +803,8 @@ void GtkSalFrame::Init( SalFrame* pParent, ULONG nStyle ) { eType = GDK_WINDOW_TYPE_HINT_UTILITY; gtk_window_set_skip_taskbar_hint( GTK_WINDOW(m_pWindow), true ); - lcl_set_accept_focus( GTK_WINDOW(m_pWindow), FALSE, true ); + if( bMetaCityToolWindowHack ) + lcl_set_accept_focus( GTK_WINDOW(m_pWindow), FALSE, true ); } else if( (nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION) ) { @@ -843,7 +849,7 @@ void GtkSalFrame::Init( SalFrame* pParent, ULONG nStyle ) if( bDecoHandling ) { gtk_window_set_resizable( GTK_WINDOW(m_pWindow), (nStyle & SAL_FRAME_STYLE_SIZEABLE) ? TRUE : FALSE ); - if( ( (nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION) ) || ( (nStyle & SAL_FRAME_STYLE_TOOLWINDOW ) ) ) + if( ( (nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION) ) || bMetaCityToolWindowHack ) lcl_set_accept_focus( GTK_WINDOW(m_pWindow), FALSE, false ); } @@ -1329,7 +1335,10 @@ void GtkSalFrame::Show( BOOL bVisible, BOOL bNoActivate ) if( nUserTime == 0 && ( getDisplay()->getWMAdaptor()->getWindowManagerName().EqualsAscii("Metacity") || - getDisplay()->getWMAdaptor()->getWindowManagerName().EqualsAscii("compiz") + ( + getDisplay()->getWMAdaptor()->getWindowManagerName().EqualsAscii("compiz") && + (m_nStyle & (SAL_FRAME_STYLE_OWNERDRAWDECORATION)) + ) ) ) { @@ -2791,7 +2800,7 @@ gboolean GtkSalFrame::signalMap( GtkWidget*, GdkEvent*, gpointer frame ) GTK_YIELD_GRAB(); - if( GetX11SalData()->isTestTool() ) + if( ImplGetSVData()->mbIsTestTool ) { /* #i76541# testtool needs the focus to be in a new document * however e.g. metacity does not necessarily put the focus into diff --git a/vcl/unx/inc/saldata.hxx b/vcl/unx/inc/saldata.hxx index a4326990c464..2d09bd35649e 100644 --- a/vcl/unx/inc/saldata.hxx +++ b/vcl/unx/inc/saldata.hxx @@ -65,7 +65,6 @@ protected: SalXLib *pXLib_; SalDisplay *m_pSalDisplay; pthread_t hMainThread_; - bool m_bIsTesttool; public: X11SalData(); @@ -90,7 +89,6 @@ public: void StartTimer( ULONG nMS ); inline void StopTimer(); void Timeout() const; - bool isTestTool() const { return m_bIsTesttool; } static int XErrorHdl( Display*, XErrorEvent* ); static int XIOErrorHdl( Display* ); diff --git a/vcl/unx/source/app/saldata.cxx b/vcl/unx/source/app/saldata.cxx index 0f9e21052c50..b1f5a113828f 100644 --- a/vcl/unx/source/app/saldata.cxx +++ b/vcl/unx/source/app/saldata.cxx @@ -277,21 +277,8 @@ X11SalData::X11SalData() m_pSalDisplay = NULL; m_pInstance = NULL; m_pPlugin = NULL; - m_bIsTesttool = false; hMainThread_ = pthread_self(); - - sal_uInt32 nArgs = osl_getCommandArgCount(); - for( sal_uInt32 i = 0; i < nArgs; i++ ) - { - rtl::OUString aArg; - osl_getCommandArg( i, &aArg.pData ); - if( aArg.equalsAscii( "-enableautomation" ) ) - { - m_bIsTesttool = true; - break; - } - } } X11SalData::~X11SalData() diff --git a/vcl/unx/source/fontmanager/fontmanager.cxx b/vcl/unx/source/fontmanager/fontmanager.cxx index 73e117550a14..a116749daf47 100644 --- a/vcl/unx/source/fontmanager/fontmanager.cxx +++ b/vcl/unx/source/fontmanager/fontmanager.cxx @@ -63,9 +63,7 @@ #include "parseAFM.hxx" -#define NO_LIST -#include "sft.h" -#undef NO_LIST +#include "sft.hxx" #if OSL_DEBUG_LEVEL > 1 #include @@ -90,6 +88,7 @@ #define PRINTER_METRICDIR "fontmetric" +using namespace vcl; using namespace utl; using namespace psp; using namespace osl; diff --git a/vcl/unx/source/gdi/salgdi.cxx b/vcl/unx/source/gdi/salgdi.cxx index 1d61dbe214a2..6d7812828a10 100644 --- a/vcl/unx/source/gdi/salgdi.cxx +++ b/vcl/unx/source/gdi/salgdi.cxx @@ -1385,6 +1385,7 @@ bool X11SalGraphics::drawPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly rRenderPeer.FillRectangle( PictOpSrc, rEntry.m_aPicture, &aRenderColor, 0, 0, 1, 1 ); // notify xrender of target drawable + // TODO: cache the matching xrender picture in the X11SalGraphics Picture aDst = rRenderPeer.CreatePicture( hDrawable_, pVisualFormat, 0, NULL ); // set clipping @@ -1396,6 +1397,10 @@ bool X11SalGraphics::drawPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly rRenderPeer.CompositeTrapezoids( PictOpOver, rEntry.m_aPicture, aDst, pMaskFormat, 0, 0, &aTrapVector[0], aTrapVector.size() ); + // release xrender-counterpart of target drawable + // TODO: use scoped xrender picture + rRenderPeer.FreePicture( aDst ); + return TRUE; } diff --git a/vcl/unx/source/plugadapt/salplug.cxx b/vcl/unx/source/plugadapt/salplug.cxx index d76977944c11..668493c6ccb3 100644 --- a/vcl/unx/source/plugadapt/salplug.cxx +++ b/vcl/unx/source/plugadapt/salplug.cxx @@ -101,21 +101,7 @@ static SalInstance* tryInstance( const OUString& rModuleBase ) */ if( rModuleBase.equalsAscii("gtk") ) { - const char* gtk_modules = getenv( "GTK_MODULES" ); - if( gtk_modules ) - { - rtl::OString aModules( gtk_modules ); - sal_Int32 nIndex = 0; - while( nIndex >= 0 ) - { - rtl::OString aToken = aModules.getToken( 0, ':', nIndex ); - if( aToken.equals( "atk-bridge" ) ) - { - pCloseModule = NULL; - break; - } - } - } + pCloseModule = NULL; } GetSalData()->m_pPlugin = aMod; diff --git a/vcl/unx/source/printergfx/glyphset.cxx b/vcl/unx/source/printergfx/glyphset.cxx index 0d26a66cac2f..2a35e975cbab 100644 --- a/vcl/unx/source/printergfx/glyphset.cxx +++ b/vcl/unx/source/printergfx/glyphset.cxx @@ -34,9 +34,7 @@ #include "glyphset.hxx" #include "psputil.hxx" -#define NO_LIST -#include "sft.h" -#undef NO_LIST +#include "sft.hxx" #include "vcl/printergfx.hxx" #include "vcl/fontmanager.hxx" @@ -51,6 +49,7 @@ #include #include +using namespace vcl; using namespace psp; using namespace rtl; diff --git a/vcl/util/makefile.mk b/vcl/util/makefile.mk index 96cf50504ef0..6f5fd8a99522 100644 --- a/vcl/util/makefile.mk +++ b/vcl/util/makefile.mk @@ -190,8 +190,6 @@ SHL1STDLIBS+= \ $(BASEBMPLIB) \ -lAppleRemote$(DLLPOSTFIX) -SHL1STDLIBS+= \ - -framework QTKit LIB1FILES+= \ $(SLB)$/sala11y.lib .ENDIF diff --git a/vcl/win/source/gdi/salgdi3.cxx b/vcl/win/source/gdi/salgdi3.cxx index 70701e2ee19a..16c055209088 100644 --- a/vcl/win/source/gdi/salgdi3.cxx +++ b/vcl/win/source/gdi/salgdi3.cxx @@ -64,8 +64,7 @@ #include "basegfx/polygon/b2dpolypolygon.hxx" #include "basegfx/matrix/b2dhommatrix.hxx" -#include -#include +#include "sft.hxx" #ifdef GCP_KERN_HACK #include @@ -76,6 +75,8 @@ #include +using namespace vcl; + static const int MAXFONTHEIGHT = 2048; // ----------- diff --git a/vcl/win/source/gdi/winlayout.cxx b/vcl/win/source/gdi/winlayout.cxx index 34900aaa951a..0689b8710655 100755 --- a/vcl/win/source/gdi/winlayout.cxx +++ b/vcl/win/source/gdi/winlayout.cxx @@ -36,7 +36,7 @@ #include "salgdi.h" #include "saldata.hxx" // for GetMirroredChar -#include "sft.h" +#include "sft.hxx" #include "vcl/sallayout.hxx" #include "vcl/svapp.hxx" @@ -2441,9 +2441,9 @@ void UniscribeLayout::ApplyDXArray( const ImplLayoutArgs& rArgs ) if( rVisualItem.IsRTL() ) { for( i = rVisualItem.mnMinGlyphPos; i < rVisualItem.mnEndGlyphPos; ++i ) - if ( (1U << mpVisualAttrs[i].uJustification) & 0xFF89 ) // any Arabic justification ? - { // the last SCRIPT_JUSTIFY_xxx - // yes // == 15 (usp 1.6) + if ( (1U << mpVisualAttrs[i].uJustification) & 0xFF82 ) // any Arabic justification + { // excluding SCRIPT_JUSTIFY_NONE + // yes rVisualItem.mbHasKashidas = true; // so prepare for kashida handling InitKashidaHandling(); @@ -2509,10 +2509,14 @@ void UniscribeLayout::ApplyDXArray( const ImplLayoutArgs& rArgs ) for( i = nMinGlyphPos; i < nEndGlyphPos; ++i ) { const int nXOffsetAdjust = mpJustifications[i] - mpGlyphAdvances[i]; - if( i == nMinGlyphPos ) + // #i99862# skip diacritics, we mustn't add extra justification to diacritics + int nIdxAdd = i - 1; + while( (nIdxAdd >= nMinGlyphPos) && !mpGlyphAdvances[nIdxAdd] ) + --nIdxAdd; + if( nIdxAdd < nMinGlyphPos ) rVisualItem.mnXOffset += nXOffsetAdjust; else - mpJustifications[i-1] += nXOffsetAdjust; + mpJustifications[nIdxAdd] += nXOffsetAdjust; mpJustifications[i] -= nXOffsetAdjust; } } @@ -2540,8 +2544,8 @@ void UniscribeLayout::KashidaItemFix( int nMinGlyphPos, int nEndGlyphPos ) { // check for vowels if( (i > nMinGlyphPos && !mpGlyphAdvances[ i-1 ]) - && (1U << mpVisualAttrs[i].uJustification) & 0xFF89 ) - { + && (1U << mpVisualAttrs[i].uJustification) & 0xFF83 ) // all Arabic justifiction types + { // including SCRIPT_JUSTIFY_NONE // vowel, we do it like ScriptJustify does // the vowel gets the extra width long nSpaceAdded = mpJustifications[ i ] - mpGlyphAdvances[ i ]; -- cgit From 09c7b55d7df42519027d0125ad7e0a01c8fa9d4b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 22 Apr 2009 08:23:48 +0000 Subject: fix a warning --- vcl/source/window/printdlg.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index bc6e22d2283a..398bac4d7e43 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -741,8 +741,8 @@ void PrintDialog::preparePreview() void PrintDialog::updateNup() { - int nRows = maPrinterPage.maNupRowsEdt.GetValue(); - int nCols = maPrinterPage.maNupColEdt.GetValue(); + int nRows = int(maPrinterPage.maNupRowsEdt.GetValue()); + int nCols = int(maPrinterPage.maNupColEdt.GetValue()); maPListener->setMultipage( nRows, nCols, maPrinterPage.maNupPortrait.IsChecked() -- cgit From f0a717315d35423a70308ce84638caba6ca8822c Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 23 Apr 2009 15:53:27 +0000 Subject: #101241# IntValue can be from NumericField which is a sal_Int64 --- vcl/inc/vcl/print.hxx | 4 ++-- vcl/source/gdi/print3.cxx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 93b635756e95..1cff0331a704 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -532,9 +532,9 @@ class VCL_DLLPUBLIC PrinterOptionsHelper sal_Bool getBoolValue( const char* i_pPropName, sal_Bool i_bDefault = sal_False ) const { return getBoolValue( rtl::OUString::createFromAscii( i_pPropName ), i_bDefault ); } - sal_Int32 getIntValue( const rtl::OUString& i_rPropertyName, sal_Int32 i_nDefault = 0 ) const; + sal_Int64 getIntValue( const rtl::OUString& i_rPropertyName, sal_Int64 i_nDefault = 0 ) const; // convenience for fixed strings - sal_Int32 getIntValue( const char* i_pPropName, sal_Int32 i_nDefault = 0 ) const + sal_Int64 getIntValue( const char* i_pPropName, sal_Int64 i_nDefault = 0 ) const { return getIntValue( rtl::OUString::createFromAscii( i_pPropName ), i_nDefault ); } rtl::OUString getStringValue( const rtl::OUString& i_rPropertyName, const rtl::OUString& i_rDefault = rtl::OUString() ) const; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 63e27b5b3a5f..0623230ae085 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -832,9 +832,9 @@ sal_Bool PrinterOptionsHelper::getBoolValue( const rtl::OUString& i_rPropertyNam return (aVal >>= bRet) ? bRet : i_bDefault; } -sal_Int32 PrinterOptionsHelper::getIntValue( const rtl::OUString& i_rPropertyName, sal_Int32 i_nDefault ) const +sal_Int64 PrinterOptionsHelper::getIntValue( const rtl::OUString& i_rPropertyName, sal_Int64 i_nDefault ) const { - sal_Int32 nRet = 0; + sal_Int64 nRet = 0; Any aVal( getValue( i_rPropertyName ) ); return (aVal >>= nRet) ? nRet : i_nDefault; } -- cgit From 060f36af7d35aaa8a7c9c28d9a8a1a6bf6a684e0 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 24 Apr 2009 09:43:48 +0000 Subject: #i92516# avoid unnecessary calls to render the current page --- vcl/inc/vcl/prndlg.hxx | 6 +++++- vcl/source/window/printdlg.cxx | 48 +++++++++++++++++++++++++++++------------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index c44bda8a2711..24ea0ea6a3e3 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -56,6 +56,8 @@ namespace vcl class PrintPreviewWindow : public Window { GDIMetaFile maMtf; + double mfScaleX; + double mfScaleY; public: PrintPreviewWindow( Window* pParent, const ResId& ); virtual ~PrintPreviewWindow(); @@ -63,6 +65,7 @@ namespace vcl virtual void Paint( const Rectangle& rRect ); void setPreview( const GDIMetaFile& ); + void setScale( double fScaleX, double fScaleY ); }; class PrinterTabPage : public TabPage @@ -135,6 +138,7 @@ namespace vcl sal_Int32 mnCurPage; sal_Int32 mnCachedPages; Rectangle maPreviewSpace; + Size maCurPageSize; std::list< Window* > maControls; std::map< Window*, rtl::OUString > maControlToPropertyMap; @@ -145,7 +149,7 @@ namespace vcl Size maNupLandscapeSize; void updateNup(); - void preparePreview(); + void preparePreview( bool i_bPrintChanged = true ); void setPreviewText( sal_Int32 ); void updatePrinterText(); void checkControlDependencies(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 398bac4d7e43..39e9f97f7290 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -51,7 +51,9 @@ using namespace com::sun::star::uno; using namespace com::sun::star::beans; PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) - : Window( i_pParent, i_rId ) + : Window( i_pParent, i_rId ), + mfScaleX( 1 ), + mfScaleY( 1 ) { } @@ -63,13 +65,17 @@ void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) { Window::Paint( i_rRect ); + GDIMetaFile aMtf( maMtf ); + SetFillColor( Color( COL_WHITE ) ); SetLineColor(); DrawRect( Rectangle( Point( 0, 0 ), GetSizePixel() )); Push(); SetMapMode( MAP_100TH_MM ); - maMtf.WindStart(); - maMtf.Play( this, Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ); + aMtf.WindStart(); + aMtf.Scale( mfScaleX, mfScaleY ); + aMtf.WindStart(); + aMtf.Play( this, Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ); Pop(); } @@ -79,6 +85,13 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi Invalidate(); } +void PrintDialog::PrintPreviewWindow::setScale( double fScaleX, double fScaleY ) +{ + mfScaleX = fScaleX; + mfScaleY = fScaleY; + Invalidate(); +} + PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) @@ -694,7 +707,7 @@ void PrintDialog::setPreviewText( sal_Int32 nSetPage ) maPageText.SetText( maNoPageStr ); } -void PrintDialog::preparePreview() +void PrintDialog::preparePreview( bool i_bNewPage ) { // page range may have changed depending on options sal_Int32 nPages = maPListener->getFilteredPageCount(); @@ -714,29 +727,34 @@ void PrintDialog::preparePreview() boost::shared_ptr aPrt( maPListener->getPrinter() ); - const MapMode aMapMode( MAP_100TH_MM ); - GDIMetaFile aMtf; - Size aPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); + if( i_bNewPage ) + { + const MapMode aMapMode( MAP_100TH_MM ); + GDIMetaFile aMtf; + maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); + + maPreviewWindow.setPreview( aMtf ); + } Size aPreviewSize; Point aPreviewPos = maPreviewSpace.TopLeft(); const long nW = maPreviewSpace.GetSize().Width(); const long nH = maPreviewSpace.GetSize().Height(); - if( aPageSize.Width() > aPageSize.Height() ) + if( maCurPageSize.Width() > maCurPageSize.Height() ) { - aPreviewSize = Size( nW, nW * aPageSize.Height() / aPageSize.Width() ); + aPreviewSize = Size( nW, nW * maCurPageSize.Height() / maCurPageSize.Width() ); aPreviewPos.Y() += (maPreviewSpace.GetHeight() - aPreviewSize.Height())/2; } else { - aPreviewSize = Size( nH * aPageSize.Width() / aPageSize.Height(), nH ); + aPreviewSize = Size( nH * maCurPageSize.Width() / maCurPageSize.Height(), nH ); aPreviewPos.X() += (maPreviewSpace.GetWidth() - aPreviewSize.Width())/2; } + maPreviewWindow.SetPosSizePixel( aPreviewPos, aPreviewSize ); const Size aLogicSize( maPreviewWindow.PixelToLogic( maPreviewWindow.GetSizePixel(), MapMode( MAP_100TH_MM ) ) ); - aMtf.Scale( double(aLogicSize.Width())/double(aPageSize.Width()), - double(aLogicSize.Height())/double(aPageSize.Height()) ); - maPreviewWindow.setPreview( aMtf ); + maPreviewWindow.setScale( double(aLogicSize.Width())/double(maCurPageSize.Width()), + double(aLogicSize.Height())/double(maCurPageSize.Height()) ); } void PrintDialog::updateNup() @@ -989,8 +1007,8 @@ void PrintDialog::Resize() aBtnRect.Bottom() = aBtnRect.Top() + maPageText.GetSizePixel().Height() - 1; maPageText.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - // and do the preview - preparePreview(); + // and do the preview; however the metafile does not need to be gotten anew + preparePreview( false ); } // ----------------------------------------------------------------------------- -- cgit From fb285c9745d6e3b6e0a00830e703adcfe0e6c230 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 24 Apr 2009 13:15:04 +0000 Subject: #i101242# release options helper on last page --- vcl/aqua/source/gdi/salprn.cxx | 10 ++++++++++ vcl/inc/vcl/print.hxx | 1 + vcl/source/gdi/print3.cxx | 27 ++++++++++++++++++++++++++- 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index e70f359bbe85..f7e08cf4804c 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -493,6 +493,9 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, bool bNeedRestart = true; sal_Int32 nAllPages = 1; + // reset IsLastPage + i_rListener.setLastPage( sal_False ); + // update job data if( i_pSetupData ) SetData( ~0, i_pSetupData ); @@ -588,6 +591,13 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, mnCurPageRangeCount = 1; } while( bNeedRestart && mnCurPageRangeCount < nAllPages ); + // inform applictation that it can release its data + // this is awkward, but the XRenderable interface has no method for this, + // so we need to call XRenderadble::render one last time with IsLastPage = TRUE + i_rListener.setLastPage( sal_True ); + GDIMetaFile aPageFile; + Size aPageSize = i_rListener.getFilteredPageFile( 0, aPageFile ); + mnCurPageRangeStart = mnCurPageRangeCount = 0; return bSuccess; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 1cff0331a704..a757684a7eff 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -496,6 +496,7 @@ public: void SAL_DLLPRIVATE createProgressDialog(); void SAL_DLLPRIVATE setPrintSelection( const rtl::OUString& ); void SAL_DLLPRIVATE setMultipage( int nRows, int nColumns, const Size& rPaperSize ); + void SAL_DLLPRIVATE setLastPage( sal_Bool i_bLastPage ); }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 0623230ae085..74aae6936609 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -79,6 +79,7 @@ public: Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; rtl::OUString maSelectionString; + sal_Bool mbLastPage; int mnMultiPageRows; int mnMultiPageColumns; @@ -88,6 +89,7 @@ public: ImplPrinterListenerData() : maSelectionString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), + mbLastPage( sal_False ), mnMultiPageRows( 1 ), mnMultiPageColumns( 1 ), mpProgress( NULL ) @@ -202,6 +204,9 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->setPrinter( pPrinter ); } + // reset last page property + i_pListener->setLastPage( sal_False ); + // check if the printer brings up its own dialog // in that case leave the work to that dialog const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); @@ -212,7 +217,12 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene { PrintDialog aDlg( NULL, i_pListener ); if( ! aDlg.Execute() ) + { + GDIMetaFile aPageFile; + i_pListener->setLastPage( sal_True ); + Size aPageSize = i_pListener->getFilteredPageFile( 0, aPageFile ); return; + } if( aDlg.isPrintToFile() ) { rtl::OUString aFile = queryFile( pListener->getPrinter().get() ); @@ -330,6 +340,8 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrgetFilteredPageCount(); for( int nPage = 0; nPage < nPages; nPage++ ) { + if( nPage == nPages-1 ) + i_pListener->setLastPage( sal_True ); i_pListener->printFilteredPage( nPage ); } EndJob(); @@ -620,10 +632,15 @@ void PrinterListener::jobFinished() { } +void PrinterListener::setLastPage( sal_Bool i_bLastPage ) +{ + mpImplData->mbLastPage = i_bLastPage; +} + Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const { std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; - size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 1; + size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 2; for( int i = 0; i < i_rMergeList.getLength(); i++ ) aMergeSet.insert( i_rMergeList[i].Name ); @@ -644,6 +661,14 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro aVal.Value <<= mpImplData->maSelectionString; aResult[nCur++] = aVal; } + // append IsLastPage + if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsLastPage" ) ) ) == aMergeSet.end() ) + { + PropertyValue aVal; + aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsLastPage" ) ); + aVal.Value <<= mpImplData->mbLastPage; + aResult[nCur++] = aVal; + } aResult.realloc( nCur ); return aResult; } -- cgit From a34d3936c81cdd3997ef5783c6c49f1239ba1f5b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 24 Apr 2009 13:21:25 +0000 Subject: #i101241# IsPrinter property --- vcl/source/gdi/print3.cxx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 74aae6936609..cee64726581d 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -640,7 +640,7 @@ void PrinterListener::setLastPage( sal_Bool i_bLastPage ) Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const { std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; - size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 2; + size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 3; for( int i = 0; i < i_rMergeList.getLength(); i++ ) aMergeSet.insert( i_rMergeList[i].Name ); @@ -669,6 +669,14 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro aVal.Value <<= mpImplData->mbLastPage; aResult[nCur++] = aVal; } + // append IsPrinter + if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsPrinter" ) ) ) == aMergeSet.end() ) + { + PropertyValue aVal; + aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsPrinter" ) ); + aVal.Value <<= sal_True; + aResult[nCur++] = aVal; + } aResult.realloc( nCur ); return aResult; } -- cgit From 2332ec48eb9166e8bcd0b205da730b2e955d8ec8 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 24 Apr 2009 15:39:41 +0000 Subject: #i92516# help ids for fixed controls --- vcl/source/window/printdlg.cxx | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 39e9f97f7290..e76ce4298474 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -50,6 +50,8 @@ using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; +#define SMHID( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( ".HelpId:vcl:PrintDialog:" a ":" b ) ) ) ) + PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ), mfScaleX( 1 ), @@ -113,6 +115,23 @@ PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rRe , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) { FreeResource(); + maPrinters.SMHID( "PrinterPage", "PrinterList" ); + maSetupButton.SMHID( "PrinterPage", "Setup" ); + maType.SMHID( "PrinterPage", "Type" ); + maTypeText.SMHID( "PrinterPage", "TypeText" ); + maStatus.SMHID( "PrinterPage", "Status" ); + maStatusText.SMHID( "PrinterPage", "StatusText" ); + maLocation.SMHID( "PrinterPage", "Locaction" ); + maLocText.SMHID( "PrinterPage", "LocactionText" ); + maComment.SMHID( "PrinterPage", "Comment" ); + maCommentText.SMHID( "PrinterPage", "CommentText" ); + maNupLine.SMHID( "PrinterPage", "NUPline" ); + maNupRowsTxt.SMHID( "PrinterPage", "NUPRowsText" ); + maNupRowsEdt.SMHID( "PrinterPage", "NUPRows" ); + maNupColTxt.SMHID( "PrinterPage", "NUPColumnsText" ); + maNupColEdt.SMHID( "PrinterPage", "NUPColumns" ); + maNupPortrait.SMHID( "PrinterPage", "NUPPortrait" ); + maNupLandscape.SMHID( "PrinterPage", "NUPLandscape" ); } PrintDialog::PrinterTabPage::~PrinterTabPage() @@ -139,6 +158,18 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) { FreeResource(); + maPrinters.SMHID( "JobPage", "PrinterList" ); + maToFileBox.SMHID( "JobPage", "ToFile" ); + maPrintRange.SMHID( "JobPage", "PrintRange" ); + maAllButton.SMHID( "JobPage", "AllButton" ); + maPagesButton.SMHID( "JobPage", "PagesButton" ); + maSelectionButton.SMHID( "JobPage", "SelectionButton" ); + maPagesEdit.SMHID( "JobPage", "Pages" ); + maCopies.SMHID( "JobPage", "CopiesLine" ); + maCopyCount.SMHID( "JobPage", "CopiesText" ); + maCopyCountField.SMHID( "JobPage", "Copies" ); + maCollateBox.SMHID( "JobPage", "Collate" ); + maCollateImage.SMHID( "JobPage", "CollateImage" ); } PrintDialog::JobTabPage::~JobTabPage() -- cgit From 28d7db7c3c0d52c923da67814f9bb40db9cc9304 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 27 Apr 2009 09:47:17 +0000 Subject: #i92516# add help ids --- vcl/source/window/printdlg.cxx | 124 ++++++++++++++++++++++++++++++----------- 1 file changed, 93 insertions(+), 31 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index e76ce4298474..b704e46ed392 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -50,7 +50,9 @@ using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; -#define SMHID( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( ".HelpId:vcl:PrintDialog:" a ":" b ) ) ) ) +#define HELPID_PREFIX ".HelpId:vcl:PrintDialog" +#define SMHID2( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ":" b ) ) ) ) +#define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ) ) ) PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ), @@ -115,23 +117,23 @@ PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rRe , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) { FreeResource(); - maPrinters.SMHID( "PrinterPage", "PrinterList" ); - maSetupButton.SMHID( "PrinterPage", "Setup" ); - maType.SMHID( "PrinterPage", "Type" ); - maTypeText.SMHID( "PrinterPage", "TypeText" ); - maStatus.SMHID( "PrinterPage", "Status" ); - maStatusText.SMHID( "PrinterPage", "StatusText" ); - maLocation.SMHID( "PrinterPage", "Locaction" ); - maLocText.SMHID( "PrinterPage", "LocactionText" ); - maComment.SMHID( "PrinterPage", "Comment" ); - maCommentText.SMHID( "PrinterPage", "CommentText" ); - maNupLine.SMHID( "PrinterPage", "NUPline" ); - maNupRowsTxt.SMHID( "PrinterPage", "NUPRowsText" ); - maNupRowsEdt.SMHID( "PrinterPage", "NUPRows" ); - maNupColTxt.SMHID( "PrinterPage", "NUPColumnsText" ); - maNupColEdt.SMHID( "PrinterPage", "NUPColumns" ); - maNupPortrait.SMHID( "PrinterPage", "NUPPortrait" ); - maNupLandscape.SMHID( "PrinterPage", "NUPLandscape" ); + maPrinters.SMHID2( "PrinterPage", "PrinterList" ); + maSetupButton.SMHID2( "PrinterPage", "Setup" ); + maType.SMHID2( "PrinterPage", "Type" ); + maTypeText.SMHID2( "PrinterPage", "TypeText" ); + maStatus.SMHID2( "PrinterPage", "Status" ); + maStatusText.SMHID2( "PrinterPage", "StatusText" ); + maLocation.SMHID2( "PrinterPage", "Locaction" ); + maLocText.SMHID2( "PrinterPage", "LocactionText" ); + maComment.SMHID2( "PrinterPage", "Comment" ); + maCommentText.SMHID2( "PrinterPage", "CommentText" ); + maNupLine.SMHID2( "PrinterPage", "NUPline" ); + maNupRowsTxt.SMHID2( "PrinterPage", "NUPRowsText" ); + maNupRowsEdt.SMHID2( "PrinterPage", "NUPRows" ); + maNupColTxt.SMHID2( "PrinterPage", "NUPColumnsText" ); + maNupColEdt.SMHID2( "PrinterPage", "NUPColumns" ); + maNupPortrait.SMHID2( "PrinterPage", "NUPPortrait" ); + maNupLandscape.SMHID2( "PrinterPage", "NUPLandscape" ); } PrintDialog::PrinterTabPage::~PrinterTabPage() @@ -158,18 +160,18 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) { FreeResource(); - maPrinters.SMHID( "JobPage", "PrinterList" ); - maToFileBox.SMHID( "JobPage", "ToFile" ); - maPrintRange.SMHID( "JobPage", "PrintRange" ); - maAllButton.SMHID( "JobPage", "AllButton" ); - maPagesButton.SMHID( "JobPage", "PagesButton" ); - maSelectionButton.SMHID( "JobPage", "SelectionButton" ); - maPagesEdit.SMHID( "JobPage", "Pages" ); - maCopies.SMHID( "JobPage", "CopiesLine" ); - maCopyCount.SMHID( "JobPage", "CopiesText" ); - maCopyCountField.SMHID( "JobPage", "Copies" ); - maCollateBox.SMHID( "JobPage", "Collate" ); - maCollateImage.SMHID( "JobPage", "CollateImage" ); + maPrinters.SMHID2( "JobPage", "PrinterList" ); + maToFileBox.SMHID2( "JobPage", "ToFile" ); + maPrintRange.SMHID2( "JobPage", "PrintRange" ); + maAllButton.SMHID2( "JobPage", "AllButton" ); + maPagesButton.SMHID2( "JobPage", "PagesButton" ); + maSelectionButton.SMHID2( "JobPage", "SelectionButton" ); + maPagesEdit.SMHID2( "JobPage", "Pages" ); + maCopies.SMHID2( "JobPage", "CopiesLine" ); + maCopyCount.SMHID2( "JobPage", "CopiesText" ); + maCopyCountField.SMHID2( "JobPage", "Copies" ); + maCollateBox.SMHID2( "JobPage", "Collate" ); + maCollateImage.SMHID2( "JobPage", "CollateImage" ); } PrintDialog::JobTabPage::~JobTabPage() @@ -291,6 +293,14 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr 1 ? maJobPage.maCollateBox.IsChecked() : FALSE; } +static void setSmartId( Window* i_pWindow, const char* i_pType, sal_Int32 i_nId = -1, const rtl::OUString& i_rPropName = rtl::OUString() ) +{ + rtl::OUStringBuffer aBuf( 256 ); + aBuf.appendAscii( HELPID_PREFIX ); + if( i_rPropName.getLength() ) + { + aBuf.append( sal_Unicode( ':' ) ); + aBuf.append( i_rPropName ); + } + if( i_pType ) + { + aBuf.append( sal_Unicode( ':' ) ); + aBuf.appendAscii( i_pType ); + } + if( i_nId >= 0 ) + { + aBuf.append( sal_Unicode( ':' ) ); + aBuf.append( i_nId ); + } + i_pWindow->SetSmartHelpId( SmartId( aBuf.makeStringAndClear() ) ); +} + void PrintDialog::setupOptionalUI() { Window* pCurParent = 0; long nCurY = 0, nXPos = 5, nMaxY = 0; - USHORT nOptPageId = 9; + USHORT nOptPageId = 9, nCurSubGroup = 0; MapMode aFontMapMode( MAP_APPFONT ); Size aTabSize = maTabCtrl.GetTabPageSizePixel(); @@ -423,6 +455,12 @@ void PrintDialog::setupOptionalUI() pNewGroup->SetText( aText ); maTabCtrl.InsertPage( ++nOptPageId, aText ); maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); + + // set help id + setSmartId( pNewGroup, "TabPage", nOptPageId ); + + // reset subgroup counter + nCurSubGroup = 0; } if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) @@ -440,6 +478,9 @@ void PrintDialog::setupOptionalUI() pNewSub->Show(); nCurY += 12; nXPos += 5; + + // set help id + setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); } else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { @@ -465,6 +506,9 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); maControlToPropertyMap[pNewBox] = aPropertyName; + // set help id + setSmartId( pNewBox, "CheckBox", -1, aPropertyName ); + } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -483,6 +527,9 @@ void PrintDialog::setupOptionalUI() nXPos += 10; nCurY += 12; + + // set help id + setSmartId( pHeading, "FixedText", -1, aPropertyName ); } // iterate options @@ -507,6 +554,9 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pBtn] = aPropertyName; maControlToNumValMap[pBtn] = m; + // set help id + setSmartId( pBtn, "RadioButton", m, aPropertyName ); + nCurY += 12; } nXPos = nOldXPos; @@ -523,6 +573,9 @@ void PrintDialog::setupOptionalUI() aPixelSize ); pHeading->Show(); + // set help id + setSmartId( pHeading, "FixedText", -1, aPropertyName ); + ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); maControls.push_front( pList ); @@ -567,6 +620,9 @@ void PrintDialog::setupOptionalUI() pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); pList->Show(); + // set help id + setSmartId( pList, "ListBox", -1, aPropertyName ); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); maControlToPropertyMap[pList] = aPropertyName; nCurY += 16; @@ -591,6 +647,9 @@ void PrintDialog::setupOptionalUI() aPixelSize ); pHeading->Show(); + // set help id + setSmartId( pHeading, "FixedText", -1, aPropertyName ); + NumericField* pField = new NumericField( pCurParent, WB_BORDER | WB_SPIN ); maControls.push_front( pField ); @@ -629,6 +688,9 @@ void PrintDialog::setupOptionalUI() pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); + // set help id + setSmartId( pField, "NumericField", -1, aPropertyName ); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); maControlToPropertyMap[pField] = aPropertyName; nCurY += 16; -- cgit From 1845fc4790d475720db8476444cce65d56065805 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 27 Apr 2009 16:11:03 +0000 Subject: #i92516# HelpTexts for new print UI --- vcl/inc/vcl/print.hxx | 8 +++++-- vcl/source/gdi/print3.cxx | 47 ++++++++++++++++++++++++++++++++++++------ vcl/source/window/printdlg.cxx | 35 ++++++++++++++++++++++++++++++- 3 files changed, 81 insertions(+), 9 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index a757684a7eff..48878199cb98 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -547,6 +547,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // general control static com::sun::star::uno::Any getUIControlOpt( const rtl::OUString& i_rTitle, + const com::sun::star::uno::Sequence< rtl::OUString >& i_rHelpText, const rtl::OUString& i_rType, const com::sun::star::beans::PropertyValue* i_pVal = NULL, const com::sun::star::uno::Sequence< rtl::OUString >* i_pChoices = NULL, @@ -556,14 +557,15 @@ class VCL_DLLPUBLIC PrinterOptionsHelper ); // create a group (e.g. a TabPage); following controls will be grouped in it until the next // group begins - static com::sun::star::uno::Any getGroupControlOpt( const rtl::OUString& i_rTitle ); + static com::sun::star::uno::Any getGroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ); // create a subgroup (e.g. a FixedLine); following controls will be grouped in it until the next // subgroup or group begins - static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle ); + static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ); // create a bool option (usually a checkbox) static com::sun::star::uno::Any getBoolControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Bool i_bValue, const rtl::OUString* i_pDependsOnName = NULL, @@ -572,6 +574,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // create a set of choices (either a radio button group or a list box) static com::sun::star::uno::Any getChoiceControlOpt( const rtl::OUString& i_rTitle, + const com::sun::star::uno::Sequence< rtl::OUString >& i_rHelpText, const rtl::OUString& i_rProperty, const com::sun::star::uno::Sequence< rtl::OUString >& i_rChoices, sal_Int32 i_nValue, @@ -583,6 +586,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // create an integer range (e.g. a spin field) // note: max value < min value means do not apply min/max values static com::sun::star::uno::Any getRangeControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Int32 i_nValue, sal_Int32 i_nMinValue = -1, diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index cee64726581d..14735ff42413 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -928,6 +928,7 @@ void PrinterOptionsHelper::appendPrintUIOptions( uno::Sequence< beans::PropertyV } Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + const Sequence< rtl::OUString >& i_rHelpTexts, const rtl::OUString& i_rType, const PropertyValue* i_pVal, const Sequence< rtl::OUString >* i_pChoices, @@ -940,6 +941,7 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, sal_Int32 nElements = 1 // ControlType + (i_rTitle.getLength() ? 1 : 0) // Text + + (i_rHelpTexts.getLength() ? 1 : 0) // HelpText + (i_pVal ? 1 : 0) // Property + (i_pChoices ? 1 : 0) // Choices + (i_pDependsOnName ? (i_nDependsOnEntry != -1 ? 2 : 1) : 0) // dependencies @@ -953,6 +955,11 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ) ); aCtrl[nUsed++].Value = makeAny( i_rTitle ); } + if( i_rHelpTexts.getLength() ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "HelpText" ) ); + aCtrl[nUsed++].Value = makeAny( i_rHelpTexts ); + } aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ControlType" ) ); aCtrl[nUsed++].Value = makeAny( i_rType ); if( i_pVal ) @@ -988,30 +995,50 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, return makeAny( aCtrl ); } -Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle ) +Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ) { - return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Group" ) ) ); + Sequence< rtl::OUString > aHelpText; + if( i_rHelpText.getLength() > 0 ) + { + aHelpText.realloc( 1 ); + *aHelpText.getArray() = i_rHelpText; + } + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Group" ) ) ); } -Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle ) +Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ) { - return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ) ); + Sequence< rtl::OUString > aHelpText; + if( i_rHelpText.getLength() > 0 ) + { + aHelpText.realloc( 1 ); + *aHelpText.getArray() = i_rHelpText; + } + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ) ); } Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Bool i_bValue, const rtl::OUString* i_pDependsOnName, sal_Int32 i_nDependsOnEntry ) { + Sequence< rtl::OUString > aHelpText; + if( i_rHelpText.getLength() > 0 ) + { + aHelpText.realloc( 1 ); + *aHelpText.getArray() = i_rHelpText; + } PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_bValue ); - return getUIControlOpt( i_rTitle, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, NULL, i_pDependsOnName, i_nDependsOnEntry ); + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, NULL, i_pDependsOnName, i_nDependsOnEntry ); } Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, + const Sequence< rtl::OUString >& i_rHelpText, const rtl::OUString& i_rProperty, const Sequence< rtl::OUString >& i_rChoices, sal_Int32 i_nValue, @@ -1023,10 +1050,11 @@ Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_nValue ); - return getUIControlOpt( i_rTitle, i_rType, &aVal, &i_rChoices, i_pDependsOnName, i_nDependsOnEntry ); + return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, &i_rChoices, i_pDependsOnName, i_nDependsOnEntry ); } Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Int32 i_nValue, sal_Int32 i_nMinValue, @@ -1035,10 +1063,17 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nDependsOnEntry ) { + Sequence< rtl::OUString > aHelpText; + if( i_rHelpText.getLength() > 0 ) + { + aHelpText.realloc( 1 ); + *aHelpText.getArray() = i_rHelpText; + } PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_nValue ); return getUIControlOpt( i_rTitle, + aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Range" ) ), &aVal, NULL, diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index b704e46ed392..b8a2a1a21910 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -349,6 +349,12 @@ static void setSmartId( Window* i_pWindow, const char* i_pType, sal_Int32 i_nId i_pWindow->SetSmartHelpId( SmartId( aBuf.makeStringAndClear() ) ); } +static void setHelpText( Window* i_pWindow, const Sequence< rtl::OUString >& i_rHelpTexts, sal_Int32 i_nIndex ) +{ + if( i_nIndex >= 0 && i_nIndex < i_rHelpTexts.getLength() ) + i_pWindow->SetHelpText( i_rHelpTexts.getConstArray()[i_nIndex] ); +} + void PrintDialog::setupOptionalUI() { Window* pCurParent = 0; @@ -369,8 +375,10 @@ void PrintDialog::setupOptionalUI() rtl::OUString aText; rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; + Sequence< rtl::OUString > aHelpTexts; sal_Int64 nMinValue = 0, nMaxValue = 0; long nDependencyIndent = 0; + sal_Int32 nCurHelpText = 0; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -432,6 +440,18 @@ void PrintDialog::setupOptionalUI() { rEntry.Value >>= nMaxValue; } + else if( rEntry.Name.equalsAscii( "HelpText" ) ) + { + if( ! (rEntry.Value >>= aHelpTexts) ) + { + rtl::OUString aHelpText; + if( (rEntry.Value >>= aHelpText) ) + { + aHelpTexts.realloc( 1 ); + *aHelpTexts.getArray() = aHelpText; + } + } + } } if( aCtrlType.equalsAscii( "Group" ) || @@ -458,6 +478,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pNewGroup, "TabPage", nOptPageId ); + // set help text + setHelpText( pNewGroup, aHelpTexts, 0 ); // reset subgroup counter nCurSubGroup = 0; @@ -481,6 +503,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); + // set help text + setHelpText( pNewSub, aHelpTexts, 0 ); } else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { @@ -508,7 +532,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pNewBox, "CheckBox", -1, aPropertyName ); - + // set help text + setHelpText( pNewBox, aHelpTexts, 0 ); } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -530,6 +555,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pHeading, "FixedText", -1, aPropertyName ); + // set help text + setHelpText( pHeading, aHelpTexts, nCurHelpText++ ); } // iterate options @@ -556,6 +583,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pBtn, "RadioButton", m, aPropertyName ); + // set help text + setHelpText( pBtn, aHelpTexts, nCurHelpText++ ); nCurY += 12; } @@ -622,6 +651,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pList, "ListBox", -1, aPropertyName ); + // set help text + setHelpText( pList, aHelpTexts, 0 ); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); maControlToPropertyMap[pList] = aPropertyName; @@ -690,6 +721,8 @@ void PrintDialog::setupOptionalUI() // set help id setSmartId( pField, "NumericField", -1, aPropertyName ); + // set help text + setHelpText( pField, aHelpTexts, 0 ); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); maControlToPropertyMap[pField] = aPropertyName; -- cgit From e9de7039fd558700fb4ae953ad5b2939b099c6b5 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Apr 2009 09:49:55 +0000 Subject: #i92516# pass selection or whole document to XRenderable interface --- vcl/inc/vcl/print.hxx | 6 ++++++ vcl/source/gdi/print3.cxx | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 48878199cb98..ab08a9ef7e56 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -456,6 +456,12 @@ public: com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getJobProperties( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rMergeList ) const; + /* get the current selection string; either a UI editable string or "all" + a special value "selection" is supported signifying the current selected contents + of the printed document is to be printed. + */ + const rtl::OUString& getSelectionString() const; + /* get the PropertyValue of a Property */ com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 14735ff42413..d3a2c784fd9e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -681,6 +681,11 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro return aResult; } +const rtl::OUString& PrinterListener::getSelectionString() const +{ + return mpImplData->maSelectionString; +} + const Sequence< beans::PropertyValue >& PrinterListener::getUIOptions() const { return mpImplData->maUIOptions; -- cgit From 51dd8091fce1270fa10b18f5b92a816dd824bd1e Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 5 May 2009 17:16:25 +0000 Subject: #i92516# catch a corner case (0 pages) --- vcl/source/gdi/print3.cxx | 3 ++- vcl/source/window/printdlg.cxx | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index d3a2c784fd9e..7d18c754ee5b 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -220,7 +220,8 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene { GDIMetaFile aPageFile; i_pListener->setLastPage( sal_True ); - Size aPageSize = i_pListener->getFilteredPageFile( 0, aPageFile ); + if( i_pListener->getPageCount() > 0 ) + i_pListener->getFilteredPageFile( 0, aPageFile ); return; } if( aDlg.isPrintToFile() ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index b8a2a1a21910..d386b7ad43b2 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -857,10 +857,14 @@ void PrintDialog::preparePreview( bool i_bNewPage ) { const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; - maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); + if( nPages > 0 ) + maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); maPreviewWindow.setPreview( aMtf ); } + // catch corner case of strange page size + if( maCurPageSize.Width() == 0 || maCurPageSize.Height() == 0 ) + maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); Size aPreviewSize; Point aPreviewPos = maPreviewSpace.TopLeft(); @@ -1155,6 +1159,9 @@ PrintProgressDialog::PrintProgressDialog( Window* i_pParent, int i_nMax ) : { FreeResource(); + if( mnMax < 1 ) + mnMax = 1; + maStr = maText.GetText(); maButton.SetClickHdl( LINK( this, PrintProgressDialog, ClickHdl ) ); @@ -1201,6 +1208,9 @@ void PrintProgressDialog::setProgress( int i_nCurrent, int i_nMax ) if( i_nMax != -1 ) mnMax = i_nMax; + if( mnMax < 1 ) + mnMax = 1; + rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, mnCur ) ); aNewText = searchAndReplace( aNewText, "%n", 2, mnMax ); maText.SetText( aNewText ); @@ -1217,6 +1227,9 @@ void PrintProgressDialog::tick() void PrintProgressDialog::Paint( const Rectangle& ) { + if( maProgressRect.IsEmpty() ) + implCalcProgressRect(); + Push( PUSH_LINECOLOR | PUSH_FILLCOLOR ); const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); Color aPrgsColor = rStyleSettings.GetHighlightColor(); -- cgit From 210e3f82d81d50d44acc59bac05a680968d4976f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 14 May 2009 08:05:27 +0000 Subject: #i92516# add: hasProperty --- vcl/inc/vcl/print.hxx | 5 +++++ vcl/source/gdi/print3.cxx | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index ab08a9ef7e56..c7575812f01d 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -531,6 +531,11 @@ class VCL_DLLPUBLIC PrinterOptionsHelper **/ void appendPrintUIOptions( com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& io_rProps ) const; + // check if a property exists + bool hasProperty( const rtl::OUString& i_rPropertyName ) const; + bool hasProperty( const char* i_pPropertyName ) const + { return hasProperty( rtl::OUString::createFromAscii( i_pPropertyName ) ); } + // returns an empty Any for not existing properties com::sun::star::uno::Any getValue( const rtl::OUString& i_rPropertyName ) const; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 7d18c754ee5b..6c6d55a4a796 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -864,6 +864,14 @@ Any PrinterOptionsHelper::getValue( const rtl::OUString& i_rPropertyName ) const return aRet; } +bool PrinterOptionsHelper::hasProperty( const rtl::OUString& i_rPropertyName ) const +{ + Any aRet; + std::hash_map< rtl::OUString, Any, rtl::OUStringHash >::const_iterator it = + m_aPropertyMap.find( i_rPropertyName ); + return it != m_aPropertyMap.end(); +} + sal_Bool PrinterOptionsHelper::getBoolValue( const rtl::OUString& i_rPropertyName, sal_Bool i_bDefault ) const { sal_Bool bRet = sal_False; -- cgit From de84f6b62c4edbfb2b998e9b12402a8c4dd105ab Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 14 May 2009 08:18:58 +0000 Subject: #i92516# filter accelerators from texts (not used on MacOS) --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 9f1b7ef64edf..ed16df90af80 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -184,6 +184,14 @@ class ListenerProperties } }; +static void filterAccelerator( rtl::OUString& io_rText ) +{ + rtl::OUStringBuffer aBuf( io_rText.getLength() ); + for( sal_Int32 nIndex = 0; nIndex != -1; ) + aBuf.append( io_rText.getToken( 0, '~', nIndex ) ); + io_rText = aBuf.makeStringAndClear(); +} + @interface ControlTarget : NSObject { ListenerProperties* mpListener; @@ -311,6 +319,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) if( rEntry.Name.equalsAscii( "Text" ) ) { rEntry.Value >>= aText; + filterAccelerator( aText ); } else if( rEntry.Name.equalsAscii( "ControlType" ) ) { -- cgit From 10b35f02b14b8377c63d76bf634f1c794995c5f6 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 14 May 2009 13:32:29 +0000 Subject: #i92516# fix 0 pages case --- vcl/aqua/source/gdi/aquaprintview.mm | 3 ++- vcl/aqua/source/gdi/salprn.cxx | 52 +++++++++++++++++++++--------------- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintview.mm b/vcl/aqua/source/gdi/aquaprintview.mm index 79efb9c80941..a050d229f033 100755 --- a/vcl/aqua/source/gdi/aquaprintview.mm +++ b/vcl/aqua/source/gdi/aquaprintview.mm @@ -76,6 +76,7 @@ int nPage = (int)(aPaperSize.width * rect.origin.y + rect.origin.x); // page count is 1 based - mpListener->printFilteredPage( nPage-1 ); + if( nPage - 1 < (mpInfoPrinter->getCurPageRangeStart() + mpInfoPrinter->getCurPageRangeCount() ) ) + mpListener->printFilteredPage( nPage-1 ); } @end diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index f7e08cf4804c..5dcac0a38027 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -491,7 +491,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, BOOL bSuccess = FALSE; AquaSalInstance* pInst = GetSalData()->mpFirstInstance; bool bNeedRestart = true; - sal_Int32 nAllPages = 1; + sal_Int32 nAllPages = 0; // reset IsLastPage i_rListener.setLastPage( sal_False ); @@ -504,30 +504,37 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, { if( bNeedRestart ) { - mnCurPageRangeStart = 1; - mnCurPageRangeCount = 1; + mnCurPageRangeStart = 0; + mnCurPageRangeCount = 0; nAllPages = i_rListener.getPageCount(); } bNeedRestart = false; - mnCurPageRangeCount = 1; - Size aCurSize( getPageSize( i_rListener, mnCurPageRangeStart ) ); - Size aNextSize( aCurSize ); - // print pages up to a different size - while( mnCurPageRangeCount + mnCurPageRangeStart < nAllPages ) + Size aCurSize( 21000, 29700 ); + if( nAllPages > 0 ) { - aNextSize = getPageSize( i_rListener, mnCurPageRangeStart + mnCurPageRangeCount ); - if( aCurSize == aNextSize // same page size - || - (aCurSize.Width() == aNextSize.Height() && aCurSize.Height() == aNextSize.Width()) // same size, but different orientation - ) + mnCurPageRangeCount = 1; + aCurSize = getPageSize( i_rListener, mnCurPageRangeStart ); + Size aNextSize( aCurSize ); + + // print pages up to a different size + while( mnCurPageRangeCount + mnCurPageRangeStart < nAllPages ) { - mnCurPageRangeCount++; + aNextSize = getPageSize( i_rListener, mnCurPageRangeStart + mnCurPageRangeCount ); + if( aCurSize == aNextSize // same page size + || + (aCurSize.Width() == aNextSize.Height() && aCurSize.Height() == aNextSize.Width()) // same size, but different orientation + ) + { + mnCurPageRangeCount++; + } + else + break; } - else - break; } + else + mnCurPageRangeCount = 0; // now for the current run mnStartPageOffsetX = mnStartPageOffsetY = 0; @@ -574,7 +581,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: YES]; - if( bShowPanel && mnCurPageRangeStart == 1 ) // only the first range of pages gets the accesory view + if( bShowPanel && mnCurPageRangeStart == 0 ) // only the first range of pages gets the accesory view pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withRestartCondition: &bNeedRestart]; bSuccess = TRUE; @@ -589,14 +596,17 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, mnCurPageRangeStart += mnCurPageRangeCount; mnCurPageRangeCount = 1; - } while( bNeedRestart && mnCurPageRangeCount < nAllPages ); + } while( bNeedRestart && mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); // inform applictation that it can release its data // this is awkward, but the XRenderable interface has no method for this, // so we need to call XRenderadble::render one last time with IsLastPage = TRUE - i_rListener.setLastPage( sal_True ); - GDIMetaFile aPageFile; - Size aPageSize = i_rListener.getFilteredPageFile( 0, aPageFile ); + if( nAllPages > 0 ) + { + i_rListener.setLastPage( sal_True ); + GDIMetaFile aPageFile; + i_rListener.getFilteredPageFile( 0, aPageFile ); + } mnCurPageRangeStart = mnCurPageRangeCount = 0; -- cgit From 5d5929a51dc6a0d53ac3838cc071b19cf3c7e193 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 14 May 2009 15:38:18 +0000 Subject: #i92516# do not access dead CGContextRef --- vcl/aqua/source/gdi/salprn.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 5dcac0a38027..e30ef8c3c942 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -605,6 +605,8 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, { i_rListener.setLastPage( sal_True ); GDIMetaFile aPageFile; + if( mrContext ) + SetupPrinterGraphics( mrContext ); i_rListener.getFilteredPageFile( 0, aPageFile ); } -- cgit From 7b03cd38245b6b76cf1a8f8c8c0c21104b483acf Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 14 May 2009 16:18:28 +0000 Subject: #i92516# implement GetLandscapeAngle, InitPaperFormats --- vcl/aqua/source/gdi/salprn.cxx | 43 +++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index e30ef8c3c942..e4f16c332955 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -742,6 +742,42 @@ ULONG AquaSalPrinter::GetErrorCode() return mpInfoPrinter->GetErrorCode(); } +void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) +{ + m_aPaperFormats.clear(); + m_bPapersInit = true; + + if( mpPrinter ) + { + if( [mpPrinter statusForTable: @"PPD"] == NSPrinterTableOK ) + { + NSArray* pPaperNames = [mpPrinter stringListForKey: @"PageSize" inTable: @"PPD"]; + if( pPaperNames ) + { + unsigned int nPapers = [pPaperNames count]; + for( unsigned int i = 0; i < nPapers; i++ ) + { + NSString* pPaper = [pPaperNames objectAtIndex: i]; + NSSize aPaperSize = [mpPrinter pageSizeForPaper: pPaper]; + if( aPaperSize.width > 0 && aPaperSize.height > 0 ) + { + vcl::PaperInfo aInfo; + aInfo.m_aPaperName = GetOUString( pPaper ); + aInfo.m_nPaperWidth = (PtTo10Mu( aPaperSize.width ) + 50 ) / 100; + aInfo.m_nPaperHeight = (PtTo10Mu( aPaperSize.height ) + 50 ) / 100; + m_aPaperFormats.push_back( aInfo ); + } + } + } + } + } +} + +int AquaSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* i_pSetupData ) +{ + return 900; +} + //////////////////////////// ////// IMPLEMENT US ///// //////////////////////////// @@ -751,11 +787,4 @@ DuplexMode AquaSalInfoPrinter::GetDuplexMode( const ImplJobSetup* i_pSetupData ) return DUPLEX_UNKNOWN; } -void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) -{ -} -int AquaSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* i_pSetupData ) -{ - return 0; -} -- cgit From 6ca5ebc179d809750a43bf13e0acec3ff6e3f551 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 15 May 2009 15:16:28 +0000 Subject: #i92516# improved paper handling --- vcl/aqua/inc/salprn.h | 6 ++- vcl/aqua/source/gdi/salprn.cxx | 93 ++++++++++++++++++++++++++++-------------- 2 files changed, 68 insertions(+), 31 deletions(-) diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index a2f4a6f80166..0ab4c02ab264 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -120,6 +120,10 @@ class AquaSalInfoPrinter : public SalInfoPrinter sal_Int32 getCurPageRangeStart() const { return mnCurPageRangeStart; } sal_Int32 getCurPageRangeCount() const { return mnCurPageRangeCount; } + // match width/height against known paper formats, possibly switching orientation + const vcl::PaperInfo* matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const; + void setPaperSize( long i_nWidth, long i_nHeight, Orientation i_eSetOrientation ); + private: AquaSalInfoPrinter( const AquaSalInfoPrinter& ); AquaSalInfoPrinter& operator=(const AquaSalInfoPrinter&); @@ -162,7 +166,7 @@ const double fPtTo100thMM = 35.27777778; inline int PtTo10Mu( double nPoints ) { return (int)(((nPoints)*fPtTo100thMM)+0.5); } -inline double TenMuToPt( double nUnits ) { return (((nUnits)/fPtTo100thMM)+0.5); } +inline double TenMuToPt( double nUnits ) { return floor(((nUnits)/fPtTo100thMM)+0.5); } diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index e4f16c332955..b109f2c19dcd 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -69,7 +69,9 @@ AquaSalInfoPrinter::AquaSalInfoPrinter( const SalPrinterQueueInfo& i_rQueue ) : mpPrintInfo( nil ), mePageOrientation( ORIENTATION_PORTRAIT ), mnStartPageOffsetX( 0 ), - mnStartPageOffsetY( 0 ) + mnStartPageOffsetY( 0 ), + mnCurPageRangeStart( 0 ), + mnCurPageRangeCount( 0 ) { NSString* pStr = CreateNSString( i_rQueue.maPrinterName ); mpPrinter = [NSPrinter printerWithName: pStr]; @@ -89,6 +91,7 @@ AquaSalInfoPrinter::AquaSalInfoPrinter( const SalPrinterQueueInfo& i_rQueue ) : const int nWidth = 100, nHeight = 100; maContextMemory.reset( reinterpret_cast( rtl_allocateMemory( nWidth * 4 * nHeight ) ), boost::bind( rtl_freeMemory, _1 ) ); + if( maContextMemory ) { mrContext = CGBitmapContextCreate( maContextMemory.get(), nWidth, nHeight, 8, nWidth * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst ); @@ -126,12 +129,9 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const long nDPIX = 720, nDPIY = 720; NSSize aPaperSize = [mpPrintInfo paperSize]; - NSRect aImageRect = [mpPrintInfo imageablePageBounds]; if( mePageOrientation == ORIENTATION_PORTRAIT ) { double dX = 0, dY = aPaperSize.height; - // dX += aImageRect.origin.x; - // dY -= aPaperSize.height - aImageRect.size.height - aImageRect.origin.y; CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetX, dY - mnStartPageOffsetY ); CGContextScaleCTM( i_rContext, 0.1, -0.1 ); } @@ -139,9 +139,6 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const { CGContextRotateCTM( i_rContext, M_PI/2 ); double dX = aPaperSize.height, dY = -aPaperSize.width; - // dY += aPaperSize.height - aImageRect.size.height - aImageRect.origin.y; - // dX -= aImageRect.origin.x; - CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetY, dY - mnStartPageOffsetX ); CGContextScaleCTM( i_rContext, -0.1, 0.1 ); } @@ -291,6 +288,28 @@ BOOL AquaSalInfoPrinter::SetPrinterData( ImplJobSetup* io_pSetupData ) // ----------------------------------------------------------------------- +void AquaSalInfoPrinter::setPaperSize( long i_nWidth, long i_nHeight, Orientation i_eSetOrientation ) +{ + + Orientation ePaperOrientation = ORIENTATION_PORTRAIT; + const vcl::PaperInfo* pPaper = matchPaper( (i_nWidth+50)/100, (i_nHeight+50)/100, ePaperOrientation ); + + if( pPaper ) + { + NSString* pPaperName = [CreateNSString( pPaper->m_aPaperName ) autorelease]; + [mpPrintInfo setPaperName: pPaperName]; + } + else if( i_nWidth > 0 && i_nHeight > 0 ) + { + NSSize aPaperSize = { TenMuToPt(i_nWidth), TenMuToPt(i_nHeight) }; + [mpPrintInfo setPaperSize: aPaperSize]; + } + // this seems counterintuitive + mePageOrientation = i_eSetOrientation; +} + +// ----------------------------------------------------------------------- + BOOL AquaSalInfoPrinter::SetData( ULONG i_nFlags, ImplJobSetup* io_pSetupData ) { if( ! io_pSetupData || io_pSetupData->mnSystem != JOBSETUP_SYSTEM_MAC ) @@ -299,27 +318,28 @@ BOOL AquaSalInfoPrinter::SetData( ULONG i_nFlags, ImplJobSetup* io_pSetupData ) if( mpPrintInfo ) { + if( (i_nFlags & SAL_JOBSET_ORIENTATION) != 0 ) + mePageOrientation = io_pSetupData->meOrientation; + if( (i_nFlags & SAL_JOBSET_PAPERSIZE) != 0) { // set paper format - double width = 0, height = 0; + long width = 0, height = 0; if( io_pSetupData->mePaperFormat == PAPER_USER ) { - width = TenMuToPt( io_pSetupData->mnPaperWidth ); - height = TenMuToPt( io_pSetupData->mnPaperHeight ); + width = io_pSetupData->mnPaperWidth; + height = io_pSetupData->mnPaperHeight; } else - getPaperSize( width, height, io_pSetupData->mePaperFormat ); - - if( width > 0 && height > 0 ) { - NSSize aPaperSize = { width, height }; - [mpPrintInfo setPaperSize: aPaperSize]; + double w = 595, h = 842; + getPaperSize( w, h, io_pSetupData->mePaperFormat ); + width = static_cast(PtTo10Mu( w )); + height = static_cast(PtTo10Mu( h )); } - } - if( (i_nFlags & SAL_JOBSET_ORIENTATION) != 0 ) - mePageOrientation = io_pSetupData->meOrientation; + setPaperSize( width, height, mePageOrientation ); + } } return mpPrintInfo != nil; @@ -539,18 +559,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, // now for the current run mnStartPageOffsetX = mnStartPageOffsetY = 0; // setup the paper size and orientation - if( aCurSize.Width() > aCurSize.Height() ) - { - mePageOrientation = ORIENTATION_LANDSCAPE; - long nTmp = aCurSize.Width(); - aCurSize.Width() = aCurSize.Height(); - aCurSize.Height() = nTmp; - } - else - mePageOrientation = ORIENTATION_PORTRAIT; - - NSSize aPaperSize = { TenMuToPt(aCurSize.Width()), TenMuToPt(aCurSize.Height()) }; - [mpPrintInfo setPaperSize: aPaperSize]; + setPaperSize( aCurSize.Width(), aCurSize.Height(), ORIENTATION_PORTRAIT ); // create view NSView* pPrintView = [[AquaPrintView alloc] initWithListener: &i_rListener withInfoPrinter: this]; @@ -773,6 +782,30 @@ void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) } } +const vcl::PaperInfo* AquaSalInfoPrinter::matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const +{ + if( ! m_bPapersInit ) + const_cast(this)->InitPaperFormats( NULL ); + + const vcl::PaperInfo* pMatch = NULL; + o_rOrientation = ORIENTATION_PORTRAIT; + for( int n = 0; n < 2 ; n++ ) + { + for( size_t i = 0; i < m_aPaperFormats.size(); i++ ) + { + if( abs( m_aPaperFormats[i].m_nPaperWidth - i_nWidth ) < 2 && + abs( m_aPaperFormats[i].m_nPaperHeight - i_nHeight ) < 2 ) + { + pMatch = &m_aPaperFormats[i]; + return pMatch; + } + } + o_rOrientation = ORIENTATION_LANDSCAPE; + std::swap( i_nWidth, i_nHeight ); + } + return pMatch; +} + int AquaSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* i_pSetupData ) { return 900; -- cgit From cf5d2108b8709bb9973026f191ba9276ee3b5e15 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 21 May 2009 11:52:39 +0000 Subject: helper class for layouting child controls --- vcl/inc/vcl/arrange.hxx | 179 ++++++++++++++++++++++ vcl/source/window/arrange.cxx | 342 ++++++++++++++++++++++++++++++++++++++++++ vcl/source/window/makefile.mk | 1 + 3 files changed, 522 insertions(+) create mode 100644 vcl/inc/vcl/arrange.hxx create mode 100644 vcl/source/window/arrange.cxx diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx new file mode 100644 index 000000000000..03a388a519bd --- /dev/null +++ b/vcl/inc/vcl/arrange.hxx @@ -0,0 +1,179 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: accel.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _VCL_ARRANGE_HXX +#define _VCL_ARRANGE_HXX + +#include "vcl/window.hxx" + +#include + +namespace vcl +{ + /* some helper classes for simple window layouting + guidelines: + - a WindowArranger is not a Window + - a WindowArranger hierarchy manages exactly one level of child windows inside a common parent + this is to keep the vcl Window hierarchy flat, as some code like accelerators depend on such behavior + - a WindowArranger never becomes owner of a Window, windows need to be destroyed separately + - a WindowArranger however always is owner of its child WindowArrangers, that is the + WindowArranger hierarchy will keep track of its objects and delete them + - a managed element of a WindowArranger can either be a Window (a leaf in the hierarchy) + or a child WindowArranger (a node in the hierarchy), but never both + */ + + class WindowArranger + { + protected: + struct Element + { + Window* m_pElement; + WindowArranger* m_pChild; + + Element() + : m_pElement( NULL ) + , m_pChild( NULL ) + {} + + Element( Window* i_pWin, WindowArranger* i_pChild ) + : m_pElement( i_pWin ) + , m_pChild( i_pChild ) + {} + + void deleteChild() { delete m_pChild; m_pChild = NULL; } + }; + + Window* m_pParentWindow; + WindowArranger* m_pParentArranger; + Rectangle m_aManagedArea; + long m_nOuterBorder; + + public: + WindowArranger( WindowArranger* i_pParent = NULL ) + : m_pParentWindow( i_pParent ? i_pParent->m_pParentWindow : NULL ) + , m_pParentArranger( i_pParent ) + , m_nOuterBorder( 0 ) + {} + virtual ~WindowArranger(); + + // ask what would be the optimal size + virtual Size getOptimalSize( WindowSizeType ) const = 0; + // call Resize to trigger layouting inside the managed area + // without function while parent window is unset + virtual void resize() = 0; + // avoid this if possible, using the constructor instead + // there can be only one parent window and all managed windows MUST + // be direct children of that window + // violating that condition will result in undefined behavior + virtual void setParentWindow( Window* ) = 0; + virtual void setParent( WindowArranger* ); + + virtual size_t countElements() const = 0; + virtual WindowArranger* getChild( size_t i_nIndex ) const = 0; + virtual Window* getWindow( size_t i_nIndex ) const = 0; + + void setManagedArea( const Rectangle& i_rArea ) + { + m_aManagedArea = i_rArea; + resize(); + } + + void setOuterBorder( long i_nBorder ) + { + m_nOuterBorder = i_nBorder; + resize(); + } + }; + + class RowOrColumn : public WindowArranger + { + long m_nBorderWidth; + bool m_bColumn; + + std::vector< WindowArranger::Element > m_aElements; + + void distributeRowWidth( std::vector< Size >& io_rSizes, long i_nUsedWidth, long i_nExtraWidth ); + public: + RowOrColumn( WindowArranger* i_pParent = NULL, bool bColumn = true, long i_nBorderWidth = 5 ) + : WindowArranger( i_pParent ) + , m_nBorderWidth( i_nBorderWidth ) + , m_bColumn( bColumn ) + {} + + virtual ~RowOrColumn(); + + virtual Size getOptimalSize( WindowSizeType ) const; + virtual void resize(); + virtual void setParentWindow( Window* ); + virtual size_t countElements() const { return m_aElements.size(); } + virtual WindowArranger* getChild( size_t i_nIndex ) const; + virtual Window* getWindow( size_t i_nIndex ) const; + + // add a managed window at the given index + // an index smaller than zero means add the window at the end + void addWindow( Window*, sal_Int32 nIndex = -1 ); + void remove( Window* ); + + void addChild( WindowArranger*, sal_Int32 nIndex = -1 ); + void remove( WindowArranger* ); + }; + + class Indenter : public WindowArranger + { + long m_nIndent; + WindowArranger::Element m_aElement; + + public: + Indenter( WindowArranger* i_pParent = NULL, long i_nIndent = 15 ) + : WindowArranger( i_pParent ) + , m_nIndent( i_nIndent ) + {} + + virtual ~Indenter(); + + virtual Size getOptimalSize( WindowSizeType ) const; + virtual void resize(); + virtual void setParentWindow( Window* ); + virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } + virtual WindowArranger* getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild : NULL; } + virtual Window* getWindow( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pElement : NULL; } + + void setIndent( long i_nIndent ) + { + m_nIndent = i_nIndent; + resize(); + } + + void setWindow( Window* ); + void setChild( WindowArranger* ); + }; +} + +#endif \ No newline at end of file diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx new file mode 100644 index 000000000000..134e18f9935a --- /dev/null +++ b/vcl/source/window/arrange.cxx @@ -0,0 +1,342 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: accel.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "vcl/arrange.hxx" + +#include "osl/diagnose.h" + +using namespace vcl; + +// ---------------------------------------- +// vcl::WindowArranger +//----------------------------------------- + +WindowArranger::~WindowArranger() +{} + +void WindowArranger::setParent( WindowArranger* i_pParent ) +{ + OSL_VERIFY( i_pParent->m_pParentWindow == m_pParentWindow || m_pParentWindow == NULL ); + + m_pParentArranger = i_pParent; + m_pParentWindow = i_pParent->m_pParentWindow; + setParentWindow( m_pParentWindow ); +} + +// ---------------------------------------- +// vcl::RowOrColumn +//----------------------------------------- + +RowOrColumn::~RowOrColumn() +{ + for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + it->deleteChild(); + } +} + +WindowArranger* RowOrColumn::getChild( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : NULL; +} + +Window* RowOrColumn::getWindow( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL; +} + +Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const +{ + Size aRet( 0, 0 ); + if( ! m_aElements.empty() ) + { + if( m_bColumn ) + aRet.Height() -= m_nBorderWidth; + else + aRet.Width() -= m_nBorderWidth; + } + + for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + // get the size of type of the managed element + Size aElementSize( it->m_pElement + ? it->m_pElement->GetOptimalSize( i_eType ) + : it->m_pChild + ? it->m_pChild->getOptimalSize( i_eType ) + : Size() ); + if( m_bColumn ) + { + // add the distance between elements + aRet.Height() += m_nBorderWidth; + // check if the width needs adjustment + if( aRet.Width() < aElementSize.Width() ) + aRet.Width() = aElementSize.Width(); + aRet.Height() += aElementSize.Height(); + } + else + { + // add the distance between elements + aRet.Width() += m_nBorderWidth; + // check if the height needs adjustment + if( aRet.Height() < aElementSize.Height() ) + aRet.Height() = aElementSize.Height(); + aRet.Width() += aElementSize.Width(); + } + } + + // add the outer border + aRet.Width() += 2*m_nOuterBorder; + aRet.Height() += 2*m_nOuterBorder; + + return aRet; +} + +void RowOrColumn::distributeRowWidth( std::vector& io_rSizes, long /*i_nUsedWidth*/, long i_nExtraWidth ) +{ + // distribute extra space evenly among elements + size_t nElements = io_rSizes.size(); + long nDelta = i_nExtraWidth / nElements; + for( size_t i = 0; i < nElements; i++ ) + { + io_rSizes[i].Width() += nDelta; + i_nExtraWidth -= nDelta; + } + // add the last pixels to the last row element + if( i_nExtraWidth > 0 && nElements > 0 ) + io_rSizes.back().Width() += i_nExtraWidth; +} + +void RowOrColumn::resize() +{ + // check if we can get optimal size, else fallback to minimal size + Size aOptSize( getOptimalSize( WINDOWSIZE_PREFERRED ) ); + WindowSizeType eType = WINDOWSIZE_PREFERRED; + if( m_bColumn ) + { + if( aOptSize.Height() > m_aManagedArea.GetHeight() ) + eType = WINDOWSIZE_MINIMUM; + } + else + { + if( aOptSize.Width() > m_aManagedArea.GetWidth() ) + eType = WINDOWSIZE_MINIMUM; + } + + size_t nElements = m_aElements.size(); + // get all element sizes for sizing + std::vector aElementSizes( nElements ); + long nUsedWidth = m_nOuterBorder - (nElements ? m_nBorderWidth : 0); + for( size_t i = 0; i < nElements; i++ ) + { + aElementSizes[i] = m_aElements[i].m_pElement + ? m_aElements[i].m_pElement->GetOptimalSize( eType ) + : m_aElements[i].m_pChild + ? m_aElements[i].m_pChild->getOptimalSize( eType ) + : Size(); + if( m_bColumn ) + { + aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder; + nUsedWidth += aElementSizes[i].Height() + m_nBorderWidth; + } + else + { + aElementSizes[i].Height() = m_aManagedArea.GetHeight() - 2* m_nOuterBorder; + nUsedWidth += aElementSizes[i].Width() + m_nBorderWidth; + } + } + + long nExtraWidth = m_aManagedArea.GetWidth() - nUsedWidth; + if( nExtraWidth > 0 ) + if( ! m_bColumn ) + distributeRowWidth( aElementSizes, nUsedWidth, nExtraWidth ); + + // get starting position + Point aElementPos( m_aManagedArea.TopLeft() ); + // outer border + aElementPos.X() += m_nOuterBorder; + aElementPos.Y() += m_nOuterBorder; + + // position managed windows + for( size_t i = 0; i < nElements; i++ ) + { + // get the size of type of the managed element + + if( m_aElements[i].m_pElement ) // this actually is a window + { + m_aElements[i].m_pElement->SetPosSizePixel( aElementPos, aElementSizes[i] ); + } + else if( m_aElements[i].m_pChild ) + { + m_aElements[i].m_pChild->setManagedArea( Rectangle( aElementPos, aElementSizes[i] ) ); + } + if( m_bColumn ) + aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height(); + else + aElementPos.X() += m_nBorderWidth + aElementSizes[i].Width(); + } +} + +void RowOrColumn::setParentWindow( Window* i_pNewParent ) +{ + m_pParentWindow = i_pNewParent; + for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + #if OSL_DEBUG_LEVEL > 0 + if( it->m_pElement ) + { + OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent ); + } + #endif + if( it->m_pChild ) + it->m_pChild->setParentWindow( i_pNewParent ); + } +} + +void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nIndex ) +{ + if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) + m_aElements.push_back( WindowArranger::Element( i_pWindow, NULL ) ); + else + { + std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); + while( i_nIndex-- ) + ++it; + m_aElements.insert( it, WindowArranger::Element( i_pWindow, NULL ) ); + } +} + +void RowOrColumn::addChild( WindowArranger* i_pChild, sal_Int32 i_nIndex ) +{ + if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) + m_aElements.push_back( WindowArranger::Element( NULL, i_pChild ) ); + else + { + std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); + while( i_nIndex-- ) + ++it; + m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild ) ); + } +} + +void RowOrColumn::remove( Window* i_pWindow ) +{ + if( i_pWindow ) + { + for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + if( it->m_pElement == i_pWindow ) + { + m_aElements.erase( it ); + return; + } + } + } +} + +void RowOrColumn::remove( WindowArranger* i_pChild ) +{ + if( i_pChild ) + { + for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + if( it->m_pChild == i_pChild ) + { + m_aElements.erase( it ); + return; + } + } + } +} + +// ---------------------------------------- +// vcl::Indenter +//----------------------------------------- + +Indenter::~Indenter() +{ + m_aElement.deleteChild(); +} + +Size Indenter::getOptimalSize( WindowSizeType i_eType ) const +{ + Size aSize( m_aElement.m_pElement + ? m_aElement.m_pElement->GetOptimalSize( i_eType ) + : m_aElement.m_pChild + ? m_aElement.m_pChild->getOptimalSize( i_eType ) + : Size() ); + aSize.Width() += 2*m_nOuterBorder + m_nIndent; + aSize.Height() += 2*m_nOuterBorder; + return aSize; +} + +void Indenter::resize() +{ + Point aPt( m_aManagedArea.TopLeft() ); + aPt.X() += m_nOuterBorder + m_nIndent; + aPt.Y() += m_nOuterBorder; + Size aSz( m_aManagedArea.GetSize() ); + aSz.Width() -= 2*m_nOuterBorder - m_nIndent; + aSz.Height() -= 2*m_nOuterBorder; + if( m_aElement.m_pElement ) + m_aElement.m_pElement->SetPosSizePixel( aPt, aSz ); + else if( m_aElement.m_pChild ) + m_aElement.m_pChild->setManagedArea( Rectangle( aPt, aSz ) ); +} + +void Indenter::setWindow( Window* i_pWindow ) +{ + OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pWindow == 0 ); + OSL_VERIFY( i_pWindow == 0 || i_pWindow->GetParent() == m_pParentWindow ); + m_aElement.m_pElement = i_pWindow; +} + +void Indenter::setChild( WindowArranger* i_pChild ) +{ + OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pChild == 0 ); + m_aElement.m_pChild = i_pChild; +} + +void Indenter::setParentWindow( Window* i_pNewParent ) +{ + m_pParentWindow = i_pNewParent; + #if OSL_DEBUG_LEVEL > 0 + if( m_aElement.m_pElement ) + { + OSL_VERIFY( m_aElement.m_pElement->GetParent() == i_pNewParent ); + } + #endif + if( m_aElement.m_pChild ) + m_aElement.m_pChild->setParentWindow( i_pNewParent ); +} diff --git a/vcl/source/window/makefile.mk b/vcl/source/window/makefile.mk index cadea48f6f7a..4d1c3d60816b 100644 --- a/vcl/source/window/makefile.mk +++ b/vcl/source/window/makefile.mk @@ -45,6 +45,7 @@ ENABLE_EXCEPTIONS=TRUE # --- Files -------------------------------------------------------- SLOFILES= \ + $(SLO)$/arrange.obj \ $(SLO)$/abstdlg.obj \ $(SLO)$/accel.obj \ $(SLO)$/accmgr.obj \ -- cgit From e2dcfdf1706b4c636c74b90fd2442b18537af1e8 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 22 May 2009 07:04:13 +0000 Subject: #i101309# need the page range controls app specific --- vcl/inc/vcl/print.hxx | 26 ++--- vcl/inc/vcl/prndlg.hxx | 11 +-- vcl/source/gdi/print3.cxx | 109 ++++++++++++--------- vcl/source/src/print.src | 42 +------- vcl/source/window/printdlg.cxx | 212 +++++++++++++++++++++++++++-------------- 5 files changed, 229 insertions(+), 171 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index c7575812f01d..98e08312e5ca 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -456,12 +456,6 @@ public: com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getJobProperties( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& i_rMergeList ) const; - /* get the current selection string; either a UI editable string or "all" - a special value "selection" is supported signifying the current selected contents - of the printed document is to be printed. - */ - const rtl::OUString& getSelectionString() const; - /* get the PropertyValue of a Property */ com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); @@ -500,7 +494,6 @@ public: void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); void SAL_DLLPRIVATE createProgressDialog(); - void SAL_DLLPRIVATE setPrintSelection( const rtl::OUString& ); void SAL_DLLPRIVATE setMultipage( int nRows, int nColumns, const Size& rPaperSize ); void SAL_DLLPRIVATE setLastPage( sal_Bool i_bLastPage ); }; @@ -560,11 +553,11 @@ class VCL_DLLPUBLIC PrinterOptionsHelper static com::sun::star::uno::Any getUIControlOpt( const rtl::OUString& i_rTitle, const com::sun::star::uno::Sequence< rtl::OUString >& i_rHelpText, const rtl::OUString& i_rType, - const com::sun::star::beans::PropertyValue* i_pVal = NULL, - const com::sun::star::uno::Sequence< rtl::OUString >* i_pChoices = NULL, + const com::sun::star::beans::PropertyValue* i_pValue = NULL, const rtl::OUString* i_pDependsOnName = NULL, sal_Int32 i_nDependsOnEntry = -1, - sal_Int32 i_nMinValue = -1, sal_Int32 i_nMaxValue = -2 + const com::sun::star::beans::PropertyValue* i_pAddProps = NULL, + sal_Int32 i_nAddProps = 0 ); // create a group (e.g. a TabPage); following controls will be grouped in it until the next // group begins @@ -572,7 +565,8 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // create a subgroup (e.g. a FixedLine); following controls will be grouped in it until the next // subgroup or group begins - static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ); + // setting bJobPage = true will make the subgroup appear on the first page of the print dialog + static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, bool i_bJobPage = false, bool i_bInternalOnly = false ); // create a bool option (usually a checkbox) static com::sun::star::uno::Any getBoolControlOpt( const rtl::OUString& i_rTitle, @@ -605,6 +599,16 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const rtl::OUString* i_pDependsOnName = NULL, sal_Int32 i_nDependsOnEntry = -1 ); + + // create a string field + // note: max value < min value means do not apply min/max values + static com::sun::star::uno::Any getEditControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, + const rtl::OUString& i_rProperty, + const rtl::OUString& i_rValue, + const rtl::OUString* i_pDependsOnName = NULL, + sal_Int32 i_nDependsOnEntry = -1 + ); }; } diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 24ea0ea6a3e3..408ec46b2aff 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -98,11 +98,6 @@ namespace vcl public: ListBox maPrinters; CheckBox maToFileBox; - FixedLine maPrintRange; - RadioButton maAllButton; - RadioButton maPagesButton; - RadioButton maSelectionButton; - Edit maPagesEdit; FixedLine maCopies; FixedText maCopyCount; @@ -123,7 +118,7 @@ namespace vcl CancelButton maCancelButton; PrintPreviewWindow maPreviewWindow; FixedText maPageText; - ScrollBar maPageScrollbar; + ScrollBar maPageSlider; TabControl maTabCtrl; PrinterTabPage maPrinterPage; @@ -159,8 +154,8 @@ namespace vcl virtual void Resize(); - DECL_LINK( ScrollHdl, ScrollBar* ); - DECL_LINK( ScrollEndHdl, ScrollBar* ); + DECL_LINK( SlideHdl, ScrollBar* ); + DECL_LINK( EndSlideHdl, ScrollBar* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); DECL_LINK( ModifyHdl, Edit* ); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 6c6d55a4a796..d16db4ef9aec 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -78,7 +78,6 @@ public: PropertyToIndexMap maPropertyToIndex; Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; - rtl::OUString maSelectionString; sal_Bool mbLastPage; int mnMultiPageRows; @@ -88,7 +87,6 @@ public: vcl::PrintProgressDialog* mpProgress; ImplPrinterListenerData() : - maSelectionString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), mbLastPage( sal_False ), mnMultiPageRows( 1 ), mnMultiPageColumns( 1 ), @@ -382,11 +380,6 @@ void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) mpImplData->maMultiPageSize = aPaperSize; } -void PrinterListener::setPrintSelection( const rtl::OUString& i_rSel ) -{ - mpImplData->maSelectionString = i_rSel; -} - static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) { Size aPageSize = pPrinter->GetPaperSize(); @@ -654,14 +647,6 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro if( aMergeSet.find( mpImplData->maUIProperties[i].Name ) == aMergeSet.end() ) aResult[nCur++] = mpImplData->maUIProperties[i]; } - // append page selection - if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintSelection" ) ) ) == aMergeSet.end() ) - { - PropertyValue aVal; - aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintSelection" ) ); - aVal.Value <<= mpImplData->maSelectionString; - aResult[nCur++] = aVal; - } // append IsLastPage if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsLastPage" ) ) ) == aMergeSet.end() ) { @@ -682,11 +667,6 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro return aResult; } -const rtl::OUString& PrinterListener::getSelectionString() const -{ - return mpImplData->maSelectionString; -} - const Sequence< beans::PropertyValue >& PrinterListener::getUIOptions() const { return mpImplData->maUIOptions; @@ -945,11 +925,10 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, const Sequence< rtl::OUString >& i_rHelpTexts, const rtl::OUString& i_rType, const PropertyValue* i_pVal, - const Sequence< rtl::OUString >* i_pChoices, const rtl::OUString* i_pDependsOnName, sal_Int32 i_nDependsOnEntry, - sal_Int32 i_nMinValue, - sal_Int32 i_nMaxValue + const PropertyValue* i_pAddProps, + sal_Int32 i_nAddProps ) { sal_Int32 nElements = @@ -957,9 +936,8 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + (i_rTitle.getLength() ? 1 : 0) // Text + (i_rHelpTexts.getLength() ? 1 : 0) // HelpText + (i_pVal ? 1 : 0) // Property - + (i_pChoices ? 1 : 0) // Choices + (i_pDependsOnName ? (i_nDependsOnEntry != -1 ? 2 : 1) : 0) // dependencies - + (i_nMaxValue >= i_nMinValue ? 2 : 0) // min/max + + i_nAddProps ; Sequence< PropertyValue > aCtrl( nElements ); @@ -981,11 +959,6 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Property" ) ); aCtrl[nUsed++].Value = makeAny( *i_pVal ); } - if( i_pChoices ) - { - aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Choices" ) ); - aCtrl[nUsed++].Value = makeAny( *i_pChoices ); - } if( i_pDependsOnName ) { aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnName" ) ); @@ -996,13 +969,8 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed++].Value = makeAny( i_nDependsOnEntry ); } } - if( i_nMaxValue >= i_nMinValue ) - { - aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MinValue" ) ); - aCtrl[nUsed++].Value = makeAny( i_nMinValue ); - aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxValue" ) ); - aCtrl[nUsed++].Value = makeAny( i_nMaxValue ); - } + for( sal_Int32 i = 0; i < i_nAddProps; i++ ) + aCtrl[ nUsed++ ] = i_pAddProps[i]; DBG_ASSERT( nUsed == nElements, "nUsed != nElements, probable heap corruption" ); @@ -1020,15 +988,29 @@ Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle, con return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Group" ) ) ); } -Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText ) +Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, + bool i_bJobPage, bool i_bInternalOnly ) { + PropertyValue aAddProps[2]; + sal_Int32 nUsed = 0; + if( i_bJobPage ) + { + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PutOnJobPage" ) ); + aAddProps[nUsed++].Value <<= sal_True; + } + if( i_bInternalOnly ) + { + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InternalUIOnly" ) ); + aAddProps[nUsed++].Value <<= sal_True; + } Sequence< rtl::OUString > aHelpText; if( i_rHelpText.getLength() > 0 ) { aHelpText.realloc( 1 ); *aHelpText.getArray() = i_rHelpText; } - return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ) ); + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ), + NULL, NULL, -1, aAddProps, nUsed ); } Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, @@ -1048,7 +1030,7 @@ Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_bValue ); - return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, NULL, i_pDependsOnName, i_nDependsOnEntry ); + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, i_pDependsOnName, i_nDependsOnEntry ); } Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, @@ -1061,10 +1043,15 @@ Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nDependsOnEntry ) { + PropertyValue aAddProps[2]; + sal_Int32 nUsed = 0; + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Choices" ) ); + aAddProps[nUsed++].Value = makeAny( i_rChoices ); + PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_nValue ); - return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, &i_rChoices, i_pDependsOnName, i_nDependsOnEntry ); + return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, i_pDependsOnName, i_nDependsOnEntry, aAddProps, nUsed ); } Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, @@ -1077,6 +1064,16 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nDependsOnEntry ) { + PropertyValue aAddProps[2]; + sal_Int32 nUsed = 0; + if( i_nMaxValue >= i_nMinValue ) + { + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MinValue" ) ); + aAddProps[nUsed++].Value = makeAny( i_nMinValue ); + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxValue" ) ); + aAddProps[nUsed++].Value = makeAny( i_nMaxValue ); + } + Sequence< rtl::OUString > aHelpText; if( i_rHelpText.getLength() > 0 ) { @@ -1090,9 +1087,33 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Range" ) ), &aVal, - NULL, i_pDependsOnName, i_nDependsOnEntry, - i_nMinValue, - i_nMaxValue ); + aAddProps, nUsed ); +} + +Any PrinterOptionsHelper::getEditControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, + const rtl::OUString& i_rProperty, + const rtl::OUString& i_rValue, + const rtl::OUString* i_pDependsOnName, + sal_Int32 i_nDependsOnEntry + ) +{ + Sequence< rtl::OUString > aHelpText; + if( i_rHelpText.getLength() > 0 ) + { + aHelpText.realloc( 1 ); + *aHelpText.getArray() = i_rHelpText; + } + PropertyValue aVal; + aVal.Name = i_rProperty; + aVal.Value = makeAny( i_rValue ); + return getUIControlOpt( i_rTitle, + aHelpText, + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Edit" ) ), + &aVal, + i_pDependsOnName, + i_nDependsOnEntry, + 0, 0 ); } diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 05fa6e1d9ccc..d6842560d1f8 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -219,53 +219,21 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 200, 12 ); Text [en-US] = "Print to file"; }; - FixedLine SV_PRINT_RANGE - { - Pos = MAP_APPFONT( 5, 35 ); - Size = MAP_APPFONT( 150, 10 ); - Text [en-US] = "Print range"; - }; - RadioButton SV_PRINT_ALL - { - Pos = MAP_APPFONT( 10, 45 ); - Size = MAP_APPFONT( 145, 15 ); - Text [en-US] = "All pages"; - Check = TRUE; - }; - RadioButton SV_PRINT_PAGERANGE - { - Pos = MAP_APPFONT( 10, 60 ); - Size = MAP_APPFONT( 60, 15 ); - Text [en-US] = "Pages"; - }; - Edit SV_PRINT_PAGERANGE_EDIT - { - Pos = MAP_APPFONT( 70, 60 ); - Size = MAP_APPFONT( 80, 12 ); - Border = TRUE; - }; - RadioButton SV_PRINT_SELECTION - { - Pos = MAP_APPFONT( 10, 75 ); - Size = MAP_APPFONT( 145, 15 ); - Text [en-US] = "Selection"; - }; - FixedLine SV_PRINT_COPIES { - Pos = MAP_APPFONT( 5, 95 ); + Pos = MAP_APPFONT( 5, 35 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Copies"; }; FixedText SV_PRINT_COPYCOUNT { - Pos = MAP_APPFONT( 10, 105 ); + Pos = MAP_APPFONT( 10, 45 ); Size = MAP_APPFONT( 80, 10 ); Text [en-US] = "Number of copies"; }; NumericField SV_PRINT_COPYCOUNT_FIELD { - Pos = MAP_APPFONT( 90, 105 ); + Pos = MAP_APPFONT( 90, 45 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -275,12 +243,12 @@ ModalDialog SV_DLG_PRINT }; FixedImage SV_PRINT_COLLATE_IMAGE { - Pos = MAP_APPFONT( 10, 125 ); + Pos = MAP_APPFONT( 10, 65 ); Size = MAP_PIXEL( 80, 30 ); }; CheckBox SV_PRINT_COLLATE { - Pos = MAP_APPFONT( 80, 125 ); + Pos = MAP_APPFONT( 80, 65 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index d386b7ad43b2..9092d3abac83 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -144,11 +144,6 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) - , maPrintRange( this, VclResId( SV_PRINT_RANGE ) ) - , maAllButton( this, VclResId( SV_PRINT_ALL ) ) - , maPagesButton( this, VclResId( SV_PRINT_PAGERANGE ) ) - , maSelectionButton( this, VclResId( SV_PRINT_SELECTION ) ) - , maPagesEdit( this, VclResId( SV_PRINT_PAGERANGE_EDIT ) ) , maCopies( this, VclResId( SV_PRINT_COPIES ) ) , maCopyCount( this, VclResId( SV_PRINT_COPYCOUNT ) ) , maCopyCountField( this, VclResId( SV_PRINT_COPYCOUNT_FIELD ) ) @@ -162,11 +157,6 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) FreeResource(); maPrinters.SMHID2( "JobPage", "PrinterList" ); maToFileBox.SMHID2( "JobPage", "ToFile" ); - maPrintRange.SMHID2( "JobPage", "PrintRange" ); - maAllButton.SMHID2( "JobPage", "AllButton" ); - maPagesButton.SMHID2( "JobPage", "PagesButton" ); - maSelectionButton.SMHID2( "JobPage", "SelectionButton" ); - maPagesEdit.SMHID2( "JobPage", "Pages" ); maCopies.SMHID2( "JobPage", "CopiesLine" ); maCopyCount.SMHID2( "JobPage", "CopiesText" ); maCopyCountField.SMHID2( "JobPage", "Copies" ); @@ -184,7 +174,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& rQueues( Printer::GetPrinterQueues() ); @@ -241,16 +231,6 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr 1 ) - { - aBuf.append( sal_Unicode('-') ); - aBuf.append( mnCachedPages ); - } - maJobPage.maPagesEdit.SetText( aBuf.makeStringAndClear() ); - // setup sizes for N-Up Size aNupSize( maPListener->getPrinter()->PixelToLogic( maPListener->getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); @@ -269,16 +249,12 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_r i_pWindow->SetHelpText( i_rHelpTexts.getConstArray()[i_nIndex] ); } +// FIXME: this is evil hackery and witchcraft +// the automatic controls should be replaced by some kind of row/column widget void PrintDialog::setupOptionalUI() { - Window* pCurParent = 0; - long nCurY = 0, nXPos = 5, nMaxY = 0; - USHORT nOptPageId = 9, nCurSubGroup = 0; + Window* pCurParent = 0, *pDynamicPageParent = 0; + long nCurY = 0, nXPos = 5, nMaxY = 0, nJobPageCurY = 0, nDynamicPageCurY = 0; + USHORT nOptPageId = 9, nCurSubGroup = 0, nJobGroups = 0; MapMode aFontMapMode( MAP_APPFONT ); + bool bOnJobPage = false; + + nJobPageCurY = maJobPage.PixelToLogic( maJobPage.maCollateImage.GetPosPixel(), aFontMapMode ).Y(); + nJobPageCurY += maJobPage.PixelToLogic( maJobPage.maCollateImage.GetSizePixel(), aFontMapMode ).Height(); + nJobPageCurY += 5; Size aTabSize = maTabCtrl.GetTabPageSizePixel(); const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); @@ -379,6 +362,7 @@ void PrintDialog::setupOptionalUI() sal_Int64 nMinValue = 0, nMaxValue = 0; long nDependencyIndent = 0; sal_Int32 nCurHelpText = 0; + sal_Bool bOnJobPageValue = sal_False; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -407,6 +391,10 @@ void PrintDialog::setupOptionalUI() rEntry.Value >>= bValue; bEnabled = bValue; } + else if( rEntry.Name.equalsAscii( "PutOnJobPage" ) ) + { + rEntry.Value >>= bOnJobPageValue; + } else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) { rtl::OUString aDepName; @@ -459,6 +447,7 @@ void PrintDialog::setupOptionalUI() aCtrlType.equalsAscii( "Radio" ) || aCtrlType.equalsAscii( "List" ) || aCtrlType.equalsAscii( "Range" ) || + aCtrlType.equalsAscii( "Edit" ) || aCtrlType.equalsAscii( "Bool" ) ) { if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) @@ -488,12 +477,36 @@ void PrintDialog::setupOptionalUI() if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) { nXPos = 5; + // change to job page or back if necessary + if( (bOnJobPage && ! bOnJobPageValue) || + (! bOnJobPage && bOnJobPageValue) ) + { + if( nCurY > nMaxY ) // keep track of maximum Y + nMaxY = nCurY; + bOnJobPage = bOnJobPageValue; + if( bOnJobPage ) + { + nDynamicPageCurY = nCurY; // save nCurY + pDynamicPageParent = pCurParent; // save current parent + pCurParent = &maJobPage; // set job page as current parent + } + else + { + nCurY = nDynamicPageCurY; // set dynamic CurY + pCurParent = pDynamicPageParent; // set current tab page as parent + } + } + if( bOnJobPage ) + { + nXPos += 100 * nJobGroups++; + nCurY = nJobPageCurY; + } FixedLine* pNewSub = new FixedLine( pCurParent ); maControls.push_front( pNewSub ); pNewSub->SetText( aText ); nCurY += 4; Size aPixelSize( aTabSize ); - aPixelSize.Width() /= 2; + aPixelSize.Width() /= 3; aPixelSize.Height() = pCurParent->GetTextHeight() + 4; pNewSub->SetPosSizePixel( pNewSub->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), aPixelSize ); @@ -545,7 +558,10 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pHeading ); pHeading->SetText( aText ); Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + if( bOnJobPage ) + aPixelSize.Width() = maJobPage.LogicToPixel( Size( 90, 10 ), aFontMapMode ).Width(); + else + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), aPixelSize ); pHeading->Show(); @@ -571,8 +587,11 @@ void PrintDialog::setupOptionalUI() pBtn->SetText( aChoices[m] ); pBtn->Check( m == nSelectVal ); Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos + nDependencyIndent, 12 ), aFontMapMode ) ); - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); - pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( 15, nCurY ), aFontMapMode ), + if( bOnJobPage ) + aPixelSize.Width() = maJobPage.LogicToPixel( Size( 80, 10 ), aFontMapMode ).Width(); + else + aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); + pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), aPixelSize ); pBtn->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pBtn->SetToggleHdl( LINK( this, PrintDialog, UIOption_RadioHdl ) ); @@ -588,6 +607,7 @@ void PrintDialog::setupOptionalUI() nCurY += 12; } + nCurY += 2; nXPos = nOldXPos; } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) @@ -728,6 +748,76 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pField] = aPropertyName; nCurY += 16; + if( bDoAlign ) + { + Point aPos = pHeading->GetPosPixel(); + Size aSize = pHeading->GetSizePixel(); + aPos.Y() += (pField->GetSizePixel().Height() - aSize.Height())/2; + pHeading->SetPosSizePixel( aPos, aSize ); + } + } + else if( aCtrlType.equalsAscii( "Edit" ) && pCurParent ) + { + FixedText* pHeading = NULL; + Size aPixelSize; + if( aText.getLength() ) + { + // add a FixedText: + pHeading = new FixedText( pCurParent ); + maControls.push_front( pHeading ); + pHeading->SetText( aText ); + aPixelSize = pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ); + aPixelSize.Width() += pHeading->GetTextWidth( aText ); + pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), + aPixelSize ); + pHeading->Show(); + + // set help id + setSmartId( pHeading, "FixedText", -1, aPropertyName ); + } + + Edit* pField = new Edit( pCurParent, WB_BORDER ); + maControls.push_front( pField ); + + rtl::OUString aCurVal; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= aCurVal; + pField->SetText( aCurVal ); + + aPixelSize = Size( pField->LogicToPixel( Size( 80, 12 ), aFontMapMode ) ); + + Point aFieldPos; + bool bDoAlign = false; + if( pHeading && aPixelSize.Width() < aTabSize.Width() - 10 ) + { + aFieldPos = pHeading->GetPosPixel(); + aFieldPos.X() += pHeading->GetSizePixel().Width() + 5; + + // align heading and list box + bDoAlign = true; + } + else + { + if( pHeading ) + nCurY += 12; + aFieldPos = pCurParent->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ); + } + + pField->SetPosSizePixel( aFieldPos, aPixelSize ); + pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); + pField->Show(); + + // set help id + setSmartId( pField, "Edit", -1, aPropertyName ); + // set help text + setHelpText( pField, aHelpTexts, 0 ); + + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maControlToPropertyMap[pField] = aPropertyName; + nCurY += 16; + if( bDoAlign ) { Point aPos = pHeading->GetPosPixel(); @@ -763,7 +853,6 @@ void PrintDialog::checkControlDependencies() else maJobPage.maCollateBox.Enable( FALSE ); - maJobPage.maPagesEdit.Enable( maJobPage.maPagesButton.IsChecked() ); Image aImg( maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateImg : maJobPage.maNoCollateImg ); if( GetSettings().GetStyleSettings().GetFieldColor().IsDark() ) aImg = maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateHCImg : maJobPage.maNoCollateHCImg; @@ -846,9 +935,9 @@ void PrintDialog::preparePreview( bool i_bNewPage ) setPreviewText( mnCurPage ); - maPageScrollbar.SetRange( Range( 0, nPages ) ); - maPageScrollbar.SetThumbPos( mnCurPage ); - maPageScrollbar.SetVisibleSize( 1 ); + maPageSlider.SetRange( Range( 0, nPages-1 ) ); + maPageSlider.SetThumbPos( mnCurPage ); + maPageSlider.SetVisibleSize( 1 ); boost::shared_ptr aPrt( maPListener->getPrinter() ); @@ -899,21 +988,21 @@ void PrintDialog::updateNup() preparePreview(); } -IMPL_LINK( PrintDialog, ScrollHdl, ScrollBar*, pScrBar ) +IMPL_LINK( PrintDialog, SlideHdl, ScrollBar*, pSlider ) { - if( pScrBar == &maPageScrollbar ) + if( pSlider == &maPageSlider ) { - sal_Int32 nNewPage = static_cast( maPageScrollbar.GetThumbPos() ); + sal_Int32 nNewPage = static_cast( maPageSlider.GetThumbPos() ); setPreviewText( nNewPage ); } return 0; } -IMPL_LINK( PrintDialog, ScrollEndHdl, ScrollBar*, pScrBar ) +IMPL_LINK( PrintDialog, EndSlideHdl, ScrollBar*, pSlider ) { - if( pScrBar == &maPageScrollbar ) + if( pSlider == &maPageSlider ) { - sal_Int32 nNewPage = static_cast( maPageScrollbar.GetThumbPos() ); + sal_Int32 nNewPage = static_cast( maPageSlider.GetThumbPos() ); if( nNewPage != mnCurPage ) { mnCurPage = nNewPage; @@ -945,20 +1034,6 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maPListener->getPrinter()->Setup( this ); } checkControlDependencies(); - if( ( pButton == &maJobPage.maAllButton || - pButton == &maJobPage.maPagesButton || - pButton == &maJobPage.maSelectionButton ) - && ((RadioButton*)pButton)->IsChecked() ) - { - if( pButton == &maJobPage.maAllButton ) - maPListener->setPrintSelection( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "all" ) ) ); - else if( pButton == &maJobPage.maPagesButton ) - maPListener->setPrintSelection( maJobPage.maPagesEdit.GetText() ); - else - maPListener->setPrintSelection( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "selection" ) ) ); - - preparePreview(); - } if( pButton == &maPrinterPage.maNupPortrait || pButton == &maPrinterPage.maNupLandscape ) updateNup(); return 0; @@ -967,12 +1042,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { checkControlDependencies(); - if( pEdit == &maJobPage.maPagesEdit && maJobPage.maPagesButton.IsChecked() ) - { - maPListener->setPrintSelection( maJobPage.maPagesEdit.GetText() ); - preparePreview(); - } - else if( pEdit == &maPrinterPage.maNupRowsEdt || pEdit == &maPrinterPage.maNupColEdt ) + if( pEdit == &maPrinterPage.maNupRowsEdt || pEdit == &maPrinterPage.maNupColEdt ) { updateNup(); } @@ -1123,15 +1193,15 @@ void PrintDialog::Resize() long nMaxY = maButtonLine.GetPosPixel().Y() - 2 * aPixDiff.Height() - maPageText.GetSizePixel().Height() - - maPageScrollbar.GetSizePixel().Height(); + - maPageSlider.GetSizePixel().Height(); long nPreviewLength = std::min( nMaxX, nMaxY ); maPreviewSpace = Rectangle( Point( aPixDiff.Width(), aPixDiff.Height() ), Size( nPreviewLength, nPreviewLength ) ); - // position text and scrollbar below preview + // position text and slider below preview aBtnRect = Rectangle( Point( aPixDiff.Width(), 2*aPixDiff.Height() + nPreviewLength ), - Size( nPreviewLength, maPageScrollbar.GetSizePixel().Height() ) ); - maPageScrollbar.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); + Size( nPreviewLength, maPageSlider.GetSizePixel().Height() ) ); + maPageSlider.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); aBtnRect.Top() = aBtnRect.Bottom() + aPixDiff.Height()/2; aBtnRect.Bottom() = aBtnRect.Top() + maPageText.GetSizePixel().Height() - 1; -- cgit From 60e54d904b1c3bd46ee9bdbe0b72756ae6cc231a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 22 May 2009 10:06:06 +0000 Subject: use autoarranging --- vcl/source/window/arrange.cxx | 23 ++-- vcl/source/window/printdlg.cxx | 292 +++++++++++++++++------------------------ 2 files changed, 130 insertions(+), 185 deletions(-) diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 134e18f9935a..d52b5e813f74 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -122,17 +122,20 @@ Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const void RowOrColumn::distributeRowWidth( std::vector& io_rSizes, long /*i_nUsedWidth*/, long i_nExtraWidth ) { - // distribute extra space evenly among elements - size_t nElements = io_rSizes.size(); - long nDelta = i_nExtraWidth / nElements; - for( size_t i = 0; i < nElements; i++ ) + if( ! io_rSizes.empty() ) { - io_rSizes[i].Width() += nDelta; - i_nExtraWidth -= nDelta; + // distribute extra space evenly among elements + size_t nElements = io_rSizes.size(); + long nDelta = i_nExtraWidth / nElements; + for( size_t i = 0; i < nElements; i++ ) + { + io_rSizes[i].Width() += nDelta; + i_nExtraWidth -= nDelta; + } + // add the last pixels to the last row element + if( i_nExtraWidth > 0 && nElements > 0 ) + io_rSizes.back().Width() += i_nExtraWidth; } - // add the last pixels to the last row element - if( i_nExtraWidth > 0 && nElements > 0 ) - io_rSizes.back().Width() += i_nExtraWidth; } void RowOrColumn::resize() @@ -154,7 +157,7 @@ void RowOrColumn::resize() size_t nElements = m_aElements.size(); // get all element sizes for sizing std::vector aElementSizes( nElements ); - long nUsedWidth = m_nOuterBorder - (nElements ? m_nBorderWidth : 0); + long nUsedWidth = 2*m_nOuterBorder - (nElements ? m_nBorderWidth : 0); for( size_t i = 0; i < nElements; i++ ) { aElementSizes[i] = m_aElements[i].m_pElement diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9092d3abac83..9a5b20c0496f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -40,6 +40,7 @@ #include "vcl/jobset.h" #include "vcl/status.hxx" #include "vcl/decoview.hxx" +#include "vcl/arrange.hxx" #include "rtl/ustrbuf.hxx" @@ -331,21 +332,21 @@ static void setHelpText( Window* i_pWindow, const Sequence< rtl::OUString >& i_r i_pWindow->SetHelpText( i_rHelpTexts.getConstArray()[i_nIndex] ); } -// FIXME: this is evil hackery and witchcraft -// the automatic controls should be replaced by some kind of row/column widget void PrintDialog::setupOptionalUI() { + const long nBorderWidth = maJobPage.maCopies.GetPosPixel().X(); + + vcl::RowOrColumn aPrintRangeRow( NULL, false, nBorderWidth ); + std::vector aDynamicColumns; + vcl::RowOrColumn* pCurColumn = 0; + + aPrintRangeRow.setParentWindow( &maJobPage ); + aPrintRangeRow.setOuterBorder( nBorderWidth ); + Window* pCurParent = 0, *pDynamicPageParent = 0; - long nCurY = 0, nXPos = 5, nMaxY = 0, nJobPageCurY = 0, nDynamicPageCurY = 0; - USHORT nOptPageId = 9, nCurSubGroup = 0, nJobGroups = 0; - MapMode aFontMapMode( MAP_APPFONT ); + USHORT nOptPageId = 9, nCurSubGroup = 0; bool bOnJobPage = false; - nJobPageCurY = maJobPage.PixelToLogic( maJobPage.maCollateImage.GetPosPixel(), aFontMapMode ).Y(); - nJobPageCurY += maJobPage.PixelToLogic( maJobPage.maCollateImage.GetSizePixel(), aFontMapMode ).Height(); - nJobPageCurY += 5; - - Size aTabSize = maTabCtrl.GetTabPageSizePixel(); const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -360,7 +361,6 @@ void PrintDialog::setupOptionalUI() Sequence< rtl::OUString > aChoices; Sequence< rtl::OUString > aHelpTexts; sal_Int64 nMinValue = 0, nMaxValue = 0; - long nDependencyIndent = 0; sal_Int32 nCurHelpText = 0; sal_Bool bOnJobPageValue = sal_False; @@ -407,16 +407,14 @@ void PrintDialog::setupOptionalUI() if( pWin->GetParent() == pCurParent ) { // is it a labeled window ? - if( dynamic_cast< ListBox* >(pWin) || - dynamic_cast< NumericField* >(pWin) ) + if( dynamic_cast< ListBox* >(pWin) || + dynamic_cast< Edit* >(pWin) + ) { Window* pLabelWin = pWin->GetLabeledBy(); if( dynamic_cast(pLabelWin) ) // sanity check pWin = pLabelWin; } - long nDependencyXPos = PixelToLogic( pWin->GetPosPixel(), aFontMapMode ).X(); - if( (nDependencyXPos + 5) > nXPos ) - nDependencyIndent = nDependencyXPos + 5 - nXPos; } } } @@ -452,15 +450,10 @@ void PrintDialog::setupOptionalUI() { if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) { - if( nCurY > nMaxY ) - nMaxY = nCurY; - // add new tab page TabPage* pNewGroup = new TabPage( &maTabCtrl ); maControls.push_front( pNewGroup ); pCurParent = pNewGroup; - nCurY = 5; - nXPos = 5; pNewGroup->SetText( aText ); maTabCtrl.InsertPage( ++nOptPageId, aText ); maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); @@ -472,52 +465,54 @@ void PrintDialog::setupOptionalUI() // reset subgroup counter nCurSubGroup = 0; + + aDynamicColumns.push_back( new vcl::RowOrColumn( NULL, true, nBorderWidth ) ); + pCurColumn = aDynamicColumns.back(); + pCurColumn->setParentWindow( pNewGroup ); + pCurColumn->setOuterBorder( nBorderWidth ); } if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) { - nXPos = 5; // change to job page or back if necessary if( (bOnJobPage && ! bOnJobPageValue) || (! bOnJobPage && bOnJobPageValue) ) { - if( nCurY > nMaxY ) // keep track of maximum Y - nMaxY = nCurY; bOnJobPage = bOnJobPageValue; if( bOnJobPage ) { - nDynamicPageCurY = nCurY; // save nCurY pDynamicPageParent = pCurParent; // save current parent pCurParent = &maJobPage; // set job page as current parent } else { - nCurY = nDynamicPageCurY; // set dynamic CurY pCurParent = pDynamicPageParent; // set current tab page as parent } } + if( bOnJobPage ) { - nXPos += 100 * nJobGroups++; - nCurY = nJobPageCurY; + // create a new column in the PrintRange row + vcl::RowOrColumn* pNewColumn = new vcl::RowOrColumn( &aPrintRangeRow, true, nBorderWidth ); + aPrintRangeRow.addChild( pNewColumn ); + pCurColumn = pNewColumn; } + else + pCurColumn = aDynamicColumns.back(); + + // create group FixedLine FixedLine* pNewSub = new FixedLine( pCurParent ); maControls.push_front( pNewSub ); pNewSub->SetText( aText ); - nCurY += 4; - Size aPixelSize( aTabSize ); - aPixelSize.Width() /= 3; - aPixelSize.Height() = pCurParent->GetTextHeight() + 4; - pNewSub->SetPosSizePixel( pNewSub->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), - aPixelSize ); pNewSub->Show(); - nCurY += 12; - nXPos += 5; // set help id setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); // set help text setHelpText( pNewSub, aHelpTexts, 0 ); + + // add group to current column + pCurColumn->addWindow( pNewSub ); } else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { @@ -525,13 +520,8 @@ void PrintDialog::setupOptionalUI() CheckBox* pNewBox = new CheckBox( pCurParent ); maControls.push_front( pNewBox ); pNewBox->SetText( aText ); - - // FIXME: measure text - pNewBox->SetPosSizePixel( pNewBox->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), - pNewBox->LogicToPixel( Size( 100, 10 ), aFontMapMode ) ); - nCurY += 12; - pNewBox->Show(); + sal_Bool bVal = sal_False; PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal ) @@ -547,34 +537,34 @@ void PrintDialog::setupOptionalUI() setSmartId( pNewBox, "CheckBox", -1, aPropertyName ); // set help text setHelpText( pNewBox, aHelpTexts, 0 ); + + // add checkbox to current column + pCurColumn->addWindow( pNewBox ); } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { - long nOldXPos = nXPos; + vcl::RowOrColumn* pRadioColumn = pCurColumn; if( aText.getLength() ) { // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); - Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); - if( bOnJobPage ) - aPixelSize.Width() = maJobPage.LogicToPixel( Size( 90, 10 ), aFontMapMode ).Width(); - else - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), - aPixelSize ); pHeading->Show(); - nXPos += 10; - nCurY += 12; - // set help id setSmartId( pHeading, "FixedText", -1, aPropertyName ); // set help text setHelpText( pHeading, aHelpTexts, nCurHelpText++ ); + // add fixed text to current column + pCurColumn->addWindow( pHeading ); + // add an indent to the current column + vcl::Indenter* pIndent = new vcl::Indenter( pCurColumn, 15 ); + pCurColumn->addChild( pIndent ); + // and create a column inside the indent + pRadioColumn = new vcl::RowOrColumn( pIndent ); + pIndent->setChild( pRadioColumn ); } - // iterate options sal_Int32 nSelectVal = 0; PropertyValue* pVal = maPListener->getValue( aPropertyName ); @@ -586,13 +576,6 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); pBtn->Check( m == nSelectVal ); - Size aPixelSize( pBtn->LogicToPixel( Size( 10 + nXPos + nDependencyIndent, 12 ), aFontMapMode ) ); - if( bOnJobPage ) - aPixelSize.Width() = maJobPage.LogicToPixel( Size( 80, 10 ), aFontMapMode ).Width(); - else - aPixelSize.Width() = aTabSize.Width() - aPixelSize.Width(); - pBtn->SetPosSizePixel( pBtn->LogicToPixel( Point( nXPos, nCurY ), aFontMapMode ), - aPixelSize ); pBtn->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pBtn->SetToggleHdl( LINK( this, PrintDialog, UIOption_RadioHdl ) ); pBtn->Show(); @@ -604,67 +587,41 @@ void PrintDialog::setupOptionalUI() setSmartId( pBtn, "RadioButton", m, aPropertyName ); // set help text setHelpText( pBtn, aHelpTexts, nCurHelpText++ ); - - nCurY += 12; + // add the radio button to the column + pRadioColumn->addWindow( pBtn ); } - nCurY += 2; - nXPos = nOldXPos; } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) { + // create a row in the current column + vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pPair ); + // add a FixedText: - FixedText* pHeading = new FixedText( pCurParent ); + FixedText* pHeading = new FixedText( pCurParent, WB_VCENTER ); maControls.push_front( pHeading ); pHeading->SetText( aText ); - Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); - aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), - aPixelSize ); pHeading->Show(); // set help id setSmartId( pHeading, "FixedText", -1, aPropertyName ); + // add to pair + pPair->addWindow( pHeading ); + ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); maControls.push_front( pList ); // iterate options - long nMaxTextWidth = 0; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { pList->InsertEntry( aChoices[m] ); - long nEntryWidth = pList->GetTextWidth( aChoices[m] ); - if( nEntryWidth > nMaxTextWidth ) - nMaxTextWidth = nEntryWidth; } - nMaxTextWidth += 50; sal_Int32 nSelectVal = 0; PropertyValue* pVal = maPListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; pList->SelectEntryPos( static_cast(nSelectVal) ); - - aPixelSize = Size( pList->LogicToPixel( Size( 25, 12 ), aFontMapMode ) ); - aPixelSize.Width() = nMaxTextWidth; - aPixelSize.Height() *= aChoices.getLength() > 15 ? 15 : aChoices.getLength(); - - Point aListPos; - bool bDoAlign = false; - if( nMaxTextWidth + aPixelSize.Width() < aTabSize.Width() - 10 ) - { - aListPos = pHeading->GetPosPixel(); - aListPos.X() += pHeading->GetSizePixel().Width() + 5; - - // align heading and list box - bDoAlign = true; - } - else - { - nCurY += 12; - aListPos = pCurParent->LogicToPixel( Point( 15 + nDependencyIndent, nCurY ), aFontMapMode ); - } - - pList->SetPosSizePixel( aListPos, aPixelSize ); pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); pList->Show(); @@ -676,31 +633,28 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); maControlToPropertyMap[pList] = aPropertyName; - nCurY += 16; - if( bDoAlign ) - { - Point aPos = pHeading->GetPosPixel(); - Size aSize = pHeading->GetSizePixel(); - aPos.Y() += (pList->GetSizePixel().Height() - aSize.Height())/2; - pHeading->SetPosSizePixel( aPos, aSize ); - } + // finish the pair + pPair->addWindow( pList ); } else if( aCtrlType.equalsAscii( "Range" ) && pCurParent ) { + // create a row in the current column + vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pPair ); + // add a FixedText: FixedText* pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); - Size aPixelSize( pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ) ); - aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), - aPixelSize ); pHeading->Show(); // set help id setSmartId( pHeading, "FixedText", -1, aPropertyName ); + // add to pair + pPair->addWindow( pHeading ); + NumericField* pField = new NumericField( pCurParent, WB_BORDER | WB_SPIN ); maControls.push_front( pField ); @@ -716,25 +670,6 @@ void PrintDialog::setupOptionalUI() pVal->Value >>= nCurVal; pField->SetValue( nCurVal ); - aPixelSize = Size( pField->LogicToPixel( Size( 80, 12 ), aFontMapMode ) ); - - Point aFieldPos; - bool bDoAlign = false; - if( aPixelSize.Width() < aTabSize.Width() - 10 ) - { - aFieldPos = pHeading->GetPosPixel(); - aFieldPos.X() += pHeading->GetSizePixel().Width() + 5; - - // align heading and list box - bDoAlign = true; - } - else - { - nCurY += 12; - aFieldPos = pCurParent->LogicToPixel( Point( 15 + nDependencyIndent, nCurY ), aFontMapMode ); - } - - pField->SetPosSizePixel( aFieldPos, aPixelSize ); pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -746,34 +681,30 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); maControlToPropertyMap[pField] = aPropertyName; - nCurY += 16; - if( bDoAlign ) - { - Point aPos = pHeading->GetPosPixel(); - Size aSize = pHeading->GetSizePixel(); - aPos.Y() += (pField->GetSizePixel().Height() - aSize.Height())/2; - pHeading->SetPosSizePixel( aPos, aSize ); - } + // add to pair + pPair->addWindow( pField ); } else if( aCtrlType.equalsAscii( "Edit" ) && pCurParent ) { + vcl::RowOrColumn* pEditColumn = pCurColumn; FixedText* pHeading = NULL; - Size aPixelSize; if( aText.getLength() ) { + // create a row in the current column + vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pPair ); + pEditColumn = pPair; + // add a FixedText: pHeading = new FixedText( pCurParent ); maControls.push_front( pHeading ); pHeading->SetText( aText ); - aPixelSize = pHeading->LogicToPixel( Size( 10, 10 ), aFontMapMode ); - aPixelSize.Width() += pHeading->GetTextWidth( aText ); - pHeading->SetPosSizePixel( pHeading->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ), - aPixelSize ); pHeading->Show(); // set help id setSmartId( pHeading, "FixedText", -1, aPropertyName ); + pPair->addWindow( pHeading ); } Edit* pField = new Edit( pCurParent, WB_BORDER ); @@ -784,27 +715,6 @@ void PrintDialog::setupOptionalUI() if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aCurVal; pField->SetText( aCurVal ); - - aPixelSize = Size( pField->LogicToPixel( Size( 80, 12 ), aFontMapMode ) ); - - Point aFieldPos; - bool bDoAlign = false; - if( pHeading && aPixelSize.Width() < aTabSize.Width() - 10 ) - { - aFieldPos = pHeading->GetPosPixel(); - aFieldPos.X() += pHeading->GetSizePixel().Width() + 5; - - // align heading and list box - bDoAlign = true; - } - else - { - if( pHeading ) - nCurY += 12; - aFieldPos = pCurParent->LogicToPixel( Point( nXPos + nDependencyIndent, nCurY ), aFontMapMode ); - } - - pField->SetPosSizePixel( aFieldPos, aPixelSize ); pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -816,15 +726,8 @@ void PrintDialog::setupOptionalUI() maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); maControlToPropertyMap[pField] = aPropertyName; - nCurY += 16; - if( bDoAlign ) - { - Point aPos = pHeading->GetPosPixel(); - Size aSize = pHeading->GetSizePixel(); - aPos.Y() += (pField->GetSizePixel().Height() - aSize.Height())/2; - pHeading->SetPosSizePixel( aPos, aSize ); - } + pEditColumn->addWindow( pField ); } } else @@ -833,17 +736,56 @@ void PrintDialog::setupOptionalUI() } } - if( nCurY > nMaxY ) - nMaxY = nCurY; + // calculate job page + long nJobPageCurY = maJobPage.maCollateImage.GetPosPixel().Y(); + nJobPageCurY += maJobPage.maCollateImage.GetSizePixel().Height(); + + Size aMaxSize = aPrintRangeRow.getOptimalSize( WINDOWSIZE_PREFERRED ); + aMaxSize.Height() += nJobPageCurY; + + Size aMaxPageSize; + for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); + it != aDynamicColumns.end(); ++it ) + { + Size aPageSize( (*it)->getOptimalSize( WINDOWSIZE_PREFERRED ) ); + if( aPageSize.Width() > aMaxPageSize.Width() ) + aMaxPageSize.Width() = aPageSize.Width(); + if( aPageSize.Height() > aMaxPageSize.Height() ) + aMaxPageSize.Height() = aPageSize.Height(); + } + if( aMaxPageSize.Width() > aMaxSize.Width() ) + aMaxSize.Width() = aMaxPageSize.Width(); + if( aMaxPageSize.Height() > aMaxSize.Height() ) + aMaxSize.Height() = aMaxPageSize.Height(); // resize dialog if necessary - Size aMaxSize( LogicToPixel( Size( nMaxY, nMaxY ), aFontMapMode ) ); - if( aMaxSize.Height() > aTabSize.Height() ) + Size aTabSize = maTabCtrl.GetTabPageSizePixel(); + if( aMaxSize.Height() > aTabSize.Height() || aMaxSize.Width() > aTabSize.Width() ) { Size aCurSize( GetSizePixel() ); - aCurSize.Height() += aMaxSize.Height() - aTabSize.Height(); + if( aMaxSize.Height() > aTabSize.Height() ) + aCurSize.Height() += aMaxSize.Height() - aTabSize.Height(); + if( aMaxSize.Width() > aTabSize.Width() ) + { + aCurSize.Width() += aMaxSize.Width() - aTabSize.Width(); + // and the tab ctrl needs more space, too + aTabSize.Width() = aMaxSize.Width(); + maTabCtrl.SetSizePixel( aTabSize ); + } SetSizePixel( aCurSize ); } + + // and finally arrange controls + aTabSize = maTabCtrl.GetTabPageSizePixel(); + aPrintRangeRow.setManagedArea( Rectangle( Point( 0, nJobPageCurY ), + Size( aTabSize.Width(), aTabSize.Height() - nJobPageCurY ) ) ); + for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); + it != aDynamicColumns.end(); ++it ) + { + (*it)->setManagedArea( Rectangle( Point(), aMaxPageSize ) ); + delete *it; + *it = NULL; + } } void PrintDialog::checkControlDependencies() -- cgit From 0b93cf4d4dd806181f6ec6afa4097c43bf1f2420 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 22 May 2009 10:19:01 +0000 Subject: simplify code --- vcl/source/window/printdlg.cxx | 210 ++++++++++++++++++----------------------- 1 file changed, 93 insertions(+), 117 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9a5b20c0496f..2d53abd9ec86 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -591,143 +591,119 @@ void PrintDialog::setupOptionalUI() pRadioColumn->addWindow( pBtn ); } } - else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) + else if( ( aCtrlType.equalsAscii( "List" ) || + aCtrlType.equalsAscii( "Range" ) || + aCtrlType.equalsAscii( "Edit" ) + ) && pCurParent ) { - // create a row in the current column - vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); - pCurColumn->addChild( pPair ); - - // add a FixedText: - FixedText* pHeading = new FixedText( pCurParent, WB_VCENTER ); - maControls.push_front( pHeading ); - pHeading->SetText( aText ); - pHeading->Show(); - - // set help id - setSmartId( pHeading, "FixedText", -1, aPropertyName ); - - // add to pair - pPair->addWindow( pHeading ); - - ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); - maControls.push_front( pList ); - - // iterate options - for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + vcl::RowOrColumn* pFieldColumn = pCurColumn; + if( aText.getLength() ) { - pList->InsertEntry( aChoices[m] ); - } - sal_Int32 nSelectVal = 0; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); - if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= nSelectVal; - pList->SelectEntryPos( static_cast(nSelectVal) ); - pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); - pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); - pList->Show(); - - // set help id - setSmartId( pList, "ListBox", -1, aPropertyName ); - // set help text - setHelpText( pList, aHelpTexts, 0 ); - - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); - maControlToPropertyMap[pList] = aPropertyName; - - // finish the pair - pPair->addWindow( pList ); - } - else if( aCtrlType.equalsAscii( "Range" ) && pCurParent ) - { - // create a row in the current column - vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); - pCurColumn->addChild( pPair ); - - // add a FixedText: - FixedText* pHeading = new FixedText( pCurParent ); - maControls.push_front( pHeading ); - pHeading->SetText( aText ); - pHeading->Show(); + // create a row in the current column + pFieldColumn = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pFieldColumn ); - // set help id - setSmartId( pHeading, "FixedText", -1, aPropertyName ); + // add a FixedText: + FixedText* pHeading = new FixedText( pCurParent, WB_VCENTER ); + maControls.push_front( pHeading ); + pHeading->SetText( aText ); + pHeading->Show(); - // add to pair - pPair->addWindow( pHeading ); + // set help id + setSmartId( pHeading, "FixedText", -1, aPropertyName ); - NumericField* pField = new NumericField( pCurParent, WB_BORDER | WB_SPIN ); - maControls.push_front( pField ); + // add to row + pFieldColumn->addWindow( pHeading ); + } - // set min/max and current value - if( nMinValue != nMaxValue ) + if( aCtrlType.equalsAscii( "List" ) ) { - pField->SetMin( nMinValue ); - pField->SetMax( nMaxValue ); - } - sal_Int64 nCurVal = 0; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); - if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= nCurVal; - pField->SetValue( nCurVal ); + ListBox* pList = new ListBox( pCurParent, WB_DROPDOWN | WB_BORDER ); + maControls.push_front( pList ); - pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); - pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); - pField->Show(); + // iterate options + for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) + { + pList->InsertEntry( aChoices[m] ); + } + sal_Int32 nSelectVal = 0; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= nSelectVal; + pList->SelectEntryPos( static_cast(nSelectVal) ); + pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); + pList->SetDropDownLineCount( aChoices.getLength() ); + pList->Show(); - // set help id - setSmartId( pField, "NumericField", -1, aPropertyName ); - // set help text - setHelpText( pField, aHelpTexts, 0 ); + // set help id + setSmartId( pList, "ListBox", -1, aPropertyName ); + // set help text + setHelpText( pList, aHelpTexts, 0 ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); - maControlToPropertyMap[pField] = aPropertyName; + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); + maControlToPropertyMap[pList] = aPropertyName; - // add to pair - pPair->addWindow( pField ); - } - else if( aCtrlType.equalsAscii( "Edit" ) && pCurParent ) - { - vcl::RowOrColumn* pEditColumn = pCurColumn; - FixedText* pHeading = NULL; - if( aText.getLength() ) + // finish the pair + pFieldColumn->addWindow( pList ); + } + else if( aCtrlType.equalsAscii( "Range" ) ) { - // create a row in the current column - vcl::RowOrColumn* pPair = new vcl::RowOrColumn( pCurColumn, false ); - pCurColumn->addChild( pPair ); - pEditColumn = pPair; + NumericField* pField = new NumericField( pCurParent, WB_BORDER | WB_SPIN ); + maControls.push_front( pField ); - // add a FixedText: - pHeading = new FixedText( pCurParent ); - maControls.push_front( pHeading ); - pHeading->SetText( aText ); - pHeading->Show(); + // set min/max and current value + if( nMinValue != nMaxValue ) + { + pField->SetMin( nMinValue ); + pField->SetMax( nMaxValue ); + } + sal_Int64 nCurVal = 0; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= nCurVal; + pField->SetValue( nCurVal ); + + pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); + pField->Show(); // set help id - setSmartId( pHeading, "FixedText", -1, aPropertyName ); - pPair->addWindow( pHeading ); - } + setSmartId( pField, "NumericField", -1, aPropertyName ); + // set help text + setHelpText( pField, aHelpTexts, 0 ); - Edit* pField = new Edit( pCurParent, WB_BORDER ); - maControls.push_front( pField ); + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maControlToPropertyMap[pField] = aPropertyName; - rtl::OUString aCurVal; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); - if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= aCurVal; - pField->SetText( aCurVal ); - pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); - pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); - pField->Show(); + // add to row + pFieldColumn->addWindow( pField ); + } + else if( aCtrlType.equalsAscii( "Edit" ) ) + { + Edit* pField = new Edit( pCurParent, WB_BORDER ); + maControls.push_front( pField ); + + rtl::OUString aCurVal; + PropertyValue* pVal = maPListener->getValue( aPropertyName ); + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= aCurVal; + pField->SetText( aCurVal ); + pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); + pField->Show(); - // set help id - setSmartId( pField, "Edit", -1, aPropertyName ); - // set help text - setHelpText( pField, aHelpTexts, 0 ); + // set help id + setSmartId( pField, "Edit", -1, aPropertyName ); + // set help text + setHelpText( pField, aHelpTexts, 0 ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); - maControlToPropertyMap[pField] = aPropertyName; + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maControlToPropertyMap[pField] = aPropertyName; - pEditColumn->addWindow( pField ); + // add to row + pFieldColumn->addWindow( pField ); + } } } else -- cgit From ea23b7444553505a98f0cf9258631e45884303ec Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 25 May 2009 09:08:28 +0000 Subject: use shared ptr, newline --- vcl/inc/vcl/arrange.hxx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 03a388a519bd..29ec72a27bd9 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -34,6 +34,7 @@ #include "vcl/window.hxx" #include +#include namespace vcl { @@ -54,12 +55,12 @@ namespace vcl protected: struct Element { - Window* m_pElement; - WindowArranger* m_pChild; + Window* m_pElement; + boost::shared_ptr m_pChild; Element() : m_pElement( NULL ) - , m_pChild( NULL ) + , m_pChild() {} Element( Window* i_pWin, WindowArranger* i_pChild ) @@ -67,7 +68,7 @@ namespace vcl , m_pChild( i_pChild ) {} - void deleteChild() { delete m_pChild; m_pChild = NULL; } + void deleteChild() { m_pChild.reset(); } }; Window* m_pParentWindow; @@ -162,7 +163,7 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } - virtual WindowArranger* getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild : NULL; } + virtual WindowArranger* getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild.get() : 0; } virtual Window* getWindow( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pElement : NULL; } void setIndent( long i_nIndent ) @@ -176,4 +177,5 @@ namespace vcl }; } -#endif \ No newline at end of file +#endif + -- cgit From 708bbabd2b9c99488ec128278b0a79d358c811cc Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 25 May 2009 15:12:27 +0000 Subject: fix some warnings --- vcl/source/window/arrange.cxx | 8 ++++---- vcl/source/window/printdlg.cxx | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index d52b5e813f74..6aae74919dad 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -65,7 +65,7 @@ RowOrColumn::~RowOrColumn() WindowArranger* RowOrColumn::getChild( size_t i_nIndex ) const { - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : NULL; + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild.get() : NULL; } Window* RowOrColumn::getWindow( size_t i_nIndex ) const @@ -274,7 +274,7 @@ void RowOrColumn::remove( WindowArranger* i_pChild ) for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); it != m_aElements.end(); ++it ) { - if( it->m_pChild == i_pChild ) + if( it->m_pChild.get() == i_pChild ) { m_aElements.erase( it ); return; @@ -327,8 +327,8 @@ void Indenter::setWindow( Window* i_pWindow ) void Indenter::setChild( WindowArranger* i_pChild ) { - OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pChild == 0 ); - m_aElement.m_pChild = i_pChild; + OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0 ) || i_pChild == 0 ); + m_aElement.m_pChild.reset( i_pChild ); } void Indenter::setParentWindow( Window* i_pNewParent ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 2d53abd9ec86..ac335940f75e 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -633,7 +633,7 @@ void PrintDialog::setupOptionalUI() pList->SelectEntryPos( static_cast(nSelectVal) ); pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); - pList->SetDropDownLineCount( aChoices.getLength() ); + pList->SetDropDownLineCount( static_cast(aChoices.getLength()) ); pList->Show(); // set help id -- cgit From 1b47f9b4216522537b01b687491cfd50145cd623 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 26 May 2009 14:01:29 +0000 Subject: add completely useless PCH directive to satisfy stupid windows compiler --- vcl/source/window/arrange.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 6aae74919dad..2d92a3a287fd 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -28,6 +28,8 @@ * ************************************************************************/ +#include "precompiled_vcl.hxx" + #include "vcl/arrange.hxx" #include "osl/diagnose.h" -- cgit From e7e3874e373e3ae1bf4da96c0fcd0ea9a394a92b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 27 May 2009 12:26:30 +0000 Subject: make WindowArranger API safer --- vcl/inc/vcl/arrange.hxx | 23 +++++++++++++++-------- vcl/source/window/arrange.cxx | 18 +++++++++--------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 29ec72a27bd9..e2d1e9e677e9 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -63,7 +63,7 @@ namespace vcl , m_pChild() {} - Element( Window* i_pWin, WindowArranger* i_pChild ) + Element( Window* i_pWin, boost::shared_ptr const & i_pChild = boost::shared_ptr() ) : m_pElement( i_pWin ) , m_pChild( i_pChild ) {} @@ -97,7 +97,7 @@ namespace vcl virtual void setParent( WindowArranger* ); virtual size_t countElements() const = 0; - virtual WindowArranger* getChild( size_t i_nIndex ) const = 0; + virtual boost::shared_ptr getChild( size_t i_nIndex ) const = 0; virtual Window* getWindow( size_t i_nIndex ) const = 0; void setManagedArea( const Rectangle& i_rArea ) @@ -122,7 +122,8 @@ namespace vcl void distributeRowWidth( std::vector< Size >& io_rSizes, long i_nUsedWidth, long i_nExtraWidth ); public: - RowOrColumn( WindowArranger* i_pParent = NULL, bool bColumn = true, long i_nBorderWidth = 5 ) + RowOrColumn( WindowArranger* i_pParent = NULL, + bool bColumn = true, long i_nBorderWidth = 5 ) : WindowArranger( i_pParent ) , m_nBorderWidth( i_nBorderWidth ) , m_bColumn( bColumn ) @@ -134,7 +135,7 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return m_aElements.size(); } - virtual WindowArranger* getChild( size_t i_nIndex ) const; + virtual boost::shared_ptr getChild( size_t i_nIndex ) const; virtual Window* getWindow( size_t i_nIndex ) const; // add a managed window at the given index @@ -142,8 +143,11 @@ namespace vcl void addWindow( Window*, sal_Int32 nIndex = -1 ); void remove( Window* ); - void addChild( WindowArranger*, sal_Int32 nIndex = -1 ); - void remove( WindowArranger* ); + void addChild( boost::shared_ptr const &, sal_Int32 nIndex = -1 ); + // convenience: use for addChild( new WindowArranger( ... ) ) constructs + void addChild( WindowArranger* i_pNewChild, sal_Int32 nIndex = -1 ) + { addChild( boost::shared_ptr( i_pNewChild ), nIndex ); } + void remove( boost::shared_ptr const & ); }; class Indenter : public WindowArranger @@ -163,7 +167,7 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } - virtual WindowArranger* getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild.get() : 0; } + virtual boost::shared_ptr getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild : boost::shared_ptr(); } virtual Window* getWindow( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pElement : NULL; } void setIndent( long i_nIndent ) @@ -173,7 +177,10 @@ namespace vcl } void setWindow( Window* ); - void setChild( WindowArranger* ); + void setChild( boost::shared_ptr const & ); + // convenience: use for setChild( new WindowArranger( ... ) ) constructs + void setChild( WindowArranger* i_pChild ) + { setChild( boost::shared_ptr( i_pChild ) ); } }; } diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 2d92a3a287fd..bedfb6c9b533 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -65,9 +65,9 @@ RowOrColumn::~RowOrColumn() } } -WindowArranger* RowOrColumn::getChild( size_t i_nIndex ) const +boost::shared_ptr RowOrColumn::getChild( size_t i_nIndex ) const { - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild.get() : NULL; + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : boost::shared_ptr(); } Window* RowOrColumn::getWindow( size_t i_nIndex ) const @@ -230,17 +230,17 @@ void RowOrColumn::setParentWindow( Window* i_pNewParent ) void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nIndex ) { if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) - m_aElements.push_back( WindowArranger::Element( i_pWindow, NULL ) ); + m_aElements.push_back( WindowArranger::Element( i_pWindow ) ); else { std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); while( i_nIndex-- ) ++it; - m_aElements.insert( it, WindowArranger::Element( i_pWindow, NULL ) ); + m_aElements.insert( it, WindowArranger::Element( i_pWindow ) ); } } -void RowOrColumn::addChild( WindowArranger* i_pChild, sal_Int32 i_nIndex ) +void RowOrColumn::addChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nIndex ) { if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) m_aElements.push_back( WindowArranger::Element( NULL, i_pChild ) ); @@ -269,14 +269,14 @@ void RowOrColumn::remove( Window* i_pWindow ) } } -void RowOrColumn::remove( WindowArranger* i_pChild ) +void RowOrColumn::remove( boost::shared_ptr const & i_pChild ) { if( i_pChild ) { for( std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); it != m_aElements.end(); ++it ) { - if( it->m_pChild.get() == i_pChild ) + if( it->m_pChild == i_pChild ) { m_aElements.erase( it ); return; @@ -327,10 +327,10 @@ void Indenter::setWindow( Window* i_pWindow ) m_aElement.m_pElement = i_pWindow; } -void Indenter::setChild( WindowArranger* i_pChild ) +void Indenter::setChild( boost::shared_ptr const & i_pChild ) { OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0 ) || i_pChild == 0 ); - m_aElement.m_pChild.reset( i_pChild ); + m_aElement.m_pChild = i_pChild; } void Indenter::setParentWindow( Window* i_pNewParent ) -- cgit From 2d74f4c2357195cc0c7b3bd0ffe9fb93e83c18e0 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 27 May 2009 12:44:22 +0000 Subject: fix last page in preview missing --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index ac335940f75e..804711c62b50 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -853,7 +853,7 @@ void PrintDialog::preparePreview( bool i_bNewPage ) setPreviewText( mnCurPage ); - maPageSlider.SetRange( Range( 0, nPages-1 ) ); + maPageSlider.SetRange( Range( 0, nPages ) ); maPageSlider.SetThumbPos( mnCurPage ); maPageSlider.SetVisibleSize( 1 ); -- cgit From 2f7007962edc48f987f14e7631bf3ddb96af7f7f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 27 May 2009 17:40:24 +0000 Subject: print range changes, dependency UI --- vcl/inc/vcl/arrange.hxx | 30 ++++-- vcl/inc/vcl/print.hxx | 13 ++- vcl/source/control/edit.cxx | 5 + vcl/source/gdi/print3.cxx | 27 ++++-- vcl/source/window/arrange.cxx | 77 ++++++++++++---- vcl/source/window/printdlg.cxx | 204 ++++++++++++++++++++++------------------- 6 files changed, 226 insertions(+), 130 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index e2d1e9e677e9..fdaf957dce76 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -57,18 +57,26 @@ namespace vcl { Window* m_pElement; boost::shared_ptr m_pChild; + sal_Int32 m_nExpandPriority; Element() : m_pElement( NULL ) , m_pChild() + , m_nExpandPriority( 0 ) {} - Element( Window* i_pWin, boost::shared_ptr const & i_pChild = boost::shared_ptr() ) + Element( Window* i_pWin, + boost::shared_ptr const & i_pChild = boost::shared_ptr(), + sal_Int32 i_nExpandPriority = 0 + ) : m_pElement( i_pWin ) , m_pChild( i_pChild ) + , m_nExpandPriority( i_nExpandPriority ) {} void deleteChild() { m_pChild.reset(); } + + sal_Int32 getExpandPriority() const; }; Window* m_pParentWindow; @@ -99,6 +107,7 @@ namespace vcl virtual size_t countElements() const = 0; virtual boost::shared_ptr getChild( size_t i_nIndex ) const = 0; virtual Window* getWindow( size_t i_nIndex ) const = 0; + virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const = 0; void setManagedArea( const Rectangle& i_rArea ) { @@ -137,16 +146,17 @@ namespace vcl virtual size_t countElements() const { return m_aElements.size(); } virtual boost::shared_ptr getChild( size_t i_nIndex ) const; virtual Window* getWindow( size_t i_nIndex ) const; + virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const; // add a managed window at the given index // an index smaller than zero means add the window at the end - void addWindow( Window*, sal_Int32 nIndex = -1 ); + void addWindow( Window*, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ); void remove( Window* ); - void addChild( boost::shared_ptr const &, sal_Int32 nIndex = -1 ); + void addChild( boost::shared_ptr const &, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ); // convenience: use for addChild( new WindowArranger( ... ) ) constructs - void addChild( WindowArranger* i_pNewChild, sal_Int32 nIndex = -1 ) - { addChild( boost::shared_ptr( i_pNewChild ), nIndex ); } + void addChild( WindowArranger* i_pNewChild, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ) + { addChild( boost::shared_ptr( i_pNewChild ), i_nExpandPrio, i_nIndex ); } void remove( boost::shared_ptr const & ); }; @@ -169,6 +179,8 @@ namespace vcl virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } virtual boost::shared_ptr getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild : boost::shared_ptr(); } virtual Window* getWindow( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pElement : NULL; } + virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const + { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } void setIndent( long i_nIndent ) { @@ -176,11 +188,11 @@ namespace vcl resize(); } - void setWindow( Window* ); - void setChild( boost::shared_ptr const & ); + void setWindow( Window*, sal_Int32 i_nExpandPrio = 0 ); + void setChild( boost::shared_ptr const &, sal_Int32 i_nExpandPrio = 0 ); // convenience: use for setChild( new WindowArranger( ... ) ) constructs - void setChild( WindowArranger* i_pChild ) - { setChild( boost::shared_ptr( i_pChild ) ); } + void setChild( WindowArranger* i_pChild, sal_Int32 i_nExpandPrio = 0 ) + { setChild( boost::shared_ptr( i_pChild ), i_nExpandPrio ); } }; } diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 98e08312e5ca..774a74572d59 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -556,6 +556,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const com::sun::star::beans::PropertyValue* i_pValue = NULL, const rtl::OUString* i_pDependsOnName = NULL, sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False, const com::sun::star::beans::PropertyValue* i_pAddProps = NULL, sal_Int32 i_nAddProps = 0 ); @@ -574,7 +575,8 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const rtl::OUString& i_rProperty, sal_Bool i_bValue, const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1 + sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False ); // create a set of choices (either a radio button group or a list box) @@ -585,7 +587,8 @@ class VCL_DLLPUBLIC PrinterOptionsHelper sal_Int32 i_nValue, const rtl::OUString& i_rType = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Radio" ) ), const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1 + sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False ); // create an integer range (e.g. a spin field) @@ -597,7 +600,8 @@ class VCL_DLLPUBLIC PrinterOptionsHelper sal_Int32 i_nMinValue = -1, sal_Int32 i_nMaxValue = -2, const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1 + sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False ); // create a string field @@ -607,7 +611,8 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const rtl::OUString& i_rProperty, const rtl::OUString& i_rValue, const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1 + sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False ); }; diff --git a/vcl/source/control/edit.cxx b/vcl/source/control/edit.cxx index 3834e4de8677..cbead10a4618 100644 --- a/vcl/source/control/edit.cxx +++ b/vcl/source/control/edit.cxx @@ -2831,6 +2831,11 @@ void Edit::SetSubEdit( Edit* pEdit ) Size Edit::CalcMinimumSize() const { Size aSize ( GetTextWidth( GetText() ), GetTextHeight() ); + // do not create edit fields in which one cannot enter anything + // a default minimum width should exist for at least 3 characters + Size aMinSize ( CalcSize( 3 ) ); + if( aSize.Width() < aMinSize.Width() ) + aSize.Width() = aMinSize.Width(); return CalcWindowSize( aSize ); } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index d16db4ef9aec..ed1080a70e7b 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -927,6 +927,7 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, const PropertyValue* i_pVal, const rtl::OUString* i_pDependsOnName, sal_Int32 i_nDependsOnEntry, + sal_Bool i_bAttachToDependency, const PropertyValue* i_pAddProps, sal_Int32 i_nAddProps ) @@ -937,6 +938,7 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + (i_rHelpTexts.getLength() ? 1 : 0) // HelpText + (i_pVal ? 1 : 0) // Property + (i_pDependsOnName ? (i_nDependsOnEntry != -1 ? 2 : 1) : 0) // dependencies + + (i_pDependsOnName && i_bAttachToDependency ? 1 : 0) // attach to dependency + i_nAddProps ; @@ -968,6 +970,11 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnEntry" ) ); aCtrl[nUsed++].Value = makeAny( i_nDependsOnEntry ); } + if( i_bAttachToDependency ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AttachToDependency" ) ); + aCtrl[nUsed++].Value = makeAny( i_bAttachToDependency ); + } } for( sal_Int32 i = 0; i < i_nAddProps; i++ ) aCtrl[ nUsed++ ] = i_pAddProps[i]; @@ -1010,7 +1017,7 @@ Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, *aHelpText.getArray() = i_rHelpText; } return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ), - NULL, NULL, -1, aAddProps, nUsed ); + NULL, NULL, -1, sal_False, aAddProps, nUsed ); } Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, @@ -1018,7 +1025,8 @@ Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rProperty, sal_Bool i_bValue, const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry + sal_Int32 i_nDependsOnEntry, + sal_Bool i_bAttachToDependency ) { Sequence< rtl::OUString > aHelpText; @@ -1030,7 +1038,7 @@ Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_bValue ); - return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, i_pDependsOnName, i_nDependsOnEntry ); + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, i_pDependsOnName, i_nDependsOnEntry, i_bAttachToDependency ); } Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, @@ -1040,7 +1048,8 @@ Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nValue, const rtl::OUString& i_rType, const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry + sal_Int32 i_nDependsOnEntry, + sal_Bool i_bAttachToDependency ) { PropertyValue aAddProps[2]; @@ -1051,7 +1060,7 @@ Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_nValue ); - return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, i_pDependsOnName, i_nDependsOnEntry, aAddProps, nUsed ); + return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, i_pDependsOnName, i_nDependsOnEntry, i_bAttachToDependency, aAddProps, nUsed ); } Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, @@ -1061,7 +1070,8 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nMinValue, sal_Int32 i_nMaxValue, const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry + sal_Int32 i_nDependsOnEntry, + sal_Bool i_bAttachToDependency ) { PropertyValue aAddProps[2]; @@ -1089,6 +1099,7 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, &aVal, i_pDependsOnName, i_nDependsOnEntry, + i_bAttachToDependency, aAddProps, nUsed ); } @@ -1097,7 +1108,8 @@ Any PrinterOptionsHelper::getEditControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rProperty, const rtl::OUString& i_rValue, const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry + sal_Int32 i_nDependsOnEntry, + sal_Bool i_bAttachToDependency ) { Sequence< rtl::OUString > aHelpText; @@ -1115,5 +1127,6 @@ Any PrinterOptionsHelper::getEditControlOpt( const rtl::OUString& i_rTitle, &aVal, i_pDependsOnName, i_nDependsOnEntry, + i_bAttachToDependency, 0, 0 ); } diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index bedfb6c9b533..ba1a89eb79da 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -31,6 +31,7 @@ #include "precompiled_vcl.hxx" #include "vcl/arrange.hxx" +#include "vcl/edit.hxx" #include "osl/diagnose.h" @@ -52,6 +53,22 @@ void WindowArranger::setParent( WindowArranger* i_pParent ) setParentWindow( m_pParentWindow ); } +sal_Int32 WindowArranger::Element::getExpandPriority() const +{ + sal_Int32 nPrio = m_nExpandPriority; + if( m_pChild ) + { + size_t nElements = m_pChild->countElements(); + for( size_t i = 0; i < nElements; i++ ) + { + sal_Int32 nCPrio = m_pChild->getExpandPriority( i ); + if( nCPrio > nPrio ) + nPrio = nCPrio; + } + } + return nPrio; +} + // ---------------------------------------- // vcl::RowOrColumn //----------------------------------------- @@ -75,6 +92,11 @@ Window* RowOrColumn::getWindow( size_t i_nIndex ) const return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL; } +sal_Int32 RowOrColumn::getExpandPriority( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].getExpandPriority() : 0; +} + Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const { Size aRet( 0, 0 ); @@ -124,19 +146,38 @@ Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const void RowOrColumn::distributeRowWidth( std::vector& io_rSizes, long /*i_nUsedWidth*/, long i_nExtraWidth ) { - if( ! io_rSizes.empty() ) + if( ! io_rSizes.empty() && io_rSizes.size() == m_aElements.size() ) { - // distribute extra space evenly among elements - size_t nElements = io_rSizes.size(); - long nDelta = i_nExtraWidth / nElements; + // find all elements with the highest expand priority + size_t nElements = m_aElements.size(); + std::vector< size_t > aIndices; + sal_Int32 nHighPrio = 0; for( size_t i = 0; i < nElements; i++ ) { - io_rSizes[i].Width() += nDelta; - i_nExtraWidth -= nDelta; + sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); + if( nCurPrio > nHighPrio ) + { + aIndices.clear(); + nHighPrio = nCurPrio; + } + if( nCurPrio == nHighPrio ) + aIndices.push_back( i ); + } + + // distribute extra space evenly among elements + nElements = aIndices.size(); + if( nElements > 0 ) // sanity check + { + long nDelta = i_nExtraWidth / nElements; + for( size_t i = 0; i < nElements; i++ ) + { + io_rSizes[ aIndices[i] ].Width() += nDelta; + i_nExtraWidth -= nDelta; + } + // add the last pixels to the last row element + if( i_nExtraWidth > 0 && nElements > 0 ) + io_rSizes[aIndices.back()].Width() += i_nExtraWidth; } - // add the last pixels to the last row element - if( i_nExtraWidth > 0 && nElements > 0 ) - io_rSizes.back().Width() += i_nExtraWidth; } } @@ -227,29 +268,29 @@ void RowOrColumn::setParentWindow( Window* i_pNewParent ) } } -void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nIndex ) +void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio, sal_Int32 i_nIndex ) { if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) - m_aElements.push_back( WindowArranger::Element( i_pWindow ) ); + m_aElements.push_back( WindowArranger::Element( i_pWindow, boost::shared_ptr(), i_nExpandPrio ) ); else { std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); while( i_nIndex-- ) ++it; - m_aElements.insert( it, WindowArranger::Element( i_pWindow ) ); + m_aElements.insert( it, WindowArranger::Element( i_pWindow, boost::shared_ptr(), i_nExpandPrio ) ); } } -void RowOrColumn::addChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nIndex ) +void RowOrColumn::addChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nExpandPrio, sal_Int32 i_nIndex ) { if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) - m_aElements.push_back( WindowArranger::Element( NULL, i_pChild ) ); + m_aElements.push_back( WindowArranger::Element( NULL, i_pChild, i_nExpandPrio ) ); else { std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); while( i_nIndex-- ) ++it; - m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild ) ); + m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild, i_nExpandPrio ) ); } } @@ -320,17 +361,19 @@ void Indenter::resize() m_aElement.m_pChild->setManagedArea( Rectangle( aPt, aSz ) ); } -void Indenter::setWindow( Window* i_pWindow ) +void Indenter::setWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio ) { OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0) || i_pWindow == 0 ); OSL_VERIFY( i_pWindow == 0 || i_pWindow->GetParent() == m_pParentWindow ); m_aElement.m_pElement = i_pWindow; + m_aElement.m_nExpandPriority = i_nExpandPrio; } -void Indenter::setChild( boost::shared_ptr const & i_pChild ) +void Indenter::setChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nExpandPrio ) { OSL_VERIFY( (m_aElement.m_pElement == 0 && m_aElement.m_pChild == 0 ) || i_pChild == 0 ); m_aElement.m_pChild = i_pChild; + m_aElement.m_nExpandPriority = i_nExpandPrio; } void Indenter::setParentWindow( Window* i_pNewParent ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 804711c62b50..08083364f801 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -347,6 +347,8 @@ void PrintDialog::setupOptionalUI() USHORT nOptPageId = 9, nCurSubGroup = 0; bool bOnJobPage = false; + std::multimap< rtl::OUString, vcl::RowOrColumn* > aPropertyToDependencyRowMap; + const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -363,6 +365,9 @@ void PrintDialog::setupOptionalUI() sal_Int64 nMinValue = 0, nMaxValue = 0; sal_Int32 nCurHelpText = 0; sal_Bool bOnJobPageValue = sal_False; + rtl::OUString aDependsOnName; + sal_Int32 nDependsOnValue = 0; + sal_Bool bUseDependencyRow = sal_False; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -397,26 +402,15 @@ void PrintDialog::setupOptionalUI() } else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) { - rtl::OUString aDepName; - rEntry.Value >>= aDepName; - std::map< rtl::OUString, Window* >::iterator it( maPropertyToWindowMap.find( aDepName ) ); - if( it != maPropertyToWindowMap.end() ) - { - Window* pWin = it->second; - // still on the same page ? - if( pWin->GetParent() == pCurParent ) - { - // is it a labeled window ? - if( dynamic_cast< ListBox* >(pWin) || - dynamic_cast< Edit* >(pWin) - ) - { - Window* pLabelWin = pWin->GetLabeledBy(); - if( dynamic_cast(pLabelWin) ) // sanity check - pWin = pLabelWin; - } - } - } + rEntry.Value >>= aDependsOnName; + } + else if( rEntry.Name.equalsAscii( "DependsOnEntry" ) ) + { + rEntry.Value >>= nDependsOnValue; + } + else if( rEntry.Name.equalsAscii( "AttachToDependency" ) ) + { + rEntry.Value >>= bUseDependencyRow; } else if( rEntry.Name.equalsAscii( "MinValue" ) ) { @@ -440,81 +434,95 @@ void PrintDialog::setupOptionalUI() } } - if( aCtrlType.equalsAscii( "Group" ) || - aCtrlType.equalsAscii( "Subgroup" ) || - aCtrlType.equalsAscii( "Radio" ) || - aCtrlType.equalsAscii( "List" ) || - aCtrlType.equalsAscii( "Range" ) || - aCtrlType.equalsAscii( "Edit" ) || - aCtrlType.equalsAscii( "Bool" ) ) + if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + { + // add new tab page + TabPage* pNewGroup = new TabPage( &maTabCtrl ); + maControls.push_front( pNewGroup ); + pCurParent = pNewGroup; + pNewGroup->SetText( aText ); + maTabCtrl.InsertPage( ++nOptPageId, aText ); + maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); + + // set help id + setSmartId( pNewGroup, "TabPage", nOptPageId ); + // set help text + setHelpText( pNewGroup, aHelpTexts, 0 ); + + // reset subgroup counter + nCurSubGroup = 0; + + aDynamicColumns.push_back( new vcl::RowOrColumn( NULL, true, nBorderWidth ) ); + pCurColumn = aDynamicColumns.back(); + pCurColumn->setParentWindow( pNewGroup ); + pCurColumn->setOuterBorder( nBorderWidth ); + } + else if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) { - if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + // change to job page or back if necessary + if( (bOnJobPage && ! bOnJobPageValue) || + (! bOnJobPage && bOnJobPageValue) ) { - // add new tab page - TabPage* pNewGroup = new TabPage( &maTabCtrl ); - maControls.push_front( pNewGroup ); - pCurParent = pNewGroup; - pNewGroup->SetText( aText ); - maTabCtrl.InsertPage( ++nOptPageId, aText ); - maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); + bOnJobPage = bOnJobPageValue; + if( bOnJobPage ) + { + pDynamicPageParent = pCurParent; // save current parent + pCurParent = &maJobPage; // set job page as current parent + } + else + { + pCurParent = pDynamicPageParent; // set current tab page as parent + } + } - // set help id - setSmartId( pNewGroup, "TabPage", nOptPageId ); - // set help text - setHelpText( pNewGroup, aHelpTexts, 0 ); + if( bOnJobPage ) + { + // create a new column in the PrintRange row + vcl::RowOrColumn* pNewColumn = new vcl::RowOrColumn( &aPrintRangeRow, true, nBorderWidth ); + aPrintRangeRow.addChild( pNewColumn ); + pCurColumn = pNewColumn; + } + else + pCurColumn = aDynamicColumns.back(); - // reset subgroup counter - nCurSubGroup = 0; + // create group FixedLine + FixedLine* pNewSub = new FixedLine( pCurParent ); + maControls.push_front( pNewSub ); + pNewSub->SetText( aText ); + pNewSub->Show(); - aDynamicColumns.push_back( new vcl::RowOrColumn( NULL, true, nBorderWidth ) ); - pCurColumn = aDynamicColumns.back(); - pCurColumn->setParentWindow( pNewGroup ); - pCurColumn->setOuterBorder( nBorderWidth ); - } + // set help id + setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); + // set help text + setHelpText( pNewSub, aHelpTexts, 0 ); - if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) + // add group to current column + pCurColumn->addWindow( pNewSub ); + } + else + { + vcl::RowOrColumn* pSaveCurColumn = pCurColumn; + + if( bUseDependencyRow && aDependsOnName.getLength() ) { - // change to job page or back if necessary - if( (bOnJobPage && ! bOnJobPageValue) || - (! bOnJobPage && bOnJobPageValue) ) + // find the correct dependency row (if any) + std::pair< std::multimap< rtl::OUString, vcl::RowOrColumn* >::iterator, + std::multimap< rtl::OUString, vcl::RowOrColumn* >::iterator > aDepRange; + aDepRange = aPropertyToDependencyRowMap.equal_range( aDependsOnName ); + if( aDepRange.first != aDepRange.second ) { - bOnJobPage = bOnJobPageValue; - if( bOnJobPage ) + while( nDependsOnValue && aDepRange.first != aDepRange.second ) { - pDynamicPageParent = pCurParent; // save current parent - pCurParent = &maJobPage; // set job page as current parent + nDependsOnValue--; + ++aDepRange.first; } - else + if( aDepRange.first != aPropertyToDependencyRowMap.end() ) { - pCurParent = pDynamicPageParent; // set current tab page as parent + pCurColumn = aDepRange.first->second; } } - - if( bOnJobPage ) - { - // create a new column in the PrintRange row - vcl::RowOrColumn* pNewColumn = new vcl::RowOrColumn( &aPrintRangeRow, true, nBorderWidth ); - aPrintRangeRow.addChild( pNewColumn ); - pCurColumn = pNewColumn; - } - else - pCurColumn = aDynamicColumns.back(); - - // create group FixedLine - FixedLine* pNewSub = new FixedLine( pCurParent ); - maControls.push_front( pNewSub ); - pNewSub->SetText( aText ); - pNewSub->Show(); - - // set help id - setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); - // set help text - setHelpText( pNewSub, aHelpTexts, 0 ); - - // add group to current column - pCurColumn->addWindow( pNewSub ); } - else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) + if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { // add a check box CheckBox* pNewBox = new CheckBox( pCurParent ); @@ -538,8 +546,12 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pNewBox, aHelpTexts, 0 ); + vcl::RowOrColumn* pDependencyRow = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pDependencyRow ); + aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pDependencyRow ) ); + // add checkbox to current column - pCurColumn->addWindow( pNewBox ); + pDependencyRow->addWindow( pNewBox ); } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -572,6 +584,10 @@ void PrintDialog::setupOptionalUI() pVal->Value >>= nSelectVal; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { + vcl::RowOrColumn* pDependencyRow = new vcl::RowOrColumn( pCurColumn, false ); + pRadioColumn->addChild( pDependencyRow ); + aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pDependencyRow ) ); + RadioButton* pBtn = new RadioButton( pCurParent, m == 0 ? WB_GROUP : 0 ); maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); @@ -588,7 +604,7 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pBtn, aHelpTexts, nCurHelpText++ ); // add the radio button to the column - pRadioColumn->addWindow( pBtn ); + pDependencyRow->addWindow( pBtn ); } } else if( ( aCtrlType.equalsAscii( "List" ) || @@ -596,13 +612,13 @@ void PrintDialog::setupOptionalUI() aCtrlType.equalsAscii( "Edit" ) ) && pCurParent ) { - vcl::RowOrColumn* pFieldColumn = pCurColumn; + // create a row in the current column + vcl::RowOrColumn* pFieldColumn = new vcl::RowOrColumn( pCurColumn, false ); + pCurColumn->addChild( pFieldColumn ); + aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pFieldColumn ) ); + if( aText.getLength() ) { - // create a row in the current column - pFieldColumn = new vcl::RowOrColumn( pCurColumn, false ); - pCurColumn->addChild( pFieldColumn ); - // add a FixedText: FixedText* pHeading = new FixedText( pCurParent, WB_VCENTER ); maControls.push_front( pHeading ); @@ -702,13 +718,15 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pField] = aPropertyName; // add to row - pFieldColumn->addWindow( pField ); + pFieldColumn->addWindow( pField, 2 ); } } - } - else - { - DBG_ERROR( "Unsupported UI option" ); + else + { + DBG_ERROR( "Unsupported UI option" ); + } + + pCurColumn = pSaveCurColumn; } } -- cgit From 9b32197487cc7993e021e4bd733685173cdae271 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 27 May 2009 18:53:40 +0000 Subject: print range changes for basic ide --- vcl/source/window/printdlg.cxx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 08083364f801..f4164b3a66a6 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -434,7 +434,8 @@ void PrintDialog::setupOptionalUI() } } - if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + if( aCtrlType.equalsAscii( "Group" ) || + ( ! pCurParent && ! (bOnJobPage || bOnJobPageValue) ) ) { // add new tab page TabPage* pNewGroup = new TabPage( &maTabCtrl ); @@ -457,7 +458,7 @@ void PrintDialog::setupOptionalUI() pCurColumn->setParentWindow( pNewGroup ); pCurColumn->setOuterBorder( nBorderWidth ); } - else if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) + else if( aCtrlType.equalsAscii( "Subgroup" ) && (pCurParent || bOnJobPageValue) ) { // change to job page or back if necessary if( (bOnJobPage && ! bOnJobPageValue) || -- cgit From 599de0cf57cc354fbe9ac9b2ec7c3cebabcc90be Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 28 May 2009 16:46:25 +0000 Subject: #i96402# SetDuplexMode --- vcl/aqua/inc/salprn.h | 2 - vcl/aqua/source/gdi/salprn.cxx | 11 +---- vcl/inc/vcl/jobset.h | 13 +++--- vcl/inc/vcl/print.hxx | 1 + vcl/inc/vcl/prntypes.hxx | 3 +- vcl/inc/vcl/salprn.hxx | 1 - vcl/inc/vcl/salptype.hxx | 6 ++- vcl/os2/inc/salprn.h | 1 - vcl/os2/source/gdi/salprn.cxx | 7 +--- vcl/source/gdi/jobset.cxx | 26 +++++++++++- vcl/source/gdi/print.cxx | 39 +++++++++++++++++- vcl/unx/headless/svpprn.cxx | 87 +++++++++++++++++++++++++++------------- vcl/unx/headless/svpprn.hxx | 1 - vcl/unx/inc/salprn.h | 1 - vcl/unx/source/gdi/salprnpsp.cxx | 87 +++++++++++++++++++++++++++------------- vcl/win/inc/salprn.h | 1 - vcl/win/source/gdi/salprn.cxx | 68 ++++++++++++++++--------------- 17 files changed, 234 insertions(+), 121 deletions(-) diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index 0ab4c02ab264..3a486d901ddc 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -96,8 +96,6 @@ class AquaSalInfoPrinter : public SalInfoPrinter virtual String GetPaperBinName( const ImplJobSetup* i_pSetupData, ULONG i_nPaperBin ); virtual void InitPaperFormats( const ImplJobSetup* i_pSetupData ); virtual int GetLandscapeAngle( const ImplJobSetup* i_pSetupData ); - virtual DuplexMode GetDuplexMode( const ImplJobSetup* i_pSetupData ); - // the artificial separation between InfoPrinter and Printer // is not really useful for us diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index b109f2c19dcd..de7e5200b8af 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -435,6 +435,8 @@ ULONG AquaSalInfoPrinter::GetCapabilities( const ImplJobSetup* i_pSetupData, USH return 0; case PRINTER_CAPABILITIES_SETORIENTATION: return 1; + case PRINTER_CAPABILITIES_SETDUPLEX: + return 0; case PRINTER_CAPABILITIES_SETPAPERBIN: return 0; case PRINTER_CAPABILITIES_SETPAPERSIZE: @@ -811,13 +813,4 @@ int AquaSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* i_pSetupData ) return 900; } -//////////////////////////// -////// IMPLEMENT US ///// -//////////////////////////// - -DuplexMode AquaSalInfoPrinter::GetDuplexMode( const ImplJobSetup* i_pSetupData ) -{ - return DUPLEX_UNKNOWN; -} - diff --git a/vcl/inc/vcl/jobset.h b/vcl/inc/vcl/jobset.h index 5d08319a7e6c..fd15d0c076da 100644 --- a/vcl/inc/vcl/jobset.h +++ b/vcl/inc/vcl/jobset.h @@ -60,12 +60,13 @@ struct ImplJobSetup String maPrinterName; // Printer-Name String maDriver; // Driver-Name Orientation meOrientation; // Orientation - USHORT mnPaperBin; // Papierschacht - Paper mePaperFormat; // Papierformat - long mnPaperWidth; // Papierbreite in 100tel mm - long mnPaperHeight; // Papierhoehe in 100tel mm - ULONG mnDriverDataLen; // Laenge der systemabhaengigen Daten - BYTE* mpDriverData; // Systemabhaengige Daten die als Byte-Block rausgeschrieben werden + DuplexMode meDuplexMode; // Duplex + USHORT mnPaperBin; // paper bin / in tray + Paper mePaperFormat; // paper format + long mnPaperWidth; // paper width (100th mm) + long mnPaperHeight; // paper height (100th mm) + ULONG mnDriverDataLen; // length of system specific data + BYTE* mpDriverData; // system specific data (will be streamed a byte block) ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash > maValueMap; ImplJobSetup(); diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 774a74572d59..83e4e984a1d3 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -335,6 +335,7 @@ public: BOOL SetOrientation( Orientation eOrient ); Orientation GetOrientation() const; DuplexMode GetDuplexMode() const; + BOOL SetDuplexMode( DuplexMode ); // returns the angle that a landscape page will be turned counterclockwise // wrt to portrait. The return value may be only valid for // the current paper diff --git a/vcl/inc/vcl/prntypes.hxx b/vcl/inc/vcl/prntypes.hxx index 84ef320de20e..8a05f95f8fc1 100644 --- a/vcl/inc/vcl/prntypes.hxx +++ b/vcl/inc/vcl/prntypes.hxx @@ -38,7 +38,7 @@ // - Duplex Mode - // --------------- -enum DuplexMode { DUPLEX_UNKNOWN, DUPLEX_OFF, DUPLEX_ON }; +enum DuplexMode { DUPLEX_UNKNOWN, DUPLEX_OFF, DUPLEX_LONGEDGE, DUPLEX_SHORTEDGE }; // --------------- // - Orientation - @@ -119,5 +119,6 @@ struct PaperInfo #define PRINTER_CAPABILITIES_FAX ((USHORT)8) #define PRINTER_CAPABILITIES_PDF ((USHORT)9) #define PRINTER_CAPABILITIES_EXTERNALDIALOG ((USHORT)10) +#define PRINTER_CAPABILITIES_SETDUPLEX ((USHORT)11) #endif // _SV_PRNTYPES_HXX diff --git a/vcl/inc/vcl/salprn.hxx b/vcl/inc/vcl/salprn.hxx index d76040f8cb8b..923b3a750e36 100644 --- a/vcl/inc/vcl/salprn.hxx +++ b/vcl/inc/vcl/salprn.hxx @@ -101,7 +101,6 @@ public: virtual void InitPaperFormats( const ImplJobSetup* pSetupData ) = 0; // returns angle that a landscape page will be turned counterclockwise wrt to portrait virtual int GetLandscapeAngle( const ImplJobSetup* pSetupData ) = 0; - virtual DuplexMode GetDuplexMode( const ImplJobSetup* pSetupData ) = 0; }; // -------------- diff --git a/vcl/inc/vcl/salptype.hxx b/vcl/inc/vcl/salptype.hxx index 7f1c82079f38..bc9883757432 100644 --- a/vcl/inc/vcl/salptype.hxx +++ b/vcl/inc/vcl/salptype.hxx @@ -40,7 +40,11 @@ #define SAL_JOBSET_ORIENTATION ((ULONG)0x00000001) #define SAL_JOBSET_PAPERBIN ((ULONG)0x00000002) #define SAL_JOBSET_PAPERSIZE ((ULONG)0x00000004) -#define SAL_JOBSET_ALL (SAL_JOBSET_ORIENTATION | SAL_JOBSET_PAPERBIN | SAL_JOBSET_PAPERSIZE) +#define SAL_JOBSET_DUPLEXMODE ((ULONG)0x00000008) +#define SAL_JOBSET_ALL (SAL_JOBSET_ORIENTATION |\ + SAL_JOBSET_PAPERBIN |\ + SAL_JOBSET_PAPERSIZE |\ + SAL_JOBSET_DUPLEXMODE) // ------------------- // - SalPrinterError - diff --git a/vcl/os2/inc/salprn.h b/vcl/os2/inc/salprn.h index 25ecfe87ed89..bddb29f61442 100644 --- a/vcl/os2/inc/salprn.h +++ b/vcl/os2/inc/salprn.h @@ -83,7 +83,6 @@ public: virtual String GetPaperBinName( const ImplJobSetup* pSetupData, ULONG nPaperBin ); virtual void InitPaperFormats( const ImplJobSetup* pSetupData ); virtual int GetLandscapeAngle( const ImplJobSetup* pSetupData ); - virtual DuplexMode GetDuplexMode( const ImplJobSetup* pSetupData ); }; // ------------------ diff --git a/vcl/os2/source/gdi/salprn.cxx b/vcl/os2/source/gdi/salprn.cxx index 0c254e2f6e62..b8207ed317f2 100644 --- a/vcl/os2/source/gdi/salprn.cxx +++ b/vcl/os2/source/gdi/salprn.cxx @@ -1831,9 +1831,4 @@ int Os2SalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* pSetupData ) printf("Os2SalInfoPrinter::GetLandscapeAngle\n"); return 0; } -DuplexMode Os2SalInfoPrinter::GetDuplexMode( const ImplJobSetup* pSetupData ) -{ - DuplexMode nRet = DUPLEX_UNKNOWN; - printf("Os2SalInfoPrinter::GetDuplexMode\n"); - return nRet; -} + diff --git a/vcl/source/gdi/jobset.cxx b/vcl/source/gdi/jobset.cxx index 686d33593466..4823a5492ded 100644 --- a/vcl/source/gdi/jobset.cxx +++ b/vcl/source/gdi/jobset.cxx @@ -73,6 +73,7 @@ ImplJobSetup::ImplJobSetup() mnRefCount = 1; mnSystem = 0; meOrientation = ORIENTATION_PORTRAIT; + meDuplexMode = DUPLEX_UNKNOWN; mnPaperBin = 0; mePaperFormat = PAPER_USER; mnPaperWidth = 0; @@ -90,6 +91,7 @@ ImplJobSetup::ImplJobSetup( const ImplJobSetup& rJobSetup ) : mnRefCount = 1; mnSystem = rJobSetup.mnSystem; meOrientation = rJobSetup.meOrientation; + meDuplexMode = rJobSetup.meDuplexMode; mnPaperBin = rJobSetup.mnPaperBin; mePaperFormat = rJobSetup.mePaperFormat; mnPaperWidth = rJobSetup.mnPaperWidth; @@ -277,6 +279,7 @@ BOOL JobSetup::operator==( const JobSetup& rJobSetup ) const (pData1->maPrinterName == pData2->maPrinterName) && (pData1->maDriver == pData2->maDriver) && (pData1->meOrientation == pData2->meOrientation) && + (pData1->meDuplexMode == pData2->meDuplexMode) && (pData1->mnPaperBin == pData2->mnPaperBin) && (pData1->mePaperFormat == pData2->mePaperFormat) && (pData1->mnPaperWidth == pData2->mnPaperWidth) && @@ -337,6 +340,7 @@ SvStream& operator>>( SvStream& rIStream, JobSetup& rJobSetup ) pJobData->mnSystem = SVBT16ToShort( pOldJobData->nSystem ); pJobData->mnDriverDataLen = SVBT32ToUInt32( pOldJobData->nDriverDataLen ); pJobData->meOrientation = (Orientation)SVBT16ToShort( pOldJobData->nOrientation ); + pJobData->meDuplexMode = DUPLEX_UNKNOWN; pJobData->mnPaperBin = SVBT16ToShort( pOldJobData->nPaperBin ); pJobData->mePaperFormat = (Paper)SVBT16ToShort( pOldJobData->nPaperFormat ); pJobData->mnPaperWidth = (long)SVBT32ToUInt32( pOldJobData->nPaperWidth ); @@ -355,7 +359,19 @@ SvStream& operator>>( SvStream& rIStream, JobSetup& rJobSetup ) String aKey, aValue; rIStream.ReadByteString( aKey, RTL_TEXTENCODING_UTF8 ); rIStream.ReadByteString( aValue, RTL_TEXTENCODING_UTF8 ); - pJobData->maValueMap[ aKey ] = aValue; + if( aKey.EqualsAscii( "COMPAT_DUPLEX_MODE" ) ) + { + if( aValue.EqualsAscii( "DUPLEX_UNKNOWN" ) ) + pJobData->meDuplexMode = DUPLEX_UNKNOWN; + else if( aValue.EqualsAscii( "DUPLEX_OFF" ) ) + pJobData->meDuplexMode = DUPLEX_OFF; + else if( aValue.EqualsAscii( "DUPLEX_SHORTEDGE" ) ) + pJobData->meDuplexMode = DUPLEX_SHORTEDGE; + else if( aValue.EqualsAscii( "DUPLEX_LONGEDGE" ) ) + pJobData->meDuplexMode = DUPLEX_LONGEDGE; + } + else + pJobData->maValueMap[ aKey ] = aValue; } DBG_ASSERT( rIStream.Tell() == nFirstPos+nLen, "corrupted job setup" ); // ensure correct stream position @@ -421,6 +437,14 @@ SvStream& operator<<( SvStream& rOStream, const JobSetup& rJobSetup ) rOStream.WriteByteString( it->first, RTL_TEXTENCODING_UTF8 ); rOStream.WriteByteString( it->second, RTL_TEXTENCODING_UTF8 ); } + rOStream.WriteByteString( "COMPAT_DUPLEX_MODE" ) ; + switch( pJobData->meDuplexMode ) + { + case DUPLEX_UNKNOWN: rOStream.WriteByteString( "DUPLEX_UNKNOWN" );break; + case DUPLEX_OFF: rOStream.WriteByteString( "DUPLEX_OFF" );break; + case DUPLEX_SHORTEDGE: rOStream.WriteByteString( "DUPLEX_SHORTEDGE" );break; + case DUPLEX_LONGEDGE: rOStream.WriteByteString( "DUPLEX_LONGEDGE" );break; + } nLen = sal::static_int_cast(rOStream.Tell() - nPos); rOStream.Seek( nPos ); rOStream << nLen; diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index f3a89f6b6b23..a74038c4eaaa 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -1200,7 +1200,44 @@ BOOL Printer::SetPaperFromInfo( const vcl::PaperInfo& rInfo ) DuplexMode Printer::GetDuplexMode() const { - return mpInfoPrinter ? mpInfoPrinter->GetDuplexMode( maJobSetup.ImplGetConstData() ) : DUPLEX_UNKNOWN; + return maJobSetup.ImplGetConstData()->meDuplexMode; +} + +// ----------------------------------------------------------------------- + +BOOL Printer::SetDuplexMode( DuplexMode eDuplex ) +{ + if ( mbInPrintPage ) + return FALSE; + + if ( maJobSetup.ImplGetConstData()->meDuplexMode != eDuplex ) + { + JobSetup aJobSetup = maJobSetup; + ImplJobSetup* pSetupData = aJobSetup.ImplGetData(); + pSetupData->meDuplexMode = eDuplex; + + if ( IsDisplayPrinter() ) + { + mbNewJobSetup = TRUE; + maJobSetup = aJobSetup; + return TRUE; + } + + ImplReleaseGraphics(); + if ( mpInfoPrinter->SetData( SAL_JOBSET_DUPLEXMODE, pSetupData ) ) + { + ImplUpdateJobSetupPaper( aJobSetup ); + mbNewJobSetup = TRUE; + maJobSetup = aJobSetup; + ImplUpdatePageData(); + ImplUpdateFontList(); + return TRUE; + } + else + return FALSE; + } + + return TRUE; } // ----------------------------------------------------------------------- diff --git a/vcl/unx/headless/svpprn.cxx b/vcl/unx/headless/svpprn.cxx index e9d726464921..880f218cccb4 100644 --- a/vcl/unx/headless/svpprn.cxx +++ b/vcl/unx/headless/svpprn.cxx @@ -154,6 +154,32 @@ static void copyJobDataToJobSetup( ImplJobSetup* pJobSetup, JobData& rData ) pJobSetup->mnPaperBin = 0xffff; } + // copy duplex + pKey = NULL; + pValue = NULL; + + pJobSetup->meDuplexMode = DUPLEX_UNKNOWN; + if( rData.m_pParser ) + pKey = rData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); + if( pKey ) + pValue = rData.m_aContext.getValue( pKey ); + if( pKey && pValue ) + { + if( pValue->m_aOption.EqualsIgnoreCaseAscii( "None" ) || + pValue->m_aOption.EqualsIgnoreCaseAscii( "Simplex", 0, 7 ) + ) + { + pJobSetup->meDuplexMode = DUPLEX_OFF; + } + else if( pValue->m_aOption.EqualsIgnoreCaseAscii( "DuplexNoTumble" ) ) + { + pJobSetup->meDuplexMode = DUPLEX_LONGEDGE; + } + else if( pValue->m_aOption.EqualsIgnoreCaseAscii( "DuplexTumble" ) ) + { + pJobSetup->meDuplexMode = DUPLEX_SHORTEDGE; + } + } // copy the whole context if( pJobSetup->mpDriverData ) @@ -491,34 +517,6 @@ void PspSalInfoPrinter::InitPaperFormats( const ImplJobSetup* ) // ----------------------------------------------------------------------- -DuplexMode PspSalInfoPrinter::GetDuplexMode( const ImplJobSetup* pJobSetup ) -{ - DuplexMode aRet = DUPLEX_UNKNOWN; - PrinterInfo aInfo( PrinterInfoManager::get().getPrinterInfo( pJobSetup->maPrinterName ) ); - if ( pJobSetup->mpDriverData ) - JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, aInfo ); - if( aInfo.m_pParser ) - { - const PPDKey * pKey = aInfo.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); - if( pKey ) - { - const PPDValue* pVal = aInfo.m_aContext.getValue( pKey ); - if( pVal && ( - pVal->m_aOption.EqualsIgnoreCaseAscii( "None" ) || - pVal->m_aOption.EqualsIgnoreCaseAscii( "Simplex", 0, 7 ) - ) ) - { - aRet = DUPLEX_OFF; - } - else - aRet = DUPLEX_ON; - } - } - return aRet; -} - -// ----------------------------------------------------------------------- - int PspSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* ) { return 900; @@ -660,6 +658,37 @@ BOOL PspSalInfoPrinter::SetData( if( nSetDataFlags & SAL_JOBSET_ORIENTATION ) aData.m_eOrientation = pJobSetup->meOrientation == ORIENTATION_LANDSCAPE ? orientation::Landscape : orientation::Portrait; + // merge duplex if necessary + if( nSetDataFlags & SAL_JOBSET_DUPLEXMODE ) + { + pKey = aData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); + if( pKey ) + { + pValue = NULL; + switch( pJobSetup->meDuplexMode ) + { + case DUPLEX_OFF: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "None" ) ) ); + if( pValue == NULL ) + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "SimplexNoTumble" ) ) ); + break; + case DUPLEX_SHORTEDGE: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "DuplexTumble" ) ) ); + break; + case DUPLEX_LONGEDGE: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "DuplexNoTumble" ) ) ); + break; + case DUPLEX_UNKNOWN: + default: + pValue = 0; + break; + } + if( ! pValue ) + pValue = pKey->getDefaultValue(); + aData.m_aContext.setValue( pKey, pValue ); + } + } + m_aJobData = aData; copyJobDataToJobSetup( pJobSetup, aData ); return TRUE; @@ -764,6 +793,8 @@ ULONG PspSalInfoPrinter::GetCapabilities( const ImplJobSetup* pJobSetup, USHORT return 0; case PRINTER_CAPABILITIES_SETORIENTATION: return 1; + case PRINTER_CAPABILITIES_SETDUPLEX: + return 1; case PRINTER_CAPABILITIES_SETPAPERBIN: return 1; case PRINTER_CAPABILITIES_SETPAPERSIZE: diff --git a/vcl/unx/headless/svpprn.hxx b/vcl/unx/headless/svpprn.hxx index c2d85c054fce..dd1c0cb1d88e 100644 --- a/vcl/unx/headless/svpprn.hxx +++ b/vcl/unx/headless/svpprn.hxx @@ -63,7 +63,6 @@ public: virtual String GetPaperBinName( const ImplJobSetup* pSetupData, ULONG nPaperBin ); virtual void InitPaperFormats( const ImplJobSetup* pSetupData ); virtual int GetLandscapeAngle( const ImplJobSetup* pSetupData ); - virtual DuplexMode GetDuplexMode( const ImplJobSetup* pSetupData ); }; class PspSalPrinter : public SalPrinter diff --git a/vcl/unx/inc/salprn.h b/vcl/unx/inc/salprn.h index 452fa5a89387..7d46d24ce94c 100644 --- a/vcl/unx/inc/salprn.h +++ b/vcl/unx/inc/salprn.h @@ -63,7 +63,6 @@ public: virtual String GetPaperBinName( const ImplJobSetup* pSetupData, ULONG nPaperBin ); virtual void InitPaperFormats( const ImplJobSetup* pSetupData ); virtual int GetLandscapeAngle( const ImplJobSetup* pSetupData ); - virtual DuplexMode GetDuplexMode( const ImplJobSetup* pSetupData ); }; class PspSalPrinter : public SalPrinter diff --git a/vcl/unx/source/gdi/salprnpsp.cxx b/vcl/unx/source/gdi/salprnpsp.cxx index b3fdfaef56ce..f3da8cb3855f 100644 --- a/vcl/unx/source/gdi/salprnpsp.cxx +++ b/vcl/unx/source/gdi/salprnpsp.cxx @@ -207,6 +207,32 @@ static void copyJobDataToJobSetup( ImplJobSetup* pJobSetup, JobData& rData ) pJobSetup->mnPaperBin = 0; } + // copy duplex + pKey = NULL; + pValue = NULL; + + pJobSetup->meDuplexMode = DUPLEX_UNKNOWN; + if( rData.m_pParser ) + pKey = rData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); + if( pKey ) + pValue = rData.m_aContext.getValue( pKey ); + if( pKey && pValue ) + { + if( pValue->m_aOption.EqualsIgnoreCaseAscii( "None" ) || + pValue->m_aOption.EqualsIgnoreCaseAscii( "Simplex", 0, 7 ) + ) + { + pJobSetup->meDuplexMode = DUPLEX_OFF; + } + else if( pValue->m_aOption.EqualsIgnoreCaseAscii( "DuplexNoTumble" ) ) + { + pJobSetup->meDuplexMode = DUPLEX_LONGEDGE; + } + else if( pValue->m_aOption.EqualsIgnoreCaseAscii( "DuplexTumble" ) ) + { + pJobSetup->meDuplexMode = DUPLEX_SHORTEDGE; + } + } // copy the whole context if( pJobSetup->mpDriverData ) @@ -560,34 +586,6 @@ void PspSalInfoPrinter::InitPaperFormats( const ImplJobSetup* ) // ----------------------------------------------------------------------- -DuplexMode PspSalInfoPrinter::GetDuplexMode( const ImplJobSetup* pJobSetup ) -{ - DuplexMode aRet = DUPLEX_UNKNOWN; - PrinterInfo aInfo( PrinterInfoManager::get().getPrinterInfo( pJobSetup->maPrinterName ) ); - if ( pJobSetup->mpDriverData ) - JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, aInfo ); - if( aInfo.m_pParser ) - { - const PPDKey * pKey = aInfo.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); - if( pKey ) - { - const PPDValue* pVal = aInfo.m_aContext.getValue( pKey ); - if( pVal && ( - pVal->m_aOption.EqualsIgnoreCaseAscii( "None" ) || - pVal->m_aOption.EqualsIgnoreCaseAscii( "Simplex", 0, 7 ) - ) ) - { - aRet = DUPLEX_OFF; - } - else - aRet = DUPLEX_ON; - } - } - return aRet; -} - -// ----------------------------------------------------------------------- - int PspSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* ) { return 900; @@ -762,6 +760,37 @@ BOOL PspSalInfoPrinter::SetData( if( nSetDataFlags & SAL_JOBSET_ORIENTATION ) aData.m_eOrientation = pJobSetup->meOrientation == ORIENTATION_LANDSCAPE ? orientation::Landscape : orientation::Portrait; + // merge duplex if necessary + if( nSetDataFlags & SAL_JOBSET_DUPLEXMODE ) + { + pKey = aData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) ); + if( pKey ) + { + pValue = NULL; + switch( pJobSetup->meDuplexMode ) + { + case DUPLEX_OFF: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "None" ) ) ); + if( pValue == NULL ) + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "SimplexNoTumble" ) ) ); + break; + case DUPLEX_SHORTEDGE: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "DuplexTumble" ) ) ); + break; + case DUPLEX_LONGEDGE: + pValue = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "DuplexNoTumble" ) ) ); + break; + case DUPLEX_UNKNOWN: + default: + pValue = 0; + break; + } + if( ! pValue ) + pValue = pKey->getDefaultValue(); + aData.m_aContext.setValue( pKey, pValue ); + } + } + m_aJobData = aData; copyJobDataToJobSetup( pJobSetup, aData ); return TRUE; @@ -866,6 +895,8 @@ ULONG PspSalInfoPrinter::GetCapabilities( const ImplJobSetup* pJobSetup, USHORT return 0; case PRINTER_CAPABILITIES_SETORIENTATION: return 1; + case PRINTER_CAPABILITIES_SETDUPLEX: + return 1; case PRINTER_CAPABILITIES_SETPAPERBIN: return 1; case PRINTER_CAPABILITIES_SETPAPERSIZE: diff --git a/vcl/win/inc/salprn.h b/vcl/win/inc/salprn.h index 58d721fd043a..09473cf518e0 100644 --- a/vcl/win/inc/salprn.h +++ b/vcl/win/inc/salprn.h @@ -88,7 +88,6 @@ public: virtual String GetPaperBinName( const ImplJobSetup* pSetupData, ULONG nPaperBin ); virtual void InitPaperFormats( const ImplJobSetup* pSetupData ); virtual int GetLandscapeAngle( const ImplJobSetup* pSetupData ); - virtual DuplexMode GetDuplexMode( const ImplJobSetup* pSetupData ); }; // ----------------- diff --git a/vcl/win/source/gdi/salprn.cxx b/vcl/win/source/gdi/salprn.cxx index cc359da97cd9..f18c888b067c 100644 --- a/vcl/win/source/gdi/salprn.cxx +++ b/vcl/win/source/gdi/salprn.cxx @@ -923,6 +923,21 @@ static void ImplDevModeToJobSetup( WinSalInfoPrinter* pPrinter, ImplJobSetup* pS break; } } + + if( nFlags & SAL_JOBSET_DUPLEXMODE ) + { + DuplexMode eDuplex = DUPLEX_UNKNOWN; + if( (CHOOSE_DEVMODE(dmFields) & DM_DUPLEX) ) + { + if( CHOOSE_DEVMODE(dmDuplex) == DMDUP_SIMPLEX ) + eDuplex = DUPLEX_OFF; + else if( CHOOSE_DEVMODE(dmDuplex) == DMDUP_VERTICAL ) + eDuplex = DUPLEX_LONGEDGE; + else if( CHOOSE_DEVMODE(dmDuplex) == DMDUP_HORIZONTAL ) + eDuplex = DUPLEX_SHORTEDGE; + } + pSetupData->meDuplexMode = eDuplex; + } } // ----------------------------------------------------------------------- @@ -1075,6 +1090,26 @@ static void ImplJobSetupToDevMode( WinSalInfoPrinter* pPrinter, ImplJobSetup* pS } } } + if( (nFlags & SAL_JOBSET_DUPLEXMODE) ) + { + switch( pSetupData->meDuplexMode ) + { + case DUPLEX_OFF: + CHOOSE_DEVMODE(dmFields) |= DM_DUPLEX; + CHOOSE_DEVMODE(dmDuplex) = DMDUP_SIMPLEX; + break; + case DUPLEX_SHORTEDGE: + CHOOSE_DEVMODE(dmFields) |= DM_DUPLEX; + CHOOSE_DEVMODE(dmDuplex) = DMDUP_HORIZONTAL; + break; + case DUPLEX_LONGEDGE: + CHOOSE_DEVMODE(dmFields) |= DM_DUPLEX; + CHOOSE_DEVMODE(dmDuplex) = DMDUP_VERTICAL; + break; + case DUPLEX_UNKNOWN: + break; + } + } } // ----------------------------------------------------------------------- @@ -1316,39 +1351,6 @@ void WinSalInfoPrinter::InitPaperFormats( const ImplJobSetup* pSetupData ) // ----------------------------------------------------------------------- -DuplexMode WinSalInfoPrinter::GetDuplexMode( const ImplJobSetup* pSetupData ) -{ - DuplexMode nRet = DUPLEX_UNKNOWN; - if ( pSetupData &&pSetupData->mpDriverData ) - { - if( aSalShlData.mbWPrinter ) - { - DEVMODEW* pDevMode = SAL_DEVMODE_W( pSetupData ); - if ( pDevMode && (pDevMode->dmFields & DM_DUPLEX )) - { - if ( pDevMode->dmDuplex == DMDUP_SIMPLEX ) - nRet = DUPLEX_OFF; - else - nRet = DUPLEX_ON; - } - } - else - { - DEVMODEA* pDevMode = SAL_DEVMODE_A( pSetupData ); - if ( pDevMode && (pDevMode->dmFields & DM_DUPLEX )) - { - if ( pDevMode->dmDuplex == DMDUP_SIMPLEX ) - nRet = DUPLEX_OFF; - else - nRet = DUPLEX_ON; - } - } - } - return nRet; -} - -// ----------------------------------------------------------------------- - int WinSalInfoPrinter::GetLandscapeAngle( const ImplJobSetup* pSetupData ) { int nRet = ImplDeviceCaps( this, DC_ORIENTATION, NULL, pSetupData ); -- cgit From efea6413054936f812fb0bceeca97ed8e199aa6d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 29 May 2009 14:45:00 +0000 Subject: filter out group for internal dialog --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index ed16df90af80..5499a5e7cc96 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -300,6 +300,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSRect aViewFrame = { { 0, 0 }, {400, 400 } }; NSSize aMaxTabSize = { 0, 0 }; NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aViewFrame]; + sal_Bool bIgnoreSubgroup = sal_False; for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -312,6 +313,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rtl::OUString aText; rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; + sal_Bool bIgnore = sal_False; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -341,6 +343,10 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rEntry.Value >>= bValue; bEnabled = bValue; } + else if( rEntry.Name.equalsAscii( "InternalUIOnly" ) ) + { + rEntry.Value >>= bIgnore; + } } if( aCtrlType.equalsAscii( "Group" ) || @@ -374,6 +380,10 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) { + bIgnoreSubgroup = bIgnore; + if( bIgnore ) + continue; + NSString* pText = CreateNSString( aText ); NSRect aTextRect = { { 0, 0 }, { 300, 15 } }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; @@ -398,6 +408,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // cleanup [pText release]; } + else if( bIgnoreSubgroup || bIgnore ) + continue; else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { NSString* pText = CreateNSString( aText ); @@ -480,6 +492,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { NSCell* pCell = [pCells objectAtIndex: m]; + filterAccelerator( aChoices[m] ); NSString* pTitle = CreateNSString( aChoices[m] ); [pCell setTitle: pTitle]; // connect target and action -- cgit From 91975f770557199dd1760ba024bff68e271749fd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 29 May 2009 14:58:05 +0000 Subject: correct restarting --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 1 - vcl/aqua/source/gdi/salprn.cxx | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 5499a5e7cc96..7c6fa970b316 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -517,7 +517,6 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // update nCurY nCurY = aRadioRect.origin.y - 5; - [pProto release]; } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index de7e5200b8af..3d86e0b6f0ad 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -607,7 +607,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, mnCurPageRangeStart += mnCurPageRangeCount; mnCurPageRangeCount = 1; - } while( bNeedRestart && mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); + } while( bNeedRestart || mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); // inform applictation that it can release its data // this is awkward, but the XRenderable interface has no method for this, -- cgit From 8db120c45b673dbfee37f8731437800425517485 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 2 Jun 2009 11:37:36 +0000 Subject: #i92516# persistency for print dialog --- vcl/inc/vcl/configsettings.hxx | 3 +- vcl/inc/vcl/prndlg.hxx | 8 +++ vcl/source/window/printdlg.cxx | 155 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 156 insertions(+), 10 deletions(-) diff --git a/vcl/inc/vcl/configsettings.hxx b/vcl/inc/vcl/configsettings.hxx index aee684a84ca4..211ea3f0892b 100644 --- a/vcl/inc/vcl/configsettings.hxx +++ b/vcl/inc/vcl/configsettings.hxx @@ -54,7 +54,6 @@ namespace vcl std::hash_map< rtl::OUString, SmallOUStrMap, rtl::OUStringHash > m_aSettings; virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString >& rPropertyNames ); - virtual void Commit(); void getValues(); SettingsConfigItem(); @@ -65,6 +64,8 @@ namespace vcl const rtl::OUString& getValue( const rtl::OUString& rGroup, const rtl::OUString& rKey ) const; void setValue( const rtl::OUString& rGroup, const rtl::OUString& rKey, const rtl::OUString& rValue ); + + virtual void Commit(); }; //........................................................................ diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 408ec46b2aff..4e7302f112c0 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -91,6 +91,9 @@ namespace vcl PrinterTabPage( Window*, const ResId& ); virtual ~PrinterTabPage(); + + void readFromSettings(); + void storeToSettings(); }; class JobTabPage : public TabPage @@ -112,6 +115,9 @@ namespace vcl JobTabPage( Window*, const ResId& ); virtual ~JobTabPage(); + + void readFromSettings(); + void storeToSettings(); }; OKButton maOKButton; @@ -150,6 +156,8 @@ namespace vcl void checkControlDependencies(); void checkOptionalControlDependencies(); void setupOptionalUI(); + void readFromSettings(); + void storeToSettings(); com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; virtual void Resize(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index f4164b3a66a6..fea99791c113 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -41,6 +41,7 @@ #include "vcl/status.hxx" #include "vcl/decoview.hxx" #include "vcl/arrange.hxx" +#include "vcl/configsettings.hxx" #include "rtl/ustrbuf.hxx" @@ -141,6 +142,43 @@ PrintDialog::PrinterTabPage::~PrinterTabPage() { } +void PrintDialog::PrinterTabPage::readFromSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + rtl::OUString aValue; + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ) ); + sal_Int32 nVal = aValue.toInt32(); + maNupRowsEdt.SetValue( sal_Int64( nVal > 1 ? nVal : 1) ); + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ) ); + nVal = aValue.toInt32(); + maNupColEdt.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ) ); + if( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ) + maNupPortrait.Check(); + else + maNupLandscape.Check(); +} + +void PrintDialog::PrinterTabPage::storeToSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ), + maNupRowsEdt.GetText() ); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ), + maNupColEdt.GetText() ); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ), + rtl::OUString::createFromAscii( maNupPortrait.IsChecked() ? "true" : "false" ) ); +} + PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) @@ -169,6 +207,39 @@ PrintDialog::JobTabPage::~JobTabPage() { } +void PrintDialog::JobTabPage::readFromSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + rtl::OUString aValue; + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); + maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Copies" ) ) ); + sal_Int32 nVal = aValue.toInt32(); + maCopyCountField.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); + maCollateBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); +} + +void PrintDialog::JobTabPage::storeToSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ), + rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Copies" ) ), + maCopyCountField.GetText() ); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), + rtl::OUString::createFromAscii( maCollateBox.IsChecked() ? "true" : "false" ) ); +} + PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rListener ) : ModalDialog( i_pParent, VclResId( SV_DLG_PRINT ) ) , maOKButton( this, VclResId( SV_PRINT_OK ) ) @@ -220,10 +291,23 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); + // fall back to last printer + SettingsConfigItem* pItem = SettingsConfigItem::get(); + String aValue( pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LastPrinter" ) ) ) ); + if( maPrinterPage.maPrinters.GetEntryPos( aValue ) != LISTBOX_ENTRY_NOTFOUND ) + { + maPrinterPage.maPrinters.SelectEntry( aValue ); + maJobPage.maPrinters.SelectEntry( aValue ); + maPListener->setPrinter( boost::shared_ptr( new Printer( aValue ) ) ); + } + else + { + // fall back to default printer + maPrinterPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); + maJobPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); + maPListener->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); + } } // update the text fields for the printer updatePrinterText(); @@ -249,6 +333,10 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr 1 + maCancelButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + #endif maJobPage.maCollateBox.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maPrinterPage.maSetupButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maPrinterPage.maNupPortrait.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); @@ -268,6 +356,9 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LastPage" ) ) ); + USHORT nCount = maTabCtrl.GetPageCount(); + for( USHORT i = 0; i < nCount; i++ ) + { + USHORT nPageId = maTabCtrl.GetPageId( i ); + if( aValue.equals( maTabCtrl.GetPageText( nPageId ) ) ) + { + maTabCtrl.SelectTabPage( nPageId ); + break; + } + } +} + +void PrintDialog::storeToSettings() +{ + maJobPage.storeToSettings(); + maPrinterPage.storeToSettings(); + + // store last selected printer + SettingsConfigItem* pItem = SettingsConfigItem::get(); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LastPrinter" ) ), + maJobPage.maPrinters.GetSelectEntry() ); + + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LastPage" ) ), + maTabCtrl.GetPageText( maTabCtrl.GetCurPageId() ) ); + pItem->Commit(); +} + bool PrintDialog::isPrintToFile() { return maJobPage.maToFileBox.IsChecked(); @@ -966,13 +1095,21 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) { - if( pButton == &maPrinterPage.maSetupButton ) + if( pButton == &maOKButton || pButton == &maCancelButton ) { - maPListener->getPrinter()->Setup( this ); + storeToSettings(); + EndDialog( pButton == &maOKButton ); + } + else + { + if( pButton == &maPrinterPage.maSetupButton ) + { + maPListener->getPrinter()->Setup( this ); + } + checkControlDependencies(); + if( pButton == &maPrinterPage.maNupPortrait || pButton == &maPrinterPage.maNupLandscape ) + updateNup(); } - checkControlDependencies(); - if( pButton == &maPrinterPage.maNupPortrait || pButton == &maPrinterPage.maNupLandscape ) - updateNup(); return 0; } -- cgit From c8e7522755016b630edeac9b7ba4e41a7e74d997 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 2 Jun 2009 13:23:25 +0000 Subject: #i92516# restart on correct page --- vcl/aqua/inc/aquaprintview.h | 11 ++++++- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 42 ++++++++++++++++++--------- vcl/aqua/source/gdi/salprn.cxx | 12 ++++---- 3 files changed, 45 insertions(+), 20 deletions(-) diff --git a/vcl/aqua/inc/aquaprintview.h b/vcl/aqua/inc/aquaprintview.h index 15b0fd3751ce..a3984333f84e 100755 --- a/vcl/aqua/inc/aquaprintview.h +++ b/vcl/aqua/inc/aquaprintview.h @@ -40,6 +40,15 @@ class AquaSalInfoPrinter; namespace vcl { class PrinterListener; } +struct PrintAccessoryViewState +{ + bool bNeedRestart; + sal_Int32 nLastPage; + + PrintAccessoryViewState() + : bNeedRestart( false ), nLastPage( 0 ) {} +}; + @interface AquaPrintView : NSView { vcl::PrinterListener* mpListener; @@ -55,7 +64,7 @@ namespace vcl { class PrinterListener; } @interface AquaPrintAccessoryView : NSObject { } -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withRestartCondition: (bool*)pbRestart; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withState: (PrintAccessoryViewState*)pState; @end diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 7c6fa970b316..f5196b369658 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -56,18 +56,23 @@ class ListenerProperties std::vector< NSObject* > maViews; int mnNextTag; sal_Int32 mnLastPageCount; - bool* mpNeedRestart; + PrintAccessoryViewState* mpState; NSPrintOperation* mpOp; + NSTabView* mpTabView; public: - ListenerProperties( vcl::PrinterListener* i_pListener, NSPrintOperation* i_pOp, bool* i_pNeedRestart ) + ListenerProperties( vcl::PrinterListener* i_pListener, + NSPrintOperation* i_pOp, + NSTabView* i_pTabView, + PrintAccessoryViewState* i_pState ) : mpListener( i_pListener ), mnNextTag( 0 ), mnLastPageCount( i_pListener->getPageCount() ), - mpNeedRestart( i_pNeedRestart ), - mpOp( i_pOp ) + mpState( i_pState ), + mpOp( i_pOp ), + mpTabView( i_pTabView ) { - *mpNeedRestart = false; + mpState->bNeedRestart = false; } void updatePrintJob() @@ -80,9 +85,14 @@ class ListenerProperties if( nPages != mnLastPageCount ) fprintf( stderr, "trouble: number of pages changed from %ld to %ld !\n", mnLastPageCount, nPages ); #endif - *mpNeedRestart = (nPages != mnLastPageCount); + mpState->bNeedRestart = (nPages != mnLastPageCount); + NSTabViewItem* pItem = [mpTabView selectedTabViewItem]; + if( pItem ) + mpState->nLastPage = [mpTabView indexOfTabViewItem: pItem]; + else + mpState->nLastPage = 0; mnLastPageCount = nPages; - if( *mpNeedRestart ) + if( mpState->bNeedRestart ) { // Warning: bad hack ahead // Apple does not give as a chance of changing the page count, @@ -285,15 +295,12 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) } @implementation AquaPrintAccessoryView -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withRestartCondition: (bool*)pbRestart; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withState: (PrintAccessoryViewState*)pState; { const Sequence< PropertyValue >& rOptions( pListener->getUIOptions() ); if( rOptions.getLength() == 0 ) return nil; - ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pbRestart ); - ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; - NSView* pCurParent = 0; long nCurY = 0; long nCurX = 0; @@ -302,6 +309,9 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aViewFrame]; sal_Bool bIgnoreSubgroup = sal_False; + ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pTabView, pState ); + ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; + for( int i = 0; i < rOptions.getLength(); i++ ) { Sequence< beans::PropertyValue > aOptProp; @@ -483,10 +493,10 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) numberOfRows: aChoices.getLength() numberOfColumns: 1]; // get currently selected value - rtl::OUString aSelectVal; + sal_Int32 nSelectVal; PropertyValue* pVal = pListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) - pVal->Value >>= aSelectVal; + pVal->Value >>= nSelectVal; // set individual titles NSArray* pCells = [pMatrix cells]; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) @@ -503,7 +513,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pCell setTag: nTag]; [pTitle release]; // set current selection - if( aSelectVal == aChoices[m] ) + if( nSelectVal == m ) [pMatrix selectCellAtRow: m column: 0]; } [pMatrix sizeToFit]; @@ -616,6 +626,10 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // set the accessory view [pOp setAccessoryView: pTabView]; + + // set the current selecte tab item + if( pState->nLastPage >= 0 && pState->nLastPage < [pTabView numberOfTabViewItems] ) + [pTabView selectTabViewItemAtIndex: pState->nLastPage]; return pCtrlTarget; } diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 3d86e0b6f0ad..944812e1a8ea 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -512,9 +512,11 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, BOOL bSuccess = FALSE; AquaSalInstance* pInst = GetSalData()->mpFirstInstance; - bool bNeedRestart = true; + PrintAccessoryViewState aAccViewState; sal_Int32 nAllPages = 0; + aAccViewState.bNeedRestart = true; + // reset IsLastPage i_rListener.setLastPage( sal_False ); @@ -524,14 +526,14 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, do { - if( bNeedRestart ) + if( aAccViewState.bNeedRestart ) { mnCurPageRangeStart = 0; mnCurPageRangeCount = 0; nAllPages = i_rListener.getPageCount(); } - bNeedRestart = false; + aAccViewState.bNeedRestart = false; Size aCurSize( 21000, 29700 ); if( nAllPages > 0 ) @@ -593,7 +595,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: YES]; if( bShowPanel && mnCurPageRangeStart == 0 ) // only the first range of pages gets the accesory view - pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withRestartCondition: &bNeedRestart]; + pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withState: &aAccViewState]; bSuccess = TRUE; mbJob = true; @@ -607,7 +609,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, mnCurPageRangeStart += mnCurPageRangeCount; mnCurPageRangeCount = 1; - } while( bNeedRestart || mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); + } while( aAccViewState.bNeedRestart || mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); // inform applictation that it can release its data // this is awkward, but the XRenderable interface has no method for this, -- cgit From 30eb643a7daf38348350968b8cbdecbcc0ec0f24 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 2 Jun 2009 16:56:35 +0000 Subject: #i92516# add missing controls, fix some minor issues --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 256 +++++++++++++++++++++++++- 1 file changed, 246 insertions(+), 10 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index f5196b369658..33774ea67d53 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -53,6 +53,7 @@ class ListenerProperties vcl::PrinterListener* mpListener; std::map< int, rtl::OUString > maTagToPropertyName; std::map< int, sal_Int32 > maTagToValueInt; + std::map< NSView*, NSView* > maViewPairMap; std::vector< NSObject* > maViews; int mnNextTag; sal_Int32 mnLastPageCount; @@ -136,6 +137,21 @@ class ListenerProperties maViews.push_back( i_pView ); } + void addViewPair( NSView* i_pLeft, NSView* i_pRight ) + { + maViewPairMap[ i_pLeft ] = i_pRight; + maViewPairMap[ i_pRight ] = i_pLeft; + } + + NSView* getPair( NSView* i_pLeft ) const + { + NSView* pRight = nil; + std::map< NSView*, NSView* >::const_iterator it = maViewPairMap.find( i_pLeft ); + if( it != maViewPairMap.end() ) + pRight = it->second; + return pRight; + } + void changePropertyWithIntValue( int i_nTag ) { std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); @@ -150,6 +166,20 @@ class ListenerProperties } } } + + void changePropertyWithIntValue( int i_nTag, sal_Int64 i_nValue ) + { + std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); + if( name_it != maTagToPropertyName.end() ) + { + PropertyValue* pVal = mpListener->getValue( name_it->second ); + if( pVal ) + { + pVal->Value <<= i_nValue; + updatePrintJob(); + } + } + } void changePropertyWithBoolValue( int i_nTag, sal_Bool i_bValue ) { @@ -165,6 +195,20 @@ class ListenerProperties } } + void changePropertyWithStringValue( int i_nTag, const rtl::OUString& i_rValue ) + { + std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); + if( name_it != maTagToPropertyName.end() ) + { + PropertyValue* pVal = mpListener->getValue( name_it->second ); + if( pVal ) + { + pVal->Value <<= i_rValue; + updatePrintJob(); + } + } + } + void updateEnableState() { for( std::vector< NSObject* >::iterator it = maViews.begin(); it != maViews.end(); ++it ) @@ -186,9 +230,15 @@ class ListenerProperties { MacOSBOOL bEnabled = mpListener->isUIOptionEnabled( name_it->second ) ? YES : NO; if( pCtrl ) + { [pCtrl setEnabled: bEnabled]; + NSView* pOther = getPair( pCtrl ); + if( pOther && [pOther isKindOfClass: [NSControl class]] ) + [(NSControl*)pOther setEnabled: bEnabled]; + } else if( pCell ) [pCell setEnabled: bEnabled]; + } } } @@ -208,6 +258,7 @@ static void filterAccelerator( rtl::OUString& io_rText ) } -(id)initWithListenerMap: (ListenerProperties*)pListener; -(void)triggered:(id)pSender; +-(void)triggeredNumeric:(id)pSender; -(void)dealloc; @end @@ -248,6 +299,45 @@ static void filterAccelerator( rtl::OUString& io_rText ) mpListener->changePropertyWithIntValue( nTag ); } } + else if( [pSender isMemberOfClass: [NSTextField class]] ) + { + NSTextField* pField = (NSTextField*)pSender; + int nTag = [pField tag]; + rtl::OUString aValue = GetOUString( [pSender stringValue] ); + mpListener->changePropertyWithStringValue( nTag, aValue ); + } + else + { + DBG_ERROR( "unsupported class" ); + } + mpListener->updateEnableState(); +} +-(void)triggeredNumeric:(id)pSender; +{ + if( [pSender isMemberOfClass: [NSTextField class]] ) + { + NSTextField* pField = (NSTextField*)pSender; + int nTag = [pField tag]; + sal_Int64 nValue = [pField intValue]; + + NSView* pOther = mpListener->getPair( pField ); + if( pOther ) + [(NSControl*)pOther setIntValue: nValue]; + + mpListener->changePropertyWithIntValue( nTag, nValue ); + } + else if( [pSender isMemberOfClass: [NSStepper class]] ) + { + NSStepper* pStep = (NSStepper*)pSender; + int nTag = [pStep tag]; + sal_Int64 nValue = [pStep intValue]; + + NSView* pOther = mpListener->getPair( pStep ); + if( pOther ) + [(NSControl*)pOther setIntValue: nValue]; + + mpListener->changePropertyWithIntValue( nTag, nValue ); + } else { DBG_ERROR( "unsupported class" ); @@ -323,6 +413,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rtl::OUString aText; rtl::OUString aPropertyName; Sequence< rtl::OUString > aChoices; + sal_Int64 nMinValue = 0, nMaxValue = 0; + long nAttachOffset = 0; sal_Bool bIgnore = sal_False; for( int n = 0; n < aOptProp.getLength(); n++ ) @@ -353,6 +445,18 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rEntry.Value >>= bValue; bEnabled = bValue; } + else if( rEntry.Name.equalsAscii( "MinValue" ) ) + { + rEntry.Value >>= nMinValue; + } + else if( rEntry.Name.equalsAscii( "MaxValue" ) ) + { + rEntry.Value >>= nMaxValue; + } + else if( rEntry.Name.equalsAscii( "AttachToDependency" ) ) + { + nAttachOffset = 20; + } else if( rEntry.Name.equalsAscii( "InternalUIOnly" ) ) { rEntry.Value >>= bIgnore; @@ -363,6 +467,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aCtrlType.equalsAscii( "Subgroup" ) || aCtrlType.equalsAscii( "Radio" ) || aCtrlType.equalsAscii( "List" ) || + aCtrlType.equalsAscii( "Edit" ) || + aCtrlType.equalsAscii( "Range" ) || aCtrlType.equalsAscii( "Bool" ) ) { // since our build target is MacOSX 10.4 we can have only one accessory view @@ -412,9 +518,6 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // update nCurY nCurY = aTextRect.origin.y - 5; - // set indent - nCurX = 20; - // cleanup [pText release]; } @@ -423,7 +526,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { NSString* pText = CreateNSString( aText ); - NSRect aCheckRect = { { nCurX, 0 }, { 0, 15 } }; + NSRect aCheckRect = { { nCurX + nAttachOffset, 0 }, { 0, 15 } }; NSButton* pBtn = [[NSButton alloc] initWithFrame: aCheckRect]; [pBtn setButtonType: NSSwitchButton]; [pBtn setTitle: pText]; @@ -432,7 +535,6 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) if( pVal ) pVal->Value >>= bVal; [pBtn setState: bVal ? NSOnState : NSOffState]; - [pBtn setEnabled: (pListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL) ? YES : NO]; [pBtn sizeToFit]; [pCurParent addSubview: pBtn]; @@ -457,11 +559,12 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { + sal_Int32 nOff = 0; if( aText.getLength() ) { // add a label NSString* pText = CreateNSString( aText ); - NSRect aTextRect = { { nCurX, 0 }, { 300, 15 } }; + NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, { 300, 15 } }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; @@ -477,6 +580,9 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // update nCurY nCurY = aTextRect.origin.y - 5; + // indent the radio group relative to the text + // nOff = 20; + // cleanup [pText release]; } @@ -484,7 +590,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // setup radio matrix NSButtonCell* pProto = [[NSButtonCell alloc] init]; - NSRect aRadioRect = { { nCurX + 20, 0 }, { 280 - nCurX, 5*aChoices.getLength() } }; + NSRect aRadioRect = { { nCurX + nOff, 0 }, { 280 - nCurX, 5*aChoices.getLength() } }; [pProto setTitle: @"RadioButtonGroup"]; [pProto setButtonType: NSRadioButton]; NSMatrix* pMatrix = [[NSMatrix alloc] initWithFrame: aRadioRect @@ -548,7 +654,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // will have to suffice for the time being. aTextSize.width *= 1.5; aTextSize.height += 3; - NSRect aTextRect = { { nCurX, 0 }, aTextSize }; + NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; @@ -561,7 +667,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aTextRect = [pTextView frame]; - NSRect aBtnRect = { { nCurX + aTextRect.size.width, 0 }, { 0, 15 } }; + NSRect aBtnRect = { { nCurX + nAttachOffset + aTextRect.size.width, 0 }, { 0, 15 } }; NSPopUpButton* pBtn = [[NSPopUpButton alloc] initWithFrame: aBtnRect pullsDown: NO]; // iterate options @@ -580,7 +686,6 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aSelectVal; [pBtn selectItemAtIndex: aSelectVal]; - [pBtn setEnabled: (pListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL) ? YES : NO]; // add the button to observed controls for enabled state changes // also add a tag just for this purpose @@ -609,12 +714,143 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // cleanup [pText release]; } + else if( (aCtrlType.equalsAscii( "Edit" ) || aCtrlType.equalsAscii( "Range" )) && pCurParent ) + { + sal_Int32 nOff = 0; + if( aText.getLength() ) + { + // add a label + NSString* pText = CreateNSString( aText ); + NSFont* pFont = [NSFont labelFontOfSize: 0]; + NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont + forKey: NSFontAttributeName]; + + NSSize aTextSize = [pText sizeWithAttributes: pDict]; + // FIXME: the only thing reliable about sizeWithAttributes is + // that the size it outputs is way too small for our NSTextView + // that would not matter so much if NSTextView's fitToSize actually + // did something out of the box, alas it doesn't. This probably needs more + // fiddling with NSTextView's and NSTextContainer's parameters, however + // since this already almost cost me my sanity a Murphy factor of 1.5 + // will have to suffice for the time being. + aTextSize.width *= 1.5; + aTextSize.height += 3; + NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; + NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setEditable: NO]; + [pTextView setSelectable: NO]; + [pTextView setDrawsBackground: NO]; + [pTextView setString: pText]; + [pTextView sizeToFit]; // FIXME: this does nothing + [pCurParent addSubview: pTextView]; + + // move to nCurY + aTextRect.origin.y = nCurY - aTextRect.size.height; + [pTextView setFrame: aTextRect]; + + // update nCurY + nCurY = aTextRect.origin.y - 5; + + // and set the offset for the real edit field + nOff = aTextSize.width + 5; + + // cleanup + [pText release]; + } + + NSRect aFieldRect = { { nCurX + nOff + nAttachOffset, 0 }, { 100, 25 } }; + NSTextField* pFieldView = [[NSTextField alloc] initWithFrame: aFieldRect]; + [pFieldView setEditable: YES]; + [pFieldView setSelectable: YES]; + [pFieldView setDrawsBackground: YES]; + [pFieldView sizeToFit]; // FIXME: this does nothing + [pCurParent addSubview: pFieldView]; + + // add the field to observed controls for enabled state changes + // also add a tag just for this purpose + pListenerProperties->addObservedControl( pFieldView ); + int nTag = pListenerProperties->addNameTag( aPropertyName ); + [pFieldView setTag: nTag]; + // pListenerProperties->addNamedView( pFieldView, aPropertyName ); + + // move to nCurY + aFieldRect.origin.y = nCurY - aFieldRect.size.height; + [pFieldView setFrame: aFieldRect]; + + // current value + PropertyValue* pVal = pListener->getValue( aPropertyName ); + if( aCtrlType.equalsAscii( "Range" ) ) + { + // add a stepper control + NSRect aStepFrame = { { aFieldRect.origin.x + aFieldRect.size.width + 5, + aFieldRect.origin.y }, + { 15, aFieldRect.size.height } }; + NSStepper* pStep = [[NSStepper alloc] initWithFrame: aStepFrame]; + [pStep setIncrement: 1]; + [pStep setValueWraps: NO]; + [pStep setTag: nTag]; + [pCurParent addSubview: pStep]; + pListenerProperties->addObservedControl( pStep ); + [pStep setTarget: pCtrlTarget]; + [pStep setAction: @selector(triggered:)]; + + // constrain the text field to decimal numbers + NSNumberFormatter* pFormatter = [[NSNumberFormatter alloc] init]; + [pFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; + [pFormatter setAllowsFloats: NO]; + if( nMinValue != nMaxValue ) + { + [pFormatter setMinimum: [[NSNumber numberWithInt: nMinValue] autorelease]]; + [pStep setMinValue: nMinValue]; + [pFormatter setMaximum: [[NSNumber numberWithInt: nMaxValue] autorelease]]; + [pStep setMaxValue: nMaxValue]; + } + [pFieldView setFormatter: pFormatter]; + + sal_Int64 nSelectVal = 0; + if( pVal && pVal->Value.hasValue() ) + pVal->Value >>= nSelectVal; + + [pFieldView setIntValue: nSelectVal]; + [pStep setIntValue: nSelectVal]; + + pListenerProperties->addViewPair( pFieldView, pStep ); + // connect target and action + [pFieldView setTarget: pCtrlTarget]; + [pFieldView setAction: @selector(triggeredNumeric:)]; + [pStep setTarget: pCtrlTarget]; + [pStep setAction: @selector(triggeredNumeric:)]; + } + else + { + // connect target and action + [pFieldView setTarget: pCtrlTarget]; + [pFieldView setAction: @selector(triggered:)]; + + if( pVal && pVal->Value.hasValue() ) + { + rtl::OUString aValue; + pVal->Value >>= aValue; + if( aValue.getLength() ) + { + NSString* pText = CreateNSString( aValue ); + [pFieldView setStringValue: pText]; + [pText release]; + } + } + } + + // update nCurY + nCurY = aFieldRect.origin.y - 5; + + } } else { DBG_ERROR( "Unsupported UI option" ); } } + pListenerProperties->updateEnableState(); adjustViewAndChildren( pCurParent, aMaxTabSize ); // find the minimum needed tab size -- cgit From 457e3281821544b84b8328590b5ca407750031dc Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 3 Jun 2009 14:41:23 +0000 Subject: #i92516# enable WB_DROPDOWN on TabControl --- rsc/source/parser/rscicpx.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/rsc/source/parser/rscicpx.cxx b/rsc/source/parser/rscicpx.cxx index e69094064754..bced7f36c3b6 100644 --- a/rsc/source/parser/rscicpx.cxx +++ b/rsc/source/parser/rscicpx.cxx @@ -2279,6 +2279,7 @@ RscTop * RscTypCont::InitClassTabControl( RscTop * pSuper, RSC_TABCONTROL_ITEMLIST ); INS_WINBIT( pClassTabControl, SingleLine ); + INS_WINBIT( pClassTabControl, DropDown ); } return pClassTabControl; -- cgit From 07c9e528cb418b3c722342d5548e49650d7852ef Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 3 Jun 2009 14:43:17 +0000 Subject: #i92516# enable WB_DROPDOWN on TabControl --- vcl/inc/vcl/lstbox.h | 5 ++ vcl/inc/vcl/tabctrl.hxx | 8 +-- vcl/source/control/ilstbox.cxx | 2 + vcl/source/control/lstbox.cxx | 18 ++++++- vcl/source/control/tabctrl.cxx | 117 ++++++++++++++++++++++++++++++++++------- 5 files changed, 128 insertions(+), 22 deletions(-) diff --git a/vcl/inc/vcl/lstbox.h b/vcl/inc/vcl/lstbox.h index 6097422b556b..9b95b9526d58 100644 --- a/vcl/inc/vcl/lstbox.h +++ b/vcl/inc/vcl/lstbox.h @@ -60,4 +60,9 @@ */ #define LISTBOX_ENTRY_FLAG_MULTILINE 0x0000002 +/** this flags lets the item be drawn disabled (e.g. in grey text) + usage only guaranteed with LISTBOX_ENTRY_FLAG_DISABLE_SELECTION +*/ +#define LISTBOX_ENTRY_FLAG_DRAW_DISABLED 0x0000004 + #endif // _SV_LSTBOX_H diff --git a/vcl/inc/vcl/tabctrl.hxx b/vcl/inc/vcl/tabctrl.hxx index b12d33d579a3..cfe40a25a7f2 100644 --- a/vcl/inc/vcl/tabctrl.hxx +++ b/vcl/inc/vcl/tabctrl.hxx @@ -31,15 +31,16 @@ #ifndef _SV_TABCTRL_HXX #define _SV_TABCTRL_HXX -#include -#include -#include +#include "vcl/sv.h" +#include "vcl/dllapi.h" +#include "vcl/ctrl.hxx" struct ImplTabItem; struct ImplTabCtrlData; class ImplTabItemList; class TabPage; class PushButton; +class ListBox; // -------------------- // - TabControl-Types - @@ -92,6 +93,7 @@ private: SAL_DLLPRIVATE void ImplPaint( const Rectangle& rRect, bool bLayout = false ); SAL_DLLPRIVATE void ImplFreeLayoutData(); DECL_DLLPRIVATE_LINK( ImplScrollBtnHdl, PushButton* pBtn ); + DECL_DLLPRIVATE_LINK( ImplListBoxSelectHdl, ListBox* ); protected: using Window::ImplInit; diff --git a/vcl/source/control/ilstbox.cxx b/vcl/source/control/ilstbox.cxx index a25ddbb68e8b..b3fed3ee7a05 100644 --- a/vcl/source/control/ilstbox.cxx +++ b/vcl/source/control/ilstbox.cxx @@ -1873,6 +1873,8 @@ void ImplListBoxWindow::DrawEntry( USHORT nPos, BOOL bDrawImage, BOOL bDrawText, USHORT nDrawStyle = ImplGetTextStyle(); if( (pEntry->mnFlags & LISTBOX_ENTRY_FLAG_MULTILINE) ) nDrawStyle |= MULTILINE_ENTRY_DRAW_FLAGS; + if( (pEntry->mnFlags & LISTBOX_ENTRY_FLAG_DRAW_DISABLED) ) + nDrawStyle |= TEXT_DRAW_DISABLE; DrawText( aTextRect, aStr, nDrawStyle, pVector, pDisplayText ); } diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 0accd17489c9..efb44a369df9 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -1267,7 +1267,23 @@ Size ListBox::CalcMinimumSize() const { aSz.Height() = mpImplLB->CalcSize( 1 ).Height(); aSz.Width() = mpImplLB->GetMaxEntryWidth(); - aSz.Width() += GetSettings().GetStyleSettings().GetScrollBarSize(); + + // try native borders; scrollbar size may not be a good indicator + // see how large the edit area inside is to estimate what is needed for the dropdown + ImplControlValue aControlValue; + Point aPoint; + Region aContent, aBound; + Size aTestSize( 100, 20 ); + Region aArea( Rectangle( aPoint, aTestSize ) ); + if( const_cast(this)->GetNativeControlRegion( + CTRL_LISTBOX, PART_SUB_EDIT, aArea, 0, aControlValue, rtl::OUString(), aBound, aContent) ) + { + // use the themes drop down size + Rectangle aContentRect = aContent.GetBoundRect(); + aSz.Width() += aTestSize.Width() - aContentRect.GetWidth(); + } + else + aSz.Width() += GetSettings().GetStyleSettings().GetScrollBarSize(); } aSz = CalcWindowSize( aSz ); diff --git a/vcl/source/control/tabctrl.cxx b/vcl/source/control/tabctrl.cxx index 561d550b1168..9ff3e4f5a728 100644 --- a/vcl/source/control/tabctrl.cxx +++ b/vcl/source/control/tabctrl.cxx @@ -47,6 +47,7 @@ #include #include #include +#include #include @@ -87,6 +88,7 @@ struct ImplTabCtrlData std::vector< Rectangle > maTabRectangles; Point maItemsOffset; // offset of the tabitems std::vector< ImplTabItem > maItemList; + ListBox* mpListBox; }; // ----------------------------------------------------------------------- @@ -159,10 +161,19 @@ void TabControl::ImplInit( Window* pParent, WinBits nStyle ) mpTabCtrlData = new ImplTabCtrlData; mpTabCtrlData->mpLeftBtn = NULL; mpTabCtrlData->mpRightBtn = NULL; + mpTabCtrlData->mpListBox = NULL; ImplInitSettings( TRUE, TRUE, TRUE ); + if( (nStyle & WB_DROPDOWN) ) + { + mpTabCtrlData->mpListBox = new ListBox( this, WB_DROPDOWN ); + mpTabCtrlData->mpListBox->SetPosSizePixel( Point( 0, 0 ), Size( 200, 20 ) ); + mpTabCtrlData->mpListBox->SetSelectHdl( LINK( this, TabControl, ImplListBoxSelectHdl ) ); + mpTabCtrlData->mpListBox->Show(); + } + // if the tabcontrol is drawn (ie filled) by a native widget, make sure all contols will have transparent background // otherwise they will paint with a wrong background if( IsNativeControlSupported(CTRL_TAB_PANE, PART_ENTIRE_CONTROL) ) @@ -292,6 +303,8 @@ TabControl::~TabControl() // TabCtrl-Daten loeschen if ( mpTabCtrlData ) { + if( mpTabCtrlData->mpListBox ) + delete mpTabCtrlData->mpListBox; if ( mpTabCtrlData->mpLeftBtn ) delete mpTabCtrlData->mpLeftBtn; if ( mpTabCtrlData->mpRightBtn ) @@ -797,7 +810,7 @@ void TabControl::ImplSetFirstPagePos( USHORT ) void TabControl::ImplShowFocus() { - if ( !GetPageCount() ) + if ( !GetPageCount() || mpTabCtrlData->mpListBox ) return; // make sure the focussed item rect is computed using a bold font @@ -1068,16 +1081,27 @@ IMPL_LINK( TabControl, ImplScrollBtnHdl, PushButton*, EMPTYARG ) // ----------------------------------------------------------------------- +IMPL_LINK( TabControl, ImplListBoxSelectHdl, ListBox*, EMPTYARG ) +{ + SelectTabPage( GetPageId( mpTabCtrlData->mpListBox->GetSelectEntryPos() ) ); + return 0; +} + +// ----------------------------------------------------------------------- + void TabControl::MouseButtonDown( const MouseEvent& rMEvt ) { - if ( rMEvt.IsLeft() ) + if( mpTabCtrlData->mpListBox == NULL ) { - USHORT nPageId = GetPageId( rMEvt.GetPosPixel() ); - ImplTabItem* pItem = ImplGetItem( nPageId ); - if( pItem && pItem->mbEnabled ) - SelectTabPage( nPageId ); - else - Sound::Beep( SOUND_ERROR, this ); + if( rMEvt.IsLeft() ) + { + USHORT nPageId = GetPageId( rMEvt.GetPosPixel() ); + ImplTabItem* pItem = ImplGetItem( nPageId ); + if( pItem && pItem->mbEnabled ) + SelectTabPage( nPageId ); + else + Sound::Beep( SOUND_ERROR, this ); + } } } @@ -1085,7 +1109,9 @@ void TabControl::MouseButtonDown( const MouseEvent& rMEvt ) void TabControl::KeyInput( const KeyEvent& rKEvt ) { - if ( GetPageCount() > 1 ) + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->KeyInput( rKEvt ); + else if ( GetPageCount() > 1 ) { KeyCode aKeyCode = rKEvt.GetKeyCode(); USHORT nKeyCode = aKeyCode.GetCode(); @@ -1230,7 +1256,7 @@ void TabControl::ImplPaint( const Rectangle& rRect, bool bLayout ) } } - if ( !mpTabCtrlData->maItemList.empty() ) + if ( !mpTabCtrlData->maItemList.empty() && mpTabCtrlData->mpListBox == NULL ) { // Some native toolkits (GTK+) draw tabs right-to-left, with an // overlap between adjacent tabs @@ -1300,6 +1326,18 @@ void TabControl::Resize() if ( !IsReallyShown() ) return; + if( mpTabCtrlData->mpListBox ) + { + // get the listbox' preferred size + Size aTabCtrlSize( GetSizePixel() ); + long nPrefWidth = mpTabCtrlData->mpListBox->GetOptimalSize( WINDOWSIZE_PREFERRED ).Width(); + if( nPrefWidth > aTabCtrlSize.Width() ) + nPrefWidth = aTabCtrlSize.Width(); + Size aNewSize( nPrefWidth, LogicToPixel( Size( 12, 12 ), MapMode( MAP_APPFONT ) ).Height() ); + Point aNewPos( (aTabCtrlSize.Width() - nPrefWidth) / 2, 0 ); + mpTabCtrlData->mpListBox->SetPosSizePixel( aNewPos, aNewSize ); + } + mbFormat = TRUE; // Aktuelle TabPage resizen/positionieren @@ -1349,8 +1387,16 @@ void TabControl::Resize() void TabControl::GetFocus() { - ImplShowFocus(); - SetInputContext( InputContext( GetFont() ) ); + if( ! mpTabCtrlData->mpListBox ) + { + ImplShowFocus(); + SetInputContext( InputContext( GetFont() ) ); + } + else + { + if( mpTabCtrlData->mpListBox->IsReallyVisible() ) + mpTabCtrlData->mpListBox->GrabFocus(); + } Control::GetFocus(); } @@ -1358,7 +1404,8 @@ void TabControl::GetFocus() void TabControl::LoseFocus() { - HideFocus(); + if( ! mpTabCtrlData->mpListBox ) + HideFocus(); Control::LoseFocus(); } @@ -1452,7 +1499,7 @@ void TabControl::RequestHelp( const HelpEvent& rHEvt ) void TabControl::Command( const CommandEvent& rCEvt ) { - if ( (rCEvt.GetCommand() == COMMAND_CONTEXTMENU) && (GetPageCount() > 1) ) + if( (mpTabCtrlData->mpListBox == NULL) && (rCEvt.GetCommand() == COMMAND_CONTEXTMENU) && (GetPageCount() > 1) ) { Point aMenuPos; BOOL bMenu; @@ -1496,7 +1543,11 @@ void TabControl::StateChanged( StateChangedType nType ) Control::StateChanged( nType ); if ( nType == STATE_CHANGE_INITSHOW ) + { ImplPosCurTabPage(); + if( mpTabCtrlData->mpListBox ) + Resize(); + } else if ( nType == STATE_CHANGE_UPDATEMODE ) { if ( IsUpdateMode() ) @@ -1714,23 +1765,33 @@ void TabControl::InsertPage( USHORT nPageId, const XubString& rText, DBG_ASSERT( GetPagePos( nPageId ) == TAB_PAGE_NOTFOUND, "TabControl::InsertPage(): PageId already exists" ); - // set current page id - if ( !mnCurPageId ) - mnCurPageId = nPageId; - // insert new page item ImplTabItem* pItem = NULL; if( nPos == TAB_APPEND || size_t(nPos) >= mpTabCtrlData->maItemList.size() ) { mpTabCtrlData->maItemList.push_back( ImplTabItem() ); pItem = &mpTabCtrlData->maItemList.back(); + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->InsertEntry( rText ); } else { std::vector< ImplTabItem >::iterator new_it = mpTabCtrlData->maItemList.insert( mpTabCtrlData->maItemList.begin() + nPos, ImplTabItem() ); pItem = &(*new_it); + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->InsertEntry( rText, nPos); } + if( mpTabCtrlData->mpListBox ) + { + if( ! mnCurPageId ) + mpTabCtrlData->mpListBox->SelectEntryPos( 0 ); + mpTabCtrlData->mpListBox->SetDropDownLineCount( mpTabCtrlData->mpListBox->GetEntryCount() ); + } + + // set current page id + if ( !mnCurPageId ) + mnCurPageId = nPageId; // init new page item pItem->mnId = nPageId; @@ -1745,6 +1806,8 @@ void TabControl::InsertPage( USHORT nPageId, const XubString& rText, Invalidate(); ImplFreeLayoutData(); + if( mpTabCtrlData->mpListBox ) // reposition/resize listbox + Resize(); ImplCallEventListeners( VCLEVENT_TABPAGE_INSERTED, (void*) (ULONG)nPageId ); } @@ -1762,6 +1825,11 @@ void TabControl::RemovePage( USHORT nPageId ) std::vector< ImplTabItem >::iterator it = mpTabCtrlData->maItemList.begin() + nPos; bool bIsCurrentPage = (it->mnId == mnCurPageId); mpTabCtrlData->maItemList.erase( it ); + if( mpTabCtrlData->mpListBox ) + { + mpTabCtrlData->mpListBox->RemoveEntry( nPos ); + mpTabCtrlData->mpListBox->SetDropDownLineCount( mpTabCtrlData->mpListBox->GetEntryCount() ); + } // If current page is removed, than first page gets the current page if ( bIsCurrentPage ) @@ -1799,6 +1867,8 @@ void TabControl::Clear() // clear item list mpTabCtrlData->maItemList.clear(); mnCurPageId = 0; + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->Clear(); ImplFreeLayoutData(); @@ -1819,6 +1889,9 @@ void TabControl::EnablePage( USHORT i_nPageId, bool i_bEnable ) { pItem->mbEnabled = i_bEnable; mbFormat = TRUE; + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->SetEntryFlags( GetPagePos( i_nPageId ), + i_bEnable ? 0 : (LISTBOX_ENTRY_FLAG_DISABLE_SELECTION | LISTBOX_ENTRY_FLAG_DRAW_DISABLED) ); if( pItem->mnId == mnCurPageId ) { // SetCurPageId will change to an enabled page @@ -1943,6 +2016,8 @@ void TabControl::SelectTabPage( USHORT nPageId ) nPageId = mnActPageId; mnActPageId = 0; SetCurPageId( nPageId ); + if( mpTabCtrlData->mpListBox ) + mpTabCtrlData->mpListBox->SelectEntryPos( GetPagePos( nPageId ) ); ImplCallEventListeners( VCLEVENT_TABPAGE_ACTIVATE, (void*) (ULONG) nPageId ); } } @@ -2007,6 +2082,12 @@ void TabControl::SetPageText( USHORT nPageId, const XubString& rText ) { pItem->maText = rText; mbFormat = TRUE; + if( mpTabCtrlData->mpListBox ) + { + USHORT nPos = GetPagePos( nPageId ); + mpTabCtrlData->mpListBox->RemoveEntry( nPos ); + mpTabCtrlData->mpListBox->InsertEntry( rText, nPos ); + } if ( IsUpdateMode() ) Invalidate(); ImplFreeLayoutData(); -- cgit From 586a494193a5d0147332abb7c17e1e70e74dee20 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 3 Jun 2009 18:51:46 +0000 Subject: #i92516# latest changes according to UX --- vcl/inc/vcl/prndlg.hxx | 49 +++---- vcl/inc/vcl/svids.hrc | 81 ++++++------ vcl/source/src/print.src | 130 ++++++++---------- vcl/source/window/printdlg.cxx | 292 +++++++++++++++++++++-------------------- 4 files changed, 274 insertions(+), 278 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 4e7302f112c0..dc8d2ba6586f 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -39,7 +39,6 @@ #include "vcl/dialog.hxx" #include "vcl/fixed.hxx" #include "vcl/button.hxx" -#include "vcl/scrbar.hxx" #include "vcl/gdimtf.hxx" #include "vcl/lstbox.hxx" #include "vcl/field.hxx" @@ -53,6 +52,16 @@ namespace vcl { class PrintDialog : public ModalDialog { + class PrinterListBox : public ListBox + { + public: + PrinterListBox( Window* i_pParent, const ResId& i_rId ) + : ListBox( i_pParent, i_rId ) + {} + virtual ~PrinterListBox() {} + virtual void RequestHelp( const HelpEvent& i_rHEvt ); + }; + class PrintPreviewWindow : public Window { GDIMetaFile maMtf; @@ -68,19 +77,9 @@ namespace vcl void setScale( double fScaleX, double fScaleY ); }; - class PrinterTabPage : public TabPage + class NUpTabPage : public TabPage { public: - ListBox maPrinters; - PushButton maSetupButton; - FixedText maType; - FixedText maTypeText; - FixedText maStatus; - FixedText maStatusText; - FixedText maLocation; - FixedText maLocText; - FixedText maComment; - FixedText maCommentText; FixedLine maNupLine; FixedText maNupRowsTxt; NumericField maNupRowsEdt; @@ -89,8 +88,8 @@ namespace vcl RadioButton maNupPortrait; RadioButton maNupLandscape; - PrinterTabPage( Window*, const ResId& ); - virtual ~PrinterTabPage(); + NUpTabPage( Window*, const ResId& ); + virtual ~NUpTabPage(); void readFromSettings(); void storeToSettings(); @@ -99,7 +98,8 @@ namespace vcl class JobTabPage : public TabPage { public: - ListBox maPrinters; + PrinterListBox maPrinters; + PushButton maSetupButton; CheckBox maToFileBox; FixedLine maCopies; @@ -123,11 +123,13 @@ namespace vcl OKButton maOKButton; CancelButton maCancelButton; PrintPreviewWindow maPreviewWindow; - FixedText maPageText; - ScrollBar maPageSlider; + NumericField maPageEdit; + FixedText maNumPagesText; + PushButton maForwardBtn; + PushButton maBackwardBtn; TabControl maTabCtrl; - PrinterTabPage maPrinterPage; + NUpTabPage maNUpPage; JobTabPage maJobPage; FixedLine maButtonLine; @@ -149,6 +151,11 @@ namespace vcl Size maNupPortraitSize; Size maNupLandscapeSize; + rtl::OUString maCommentText; + rtl::OUString maStatusText; + rtl::OUString maLocationText; + rtl::OUString maTypeText; + void updateNup(); void preparePreview( bool i_bPrintChanged = true ); void setPreviewText( sal_Int32 ); @@ -162,8 +169,6 @@ namespace vcl virtual void Resize(); - DECL_LINK( SlideHdl, ScrollBar* ); - DECL_LINK( EndSlideHdl, ScrollBar* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); DECL_LINK( ModifyHdl, Edit* ); @@ -190,8 +195,8 @@ namespace vcl CancelButton maButton; bool mbCanceled; - int mnCur; - int mnMax; + sal_Int32 mnCur; + sal_Int32 mnMax; long mnProgressHeight; Rectangle maProgressRect; bool mbNativeProgress; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 1c5f5d598faf..c42435344d34 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -77,52 +77,51 @@ #define SV_DLG_PRINT 2048 #define SV_PRINT_OK 1 #define SV_PRINT_CANCEL 2 -#define SV_PRINT_PAGE_TXT 3 -#define SV_PRINT_PAGE_PREVIEW 4 -#define SV_PRINT_PAGE_SCROLL 5 -#define SV_PRINT_TABCTRL 6 +#define SV_PRINT_PAGE_PREVIEW 3 +#define SV_PRINT_PAGE_TXT 4 +#define SV_PRINT_PAGE_FORWARD 5 +#define SV_PRINT_PAGE_BACKWARD 6 +#define SV_PRINT_PAGE_EDIT 7 +#define SV_PRINT_TABCTRL 8 +#define SV_PRINT_PRT_TYPE 9 +#define SV_PRINT_PRT_STATUS 10 +#define SV_PRINT_PRT_LOCATION 11 +#define SV_PRINT_PRT_COMMENT 12 + +#define SV_PRINT_TAB_NUP 1 +#define SV_PRINT_PRT_NUP 1 +#define SV_PRINT_PRT_NUP_ROWS_TXT 2 +#define SV_PRINT_PRT_NUP_ROWS_EDT 3 +#define SV_PRINT_PRT_NUP_COLUMNS_TXT 4 +#define SV_PRINT_PRT_NUP_COLUMNS_EDT 5 +#define SV_PRINT_PRT_NUP_PORTRAIT 6 +#define SV_PRINT_PRT_NUP_LANDSCAPE 7 -#define SV_PRINT_TAB_PRINTER 1 +#define SV_PRINT_TAB_JOB 2 #define SV_PRINT_PRINTERS 1 -#define SV_PRINT_PRT_TYPE 2 -#define SV_PRINT_PRT_TYPE_TXT 3 -#define SV_PRINT_PRT_STATUS 4 -#define SV_PRINT_PRT_STATUS_TXT 5 -#define SV_PRINT_PRT_LOCATION 6 -#define SV_PRINT_PRT_LOCATION_TXT 7 -#define SV_PRINT_PRT_COMMENT 8 -#define SV_PRINT_PRT_COMMENT_TXT 9 -#define SV_PRINT_PRT_TOFILE 10 -#define SV_PRINT_PRT_SETUP 11 -#define SV_PRINT_PRT_NUP 12 -#define SV_PRINT_PRT_NUP_ROWS_TXT 13 -#define SV_PRINT_PRT_NUP_ROWS_EDT 14 -#define SV_PRINT_PRT_NUP_COLUMNS_TXT 15 -#define SV_PRINT_PRT_NUP_COLUMNS_EDT 16 -#define SV_PRINT_PRT_NUP_PORTRAIT 17 -#define SV_PRINT_PRT_NUP_LANDSCAPE 18 - -#define SV_DLG_PRINT_PROGRESS 2048 +#define SV_PRINT_PRT_TOFILE 2 +#define SV_PRINT_PRT_SETUP 3 +#define SV_PRINT_RANGE 4 +#define SV_PRINT_ALL 5 +#define SV_PRINT_PAGERANGE 6 +#define SV_PRINT_SELECTION 7 +#define SV_PRINT_PAGERANGE_EDIT 8 +#define SV_PRINT_COPIES 9 +#define SV_PRINT_COPYCOUNT 10 +#define SV_PRINT_COPYCOUNT_FIELD 11 +#define SV_PRINT_COLLATE 12 +#define SV_PRINT_COLLATE_IMAGE 13 +#define SV_PRINT_BUTTONLINE 14 +#define SV_PRINT_COLLATE_IMG 15 +#define SV_PRINT_NOCOLLATE_IMG 16 +#define SV_PRINT_COLLATE_HC_IMG 17 +#define SV_PRINT_NOCOLLATE_HC_IMG 18 +#define SV_PRINT_NOPAGES 19 + +#define SV_DLG_PRINT_PROGRESS 2049 #define SV_PRINT_PROGRESS_CANCEL 1 #define SV_PRINT_PROGRESS_TEXT 2 -#define SV_PRINT_TAB_JOB 2 -#define SV_PRINT_RANGE 1 -#define SV_PRINT_ALL 2 -#define SV_PRINT_PAGERANGE 3 -#define SV_PRINT_SELECTION 4 -#define SV_PRINT_PAGERANGE_EDIT 5 -#define SV_PRINT_COPIES 6 -#define SV_PRINT_COPYCOUNT 7 -#define SV_PRINT_COPYCOUNT_FIELD 8 -#define SV_PRINT_COLLATE 9 -#define SV_PRINT_COLLATE_IMAGE 10 -#define SV_PRINT_BUTTONLINE 11 -#define SV_PRINT_COLLATE_IMG 12 -#define SV_PRINT_NOCOLLATE_IMG 13 -#define SV_PRINT_COLLATE_HC_IMG 14 -#define SV_PRINT_NOCOLLATE_HC_IMG 15 -#define SV_PRINT_NOPAGES 16 #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index d6842560d1f8..c949dbea95dd 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -59,25 +59,36 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 130, 130 ); Border = TRUE; }; - ScrollBar SV_PRINT_PAGE_SCROLL + NumericField SV_PRINT_PAGE_EDIT { Pos = MAP_APPFONT( 5, 140 ); - Size = MAP_APPFONT( 130, 10 ); + Size = MAP_APPFONT( 30, 12 ); SVLook = TRUE; - HScroll = TRUE; - TabStop = TRUE; + Spin = TRUE; + Border = TRUE; }; FixedText SV_PRINT_PAGE_TXT { - Pos = MAP_APPFONT( 5,150 ); - Size = MAP_APPFONT( 130, 10 ); - Text [ en-US ] = "Page %p of %n"; - Center = TRUE; + Pos = MAP_APPFONT( 40,142 ); + Size = MAP_APPFONT( 30, 12 ); + Text [ en-US ] = "/ %n"; + VCenter = TRUE; + }; + PushButton SV_PRINT_PAGE_FORWARD + { + Pos = MAP_APPFONT( 95, 140 ); + Size = MAP_APPFONT( 15, 12 ); + }; + PushButton SV_PRINT_PAGE_BACKWARD + { + Pos = MAP_APPFONT( 80, 140 ); + Size = MAP_APPFONT( 15, 12 ); }; TabControl SV_PRINT_TABCTRL { Pos = MAP_APPFONT( 140, 5 ); Size = MAP_APPFONT( 205, 165 ); +// DropDown = TRUE; }; FixedLine SV_PRINT_BUTTONLINE { @@ -89,82 +100,43 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "No pages"; }; - TabPage SV_PRINT_TAB_PRINTER + String SV_PRINT_PRT_TYPE + { + Text [en-US] = "Type: %s"; + }; + String SV_PRINT_PRT_STATUS + { + Text [en-US] = "Status: %s"; + }; + String SV_PRINT_PRT_LOCATION + { + Text [en-US] = "Location: %s"; + }; + String SV_PRINT_PRT_COMMENT + { + Text [en-US] = "Comment: %s"; + }; + + TabPage SV_PRINT_TAB_NUP { - Text [en-US] = "Printer"; + Text [en-US] = "N-Up"; Hide = TRUE; - ListBox SV_PRINT_PRINTERS - { - Pos = MAP_APPFONT( 5, 5 ); - Size = MAP_APPFONT( 100, 200 ); - DropDown = TRUE; - }; - PushButton SV_PRINT_PRT_SETUP - { - Pos = MAP_APPFONT( 115, 5 ); - Size = MAP_APPFONT( 50, 15 ); - Text [en-US] = "Properties..."; - }; - FixedText SV_PRINT_PRT_TYPE - { - Pos = MAP_APPFONT( 5, 30 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Type"; - }; - FixedText SV_PRINT_PRT_TYPE_TXT - { - Pos = MAP_APPFONT( 50, 30 ); - Size = MAP_APPFONT( 200, 10 ); - }; - FixedText SV_PRINT_PRT_STATUS - { - Pos = MAP_APPFONT( 5, 42 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Status"; - }; - FixedText SV_PRINT_PRT_STATUS_TXT - { - Pos = MAP_APPFONT( 50, 42 ); - Size = MAP_APPFONT( 200, 10 ); - }; - FixedText SV_PRINT_PRT_LOCATION - { - Pos = MAP_APPFONT( 5, 54 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Location"; - }; - FixedText SV_PRINT_PRT_LOCATION_TXT - { - Pos = MAP_APPFONT( 50, 54 ); - Size = MAP_APPFONT( 200, 10 ); - }; - FixedText SV_PRINT_PRT_COMMENT - { - Pos = MAP_APPFONT( 5, 66 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Comment"; - }; - FixedText SV_PRINT_PRT_COMMENT_TXT - { - Pos = MAP_APPFONT( 50, 66 ); - Size = MAP_APPFONT( 200, 10 ); - }; FixedLine SV_PRINT_PRT_NUP { - Pos = MAP_APPFONT( 5, 80 ); + Pos = MAP_APPFONT( 5, 10 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "N-Up printing"; }; FixedText SV_PRINT_PRT_NUP_ROWS_TXT { - Pos = MAP_APPFONT( 10, 95 ); + Pos = MAP_APPFONT( 10, 25 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Rows"; }; NumericField SV_PRINT_PRT_NUP_ROWS_EDT { - Pos = MAP_APPFONT( 55, 95 ); + Pos = MAP_APPFONT( 55, 25 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -174,13 +146,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_COLUMNS_TXT { - Pos = MAP_APPFONT( 10, 110 ); + Pos = MAP_APPFONT( 10, 50 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "C~olumns"; }; NumericField SV_PRINT_PRT_NUP_COLUMNS_EDT { - Pos = MAP_APPFONT( 55, 110 ); + Pos = MAP_APPFONT( 55, 50 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -190,13 +162,13 @@ ModalDialog SV_DLG_PRINT }; RadioButton SV_PRINT_PRT_NUP_PORTRAIT { - Pos = MAP_APPFONT( 110, 95 ); + Pos = MAP_APPFONT( 110, 25 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "Po~rtrait"; }; RadioButton SV_PRINT_PRT_NUP_LANDSCAPE { - Pos = MAP_APPFONT( 110, 105 ); + Pos = MAP_APPFONT( 110, 35 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "~Landscape"; }; @@ -213,6 +185,12 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 100, 200 ); DropDown = TRUE; }; + PushButton SV_PRINT_PRT_SETUP + { + Pos = MAP_APPFONT( 115, 5 ); + Size = MAP_APPFONT( 50, 15 ); + Text [en-US] = "Properties..."; + }; CheckBox SV_PRINT_PRT_TOFILE { Pos = MAP_APPFONT( 10, 20 ); @@ -233,7 +211,7 @@ ModalDialog SV_DLG_PRINT }; NumericField SV_PRINT_COPYCOUNT_FIELD { - Pos = MAP_APPFONT( 90, 45 ); + Pos = MAP_APPFONT( 10, 55 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -243,12 +221,12 @@ ModalDialog SV_DLG_PRINT }; FixedImage SV_PRINT_COLLATE_IMAGE { - Pos = MAP_APPFONT( 10, 65 ); + Pos = MAP_APPFONT( 90, 60 ); Size = MAP_PIXEL( 80, 30 ); }; CheckBox SV_PRINT_COLLATE { - Pos = MAP_APPFONT( 80, 65 ); + Pos = MAP_APPFONT( 90, 45 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index fea99791c113..4ec838ad289c 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -42,6 +42,7 @@ #include "vcl/decoview.hxx" #include "vcl/arrange.hxx" #include "vcl/configsettings.hxx" +#include "vcl/help.hxx" #include "rtl/ustrbuf.hxx" @@ -56,6 +57,14 @@ using namespace com::sun::star::beans; #define SMHID2( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ":" b ) ) ) ) #define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ) ) ) +void PrintDialog::PrinterListBox::RequestHelp( const HelpEvent& i_rHEvt ) +{ + if( i_rHEvt.GetMode() & HELPMODE_QUICK ) + Help::ShowBalloon( this, i_rHEvt.GetMousePosPixel(), GetHelpText() ); + else + ListBox::RequestHelp( i_rHEvt ); +} + PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ), mfScaleX( 1 ), @@ -98,18 +107,8 @@ void PrintDialog::PrintPreviewWindow::setScale( double fScaleX, double fScaleY ) Invalidate(); } -PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rResId ) +PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) - , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) - , maSetupButton( this, VclResId( SV_PRINT_PRT_SETUP ) ) - , maType( this, VclResId( SV_PRINT_PRT_TYPE ) ) - , maTypeText( this, VclResId( SV_PRINT_PRT_TYPE_TXT ) ) - , maStatus( this, VclResId( SV_PRINT_PRT_STATUS ) ) - , maStatusText(this, VclResId( SV_PRINT_PRT_STATUS_TXT ) ) - , maLocation( this, VclResId( SV_PRINT_PRT_LOCATION ) ) - , maLocText( this, VclResId( SV_PRINT_PRT_LOCATION_TXT ) ) - , maComment( this, VclResId( SV_PRINT_PRT_COMMENT ) ) - , maCommentText( this, VclResId( SV_PRINT_PRT_COMMENT_TXT ) ) , maNupLine( this, VclResId( SV_PRINT_PRT_NUP ) ) , maNupRowsTxt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_TXT ) ) , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) @@ -119,45 +118,35 @@ PrintDialog::PrinterTabPage::PrinterTabPage( Window* i_pParent, const ResId& rRe , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) { FreeResource(); - maPrinters.SMHID2( "PrinterPage", "PrinterList" ); - maSetupButton.SMHID2( "PrinterPage", "Setup" ); - maType.SMHID2( "PrinterPage", "Type" ); - maTypeText.SMHID2( "PrinterPage", "TypeText" ); - maStatus.SMHID2( "PrinterPage", "Status" ); - maStatusText.SMHID2( "PrinterPage", "StatusText" ); - maLocation.SMHID2( "PrinterPage", "Locaction" ); - maLocText.SMHID2( "PrinterPage", "LocactionText" ); - maComment.SMHID2( "PrinterPage", "Comment" ); - maCommentText.SMHID2( "PrinterPage", "CommentText" ); - maNupLine.SMHID2( "PrinterPage", "NUPline" ); - maNupRowsTxt.SMHID2( "PrinterPage", "NUPRowsText" ); - maNupRowsEdt.SMHID2( "PrinterPage", "NUPRows" ); - maNupColTxt.SMHID2( "PrinterPage", "NUPColumnsText" ); - maNupColEdt.SMHID2( "PrinterPage", "NUPColumns" ); - maNupPortrait.SMHID2( "PrinterPage", "NUPPortrait" ); - maNupLandscape.SMHID2( "PrinterPage", "NUPLandscape" ); + maNupLine.SMHID2( "NUpPage", "NUPline" ); + maNupRowsTxt.SMHID2( "NUpPage", "NUPRowsText" ); + maNupRowsEdt.SMHID2( "NUpPage", "NUPRows" ); + maNupColTxt.SMHID2( "NUpPage", "NUPColumnsText" ); + maNupColEdt.SMHID2( "NUpPage", "NUPColumns" ); + maNupPortrait.SMHID2( "NUpPage", "NUPPortrait" ); + maNupLandscape.SMHID2( "NUpPage", "NUPLandscape" ); } -PrintDialog::PrinterTabPage::~PrinterTabPage() +PrintDialog::NUpTabPage::~NUpTabPage() { } -void PrintDialog::PrinterTabPage::readFromSettings() +void PrintDialog::NUpTabPage::readFromSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ) ); sal_Int32 nVal = aValue.toInt32(); maNupRowsEdt.SetValue( sal_Int64( nVal > 1 ? nVal : 1) ); - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ) ); nVal = aValue.toInt32(); maNupColEdt.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ) ); if( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ) maNupPortrait.Check(); @@ -165,16 +154,16 @@ void PrintDialog::PrinterTabPage::readFromSettings() maNupLandscape.Check(); } -void PrintDialog::PrinterTabPage::storeToSettings() +void PrintDialog::NUpTabPage::storeToSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ), maNupRowsEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ), maNupColEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_PrinterPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ), rtl::OUString::createFromAscii( maNupPortrait.IsChecked() ? "true" : "false" ) ); } @@ -182,6 +171,7 @@ void PrintDialog::PrinterTabPage::storeToSettings() PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) + , maSetupButton( this, VclResId( SV_PRINT_PRT_SETUP ) ) , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) , maCopies( this, VclResId( SV_PRINT_COPIES ) ) , maCopyCount( this, VclResId( SV_PRINT_COPYCOUNT ) ) @@ -195,6 +185,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) { FreeResource(); maPrinters.SMHID2( "JobPage", "PrinterList" ); + maSetupButton.SMHID2( "JobPage", "Setup" ); maToFileBox.SMHID2( "JobPage", "ToFile" ); maCopies.SMHID2( "JobPage", "CopiesLine" ); maCopyCount.SMHID2( "JobPage", "CopiesText" ); @@ -245,48 +236,53 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& rQueues( Printer::GetPrinterQueues() ); for( std::vector< rtl::OUString >::const_iterator it = rQueues.begin(); it != rQueues.end(); ++it ) { - maPrinterPage.maPrinters.InsertEntry( *it ); maJobPage.maPrinters.InsertEntry( *it ); } // select current printer - if( maPrinterPage.maPrinters.GetEntryPos( maPListener->getPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) + if( maJobPage.maPrinters.GetEntryPos( maPListener->getPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) { - maPrinterPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); maJobPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); } else @@ -295,16 +291,14 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LastPrinter" ) ) ) ); - if( maPrinterPage.maPrinters.GetEntryPos( aValue ) != LISTBOX_ENTRY_NOTFOUND ) + if( maJobPage.maPrinters.GetEntryPos( aValue ) != LISTBOX_ENTRY_NOTFOUND ) { - maPrinterPage.maPrinters.SelectEntry( aValue ); maJobPage.maPrinters.SelectEntry( aValue ); maPListener->setPrinter( boost::shared_ptr( new Printer( aValue ) ) ); } else { // fall back to default printer - maPrinterPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); maJobPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); maPListener->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); } @@ -313,7 +307,6 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr 1 maCancelButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); #endif + maForwardBtn.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maBackwardBtn.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maJobPage.maCollateBox.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); - maPrinterPage.maSetupButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); - maPrinterPage.maNupPortrait.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); - maPrinterPage.maNupLandscape.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maJobPage.maSetupButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maNUpPage.maNupPortrait.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); + maNUpPage.maNupLandscape.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); // setup modify hdl + maPageEdit.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); maJobPage.maCopyCountField.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); - maPrinterPage.maNupRowsEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); - maPrinterPage.maNupColEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); + maNUpPage.maNupRowsEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); + maNUpPage.maNupColEdt.SetModifyHdl( LINK( this, PrintDialog, ModifyHdl ) ); // setup optional UI options set by application setupOptionalUI(); @@ -366,8 +362,10 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPrinter()->HasSupport( SUPPORT_SETUPDIALOG ) ); + bool bHaveSetup = maPListener->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ); + maJobPage.maSetupButton.Enable( bHaveSetup ); + if( bHaveSetup ) + { + if( ! maJobPage.maSetupButton.IsVisible() ) + { + Point aPrinterPos( maJobPage.maPrinters.GetPosPixel() ); + Point aSetupPos( maJobPage.maSetupButton.GetPosPixel() ); + Size aPrinterSize( maJobPage.maPrinters.GetSizePixel() ); + aPrinterSize.Width() = aSetupPos.X() - aPrinterPos.X() - LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ).Width(); + maJobPage.maPrinters.SetSizePixel( aPrinterSize ); + maJobPage.maSetupButton.Show(); + } + } + else + { + if( maJobPage.maSetupButton.IsVisible() ) + { + Point aPrinterPos( maJobPage.maPrinters.GetPosPixel() ); + Point aSetupPos( maJobPage.maSetupButton.GetPosPixel() ); + Size aPrinterSize( maJobPage.maPrinters.GetSizePixel() ); + Size aSetupSize( maJobPage.maSetupButton.GetSizePixel() ); + aPrinterSize.Width() = aSetupPos.X() + aSetupSize.Width() - aPrinterPos.X(); + maJobPage.maPrinters.SetSizePixel( aPrinterSize ); + maJobPage.maSetupButton.Hide(); + } + } } void PrintDialog::checkOptionalControlDependencies() @@ -948,27 +968,14 @@ void PrintDialog::checkOptionalControlDependencies() } } -void PrintDialog::updatePrinterText() -{ - const QueueInfo* pInfo = Printer::GetQueueInfo( maPrinterPage.maPrinters.GetSelectEntry(), true ); - if( pInfo ) - { - maPrinterPage.maTypeText.SetText( pInfo->GetDriver() ); - // FIXME: status message - // maJobPage.maStatusText.SetText(); - maPrinterPage.maLocText.SetText( pInfo->GetLocation() ); - maPrinterPage.maCommentText.SetText( pInfo->GetComment() ); - } -} - -static rtl::OUString searchAndReplace( const rtl::OUString& i_rOrig, const char* i_pRepl, sal_Int32 i_nReplLen, sal_Int32 i_nReplacement ) +static rtl::OUString searchAndReplace( const rtl::OUString& i_rOrig, const char* i_pRepl, sal_Int32 i_nReplLen, const rtl::OUString& i_rRepl ) { sal_Int32 nPos = i_rOrig.indexOfAsciiL( i_pRepl, i_nReplLen ); if( nPos != -1 ) { rtl::OUStringBuffer aBuf( i_rOrig.getLength() ); aBuf.append( i_rOrig.getStr(), nPos ); - aBuf.append( i_nReplacement ); + aBuf.append( i_rRepl ); if( nPos + i_nReplLen < i_rOrig.getLength() ) aBuf.append( i_rOrig.getStr() + nPos + i_nReplLen ); return aBuf.makeStringAndClear(); @@ -976,16 +983,31 @@ static rtl::OUString searchAndReplace( const rtl::OUString& i_rOrig, const char* return i_rOrig; } +void PrintDialog::updatePrinterText() +{ + const QueueInfo* pInfo = Printer::GetQueueInfo( maJobPage.maPrinters.GetSelectEntry(), true ); + if( pInfo ) + { + rtl::OUStringBuffer aBuf( 256 ); + aBuf.append( searchAndReplace( maTypeText, "%s", 2, pInfo->GetDriver() ) ); + aBuf.append( sal_Unicode( '\n' ) ); + aBuf.append( searchAndReplace( maLocationText, "%s", 2, pInfo->GetLocation() ) ); + aBuf.append( sal_Unicode( '\n' ) ); + aBuf.append( searchAndReplace( maCommentText, "%s", 2, pInfo->GetComment() ) ); + aBuf.append( sal_Unicode( '\n' ) ); + maJobPage.maPrinters.SetHelpText( aBuf.makeStringAndClear() ); + } +} + void PrintDialog::setPreviewText( sal_Int32 nSetPage ) { if( mnCachedPages != 0 ) { - rtl::OUString aNewText( searchAndReplace( maPageStr, "%p", 2, nSetPage+1 ) ); - aNewText = searchAndReplace( aNewText, "%n", 2, mnCachedPages ); - maPageText.SetText( aNewText ); + rtl::OUString aNewText( searchAndReplace( maPageStr, "%n", 2, rtl::OUString::valueOf( mnCachedPages ) ) ); + maNumPagesText.SetText( aNewText ); } else - maPageText.SetText( maNoPageStr ); + maNumPagesText.SetText( maNoPageStr ); } void PrintDialog::preparePreview( bool i_bNewPage ) @@ -1001,9 +1023,8 @@ void PrintDialog::preparePreview( bool i_bNewPage ) setPreviewText( mnCurPage ); - maPageSlider.SetRange( Range( 0, nPages ) ); - maPageSlider.SetThumbPos( mnCurPage ); - maPageSlider.SetVisibleSize( 1 ); + maPageEdit.SetMin( 1 ); + maPageEdit.SetMax( nPages ); boost::shared_ptr aPrt( maPListener->getPrinter() ); @@ -1044,47 +1065,22 @@ void PrintDialog::preparePreview( bool i_bNewPage ) void PrintDialog::updateNup() { - int nRows = int(maPrinterPage.maNupRowsEdt.GetValue()); - int nCols = int(maPrinterPage.maNupColEdt.GetValue()); + int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); + int nCols = int(maNUpPage.maNupColEdt.GetValue()); maPListener->setMultipage( nRows, nCols, - maPrinterPage.maNupPortrait.IsChecked() + maNUpPage.maNupPortrait.IsChecked() ? maNupPortraitSize : maNupLandscapeSize ); preparePreview(); } -IMPL_LINK( PrintDialog, SlideHdl, ScrollBar*, pSlider ) -{ - if( pSlider == &maPageSlider ) - { - sal_Int32 nNewPage = static_cast( maPageSlider.GetThumbPos() ); - setPreviewText( nNewPage ); - } - return 0; -} - -IMPL_LINK( PrintDialog, EndSlideHdl, ScrollBar*, pSlider ) -{ - if( pSlider == &maPageSlider ) - { - sal_Int32 nNewPage = static_cast( maPageSlider.GetThumbPos() ); - if( nNewPage != mnCurPage ) - { - mnCurPage = nNewPage; - preparePreview(); - } - } - return 0; -} - IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) { - if( pBox == &maPrinterPage.maPrinters || pBox == &maJobPage.maPrinters ) + if( pBox == &maJobPage.maPrinters ) { String aNewPrinter( pBox->GetSelectEntry() ); maJobPage.maPrinters.SelectEntry( aNewPrinter ); - maPrinterPage.maPrinters.SelectEntry( aNewPrinter ); // set new printer maPListener->setPrinter( boost::shared_ptr( new Printer( aNewPrinter ) ) ); // update text fields @@ -1100,14 +1096,22 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) storeToSettings(); EndDialog( pButton == &maOKButton ); } + else if( pButton == &maForwardBtn ) + { + maPageEdit.Up(); + } + else if( pButton == &maBackwardBtn ) + { + maPageEdit.Down(); + } else { - if( pButton == &maPrinterPage.maSetupButton ) + if( pButton == &maJobPage.maSetupButton ) { maPListener->getPrinter()->Setup( this ); } checkControlDependencies(); - if( pButton == &maPrinterPage.maNupPortrait || pButton == &maPrinterPage.maNupLandscape ) + if( pButton == &maNUpPage.maNupPortrait || pButton == &maNUpPage.maNupLandscape ) updateNup(); } return 0; @@ -1116,10 +1120,15 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { checkControlDependencies(); - if( pEdit == &maPrinterPage.maNupRowsEdt || pEdit == &maPrinterPage.maNupColEdt ) + if( pEdit == &maNUpPage.maNupRowsEdt || pEdit == &maNUpPage.maNupColEdt ) { updateNup(); } + else if( pEdit == &maPageEdit ) + { + mnCurPage = sal_Int32( maPageEdit.GetValue() - 1 ); + preparePreview(); + } return 0; } @@ -1266,23 +1275,28 @@ void PrintDialog::Resize() long nMaxX = maTabCtrl.GetPosPixel().X() - 2*aPixDiff.Width(); long nMaxY = maButtonLine.GetPosPixel().Y() - 2 * aPixDiff.Height() - - maPageText.GetSizePixel().Height() - - maPageSlider.GetSizePixel().Height(); + - maForwardBtn.GetSizePixel().Height(); long nPreviewLength = std::min( nMaxX, nMaxY ); maPreviewSpace = Rectangle( Point( aPixDiff.Width(), aPixDiff.Height() ), Size( nPreviewLength, nPreviewLength ) ); - // position text and slider below preview - aBtnRect = Rectangle( Point( aPixDiff.Width(), 2*aPixDiff.Height() + nPreviewLength ), - Size( nPreviewLength, maPageSlider.GetSizePixel().Height() ) ); - maPageSlider.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - - aBtnRect.Top() = aBtnRect.Bottom() + aPixDiff.Height()/2; - aBtnRect.Bottom() = aBtnRect.Top() + maPageText.GetSizePixel().Height() - 1; - maPageText.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - // and do the preview; however the metafile does not need to be gotten anew preparePreview( false ); + + // position text and slider below preview, aligned + Point aCtrlPos( maPreviewWindow.GetPosPixel().X(), 2*aPixDiff.Height() + nPreviewLength ); + maPageEdit.SetPosPixel( aCtrlPos ); + + aCtrlPos.X() += maPageEdit.GetSizePixel().Width() + aPixDiff.Width(); + maNumPagesText.SetPosPixel( aCtrlPos ); + + aCtrlPos.X() = maPreviewWindow.GetPosPixel().X() + maPreviewWindow.GetSizePixel().Width(); + aCtrlPos.X() -= maForwardBtn.GetSizePixel().Width(); + maForwardBtn.SetPosPixel( aCtrlPos ); + + aCtrlPos.X() -= aPixDiff.Width() + maBackwardBtn.GetSizePixel().Width(); + maBackwardBtn.SetPosPixel( aCtrlPos ); + } // ----------------------------------------------------------------------------- @@ -1355,8 +1369,8 @@ void PrintProgressDialog::setProgress( int i_nCurrent, int i_nMax ) if( mnMax < 1 ) mnMax = 1; - rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, mnCur ) ); - aNewText = searchAndReplace( aNewText, "%n", 2, mnMax ); + rtl::OUString aNewText( searchAndReplace( maStr, "%p", 2, rtl::OUString::valueOf( mnCur ) ) ); + aNewText = searchAndReplace( aNewText, "%n", 2, rtl::OUString::valueOf( mnMax ) ); maText.SetText( aNewText ); // update progress -- cgit From fc1d80c5911955f1937822dd9561e7d81cb8a2ea Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 3 Jun 2009 19:22:35 +0000 Subject: fix a warning --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 4ec838ad289c..629e39f37336 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -999,7 +999,7 @@ void PrintDialog::updatePrinterText() } } -void PrintDialog::setPreviewText( sal_Int32 nSetPage ) +void PrintDialog::setPreviewText( sal_Int32 ) { if( mnCachedPages != 0 ) { -- cgit From b6cb39ab39a25200954d20780aabe70ac1347479 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 3 Jun 2009 19:23:14 +0000 Subject: fix a warning --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 33774ea67d53..b016920ae18e 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -599,7 +599,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) numberOfRows: aChoices.getLength() numberOfColumns: 1]; // get currently selected value - sal_Int32 nSelectVal; + sal_Int32 nSelectVal = 0; PropertyValue* pVal = pListener->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; -- cgit From 33ce99fd93f419a1659a541b37ad7b1de84a3e00 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 4 Jun 2009 10:37:39 +0000 Subject: get correct page count --- vcl/aqua/source/gdi/salprn.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 944812e1a8ea..f58c63b19079 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -530,7 +530,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, { mnCurPageRangeStart = 0; mnCurPageRangeCount = 0; - nAllPages = i_rListener.getPageCount(); + nAllPages = i_rListener.getFilteredPageCount(); } aAccViewState.bNeedRestart = false; -- cgit From a7432bba85ee4904c0768d0a32052c86a835fc6d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 5 Jun 2009 15:01:27 +0000 Subject: improve control arrangement, small UI changes --- vcl/inc/vcl/arrange.hxx | 22 ++++++++++++++++++++++ vcl/inc/vcl/prndlg.hxx | 3 +++ vcl/source/src/print.src | 10 +++++----- vcl/source/window/printdlg.cxx | 26 ++++++++++++++------------ 4 files changed, 44 insertions(+), 17 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index fdaf957dce76..cd13400fc27e 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -194,6 +194,28 @@ namespace vcl void setChild( WindowArranger* i_pChild, sal_Int32 i_nExpandPrio = 0 ) { setChild( boost::shared_ptr( i_pChild ), i_nExpandPrio ); } }; + + class Spacer : public WindowArranger + { + WindowArranger::Element m_aElement; + public: + Spacer( WindowArranger* i_pParent = NULL, sal_Int32 i_nPrio = 20 ) + : WindowArranger( i_pParent ) + , m_aElement( NULL, boost::shared_ptr(), i_nPrio ) + {} + + virtual ~Spacer() {} + + virtual Size getOptimalSize( WindowSizeType ) const + { return Size( 0, 0 ); } + virtual void resize() {} + virtual void setParentWindow( Window* ) {} + virtual size_t countElements() const { return 1; } + virtual boost::shared_ptr getChild( size_t i_nIndex ) const { return boost::shared_ptr(); } + virtual Window* getWindow( size_t i_nIndex ) const { return NULL; } + virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const + { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } + }; } #endif diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index dc8d2ba6586f..04a62fc84954 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -44,6 +44,7 @@ #include "vcl/field.hxx" #include "vcl/tabctrl.hxx" #include "vcl/tabpage.hxx" +#include "vcl/arrange.hxx" #include #include @@ -156,6 +157,8 @@ namespace vcl rtl::OUString maLocationText; rtl::OUString maTypeText; + vcl::RowOrColumn maPreviewCtrlRow; + void updateNup(); void preparePreview( bool i_bPrintChanged = true ); void setPreviewText( sal_Int32 ); diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index c949dbea95dd..58d8010f0a2c 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -57,14 +57,14 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 130, 130 ); - Border = TRUE; + Border = FALSE; }; NumericField SV_PRINT_PAGE_EDIT { Pos = MAP_APPFONT( 5, 140 ); Size = MAP_APPFONT( 30, 12 ); SVLook = TRUE; - Spin = TRUE; + Spin = FALSE; Border = TRUE; }; FixedText SV_PRINT_PAGE_TXT @@ -211,7 +211,7 @@ ModalDialog SV_DLG_PRINT }; NumericField SV_PRINT_COPYCOUNT_FIELD { - Pos = MAP_APPFONT( 10, 55 ); + Pos = MAP_APPFONT( 10, 56 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -221,12 +221,12 @@ ModalDialog SV_DLG_PRINT }; FixedImage SV_PRINT_COLLATE_IMAGE { - Pos = MAP_APPFONT( 90, 60 ); + Pos = MAP_APPFONT( 95, 60 ); Size = MAP_PIXEL( 80, 30 ); }; CheckBox SV_PRINT_COLLATE { - Pos = MAP_APPFONT( 90, 45 ); + Pos = MAP_APPFONT( 95, 45 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 629e39f37336..ec700683cc64 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -252,9 +252,20 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Mon, 8 Jun 2009 12:43:56 +0000 Subject: #i92516# move preview and corresponding controls into an own border --- vcl/inc/vcl/arrange.hxx | 1 + vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/window/printdlg.cxx | 48 ++++++++++++++++++++++++++++++++++++------ 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index cd13400fc27e..1f085521c818 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -114,6 +114,7 @@ namespace vcl m_aManagedArea = i_rArea; resize(); } + const Rectangle& getManagedArea() const { return m_aManagedArea; } void setOuterBorder( long i_nBorder ) { diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 04a62fc84954..64bfa65a8d23 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -158,6 +158,7 @@ namespace vcl rtl::OUString maTypeText; vcl::RowOrColumn maPreviewCtrlRow; + Rectangle maPreviewBackground; void updateNup(); void preparePreview( bool i_bPrintChanged = true ); @@ -171,6 +172,7 @@ namespace vcl com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; virtual void Resize(); + virtual void Paint( const Rectangle& ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index ec700683cc64..e94b0803df4a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -43,6 +43,7 @@ #include "vcl/arrange.hxx" #include "vcl/configsettings.hxx" #include "vcl/help.hxx" +#include "vcl/decoview.hxx" #include "rtl/ustrbuf.hxx" @@ -1252,6 +1253,34 @@ IMPL_LINK( PrintDialog, UIOption_ModifyHdl, Edit*, i_pBox ) return 0; } +void PrintDialog::Paint( const Rectangle& i_rRect ) +{ + ModalDialog::Paint( i_rRect ); + + #if 0 + // sadly Tab panes are not a reliable choice for a grouping background + // since they depend on the tab items above in some themes + if( IsNativeControlSupported( CTRL_TAB_PANE, PART_ENTIRE_CONTROL) ) + { + Rectangle aPrevBg( maPreviewBackground ); + #ifdef QUARTZ + // FIXME: this interacts with vcl/aqua/source/gdi/salnativewidgets.cxx where + // some magic offsets are added to the area + aPrevBg.Top() += 10; + #endif + const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 ); + + ControlState nState = CTRL_STATE_ENABLED; + Region aCtrlRegion( aPrevBg ); + DrawNativeControl( CTRL_TAB_PANE, PART_ENTIRE_CONTROL, aCtrlRegion, nState, + aControlValue, rtl::OUString() ); + } + #else + DecorationView aVw( this ); + aVw.DrawFrame( maPreviewBackground, FRAME_DRAW_IN ); + #endif +} + void PrintDialog::Resize() { Size aPixDiff( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); @@ -1285,20 +1314,25 @@ void PrintDialog::Resize() // set size for preview long nMaxX = maTabCtrl.GetPosPixel().X() - 2*aPixDiff.Width(); long nMaxY = maButtonLine.GetPosPixel().Y() - - 2 * aPixDiff.Height() + - 4 * aPixDiff.Height() - maForwardBtn.GetSizePixel().Height(); long nPreviewLength = std::min( nMaxX, nMaxY ); - maPreviewSpace = Rectangle( Point( aPixDiff.Width(), aPixDiff.Height() ), + maPreviewSpace = Rectangle( Point( aPixDiff.Width(), 2 * aPixDiff.Height() ), Size( nPreviewLength, nPreviewLength ) ); - // and do the preview; however the metafile does not need to be gotten anew - preparePreview( false ); - // position text and slider below preview, aligned Size aPrefSize( maPreviewCtrlRow.getOptimalSize( WINDOWSIZE_PREFERRED ) ); - aPrefSize.Width() = maPreviewWindow.GetSizePixel().Width(); - Point aCtrlPos( maPreviewWindow.GetPosPixel().X(), 2*aPixDiff.Height() + nPreviewLength ); + aPrefSize.Width() = nPreviewLength - 2* aPixDiff.Width(); + Point aCtrlPos( 2*aPixDiff.Width(), 3*aPixDiff.Height() + nPreviewLength ); maPreviewCtrlRow.setManagedArea( Rectangle( aCtrlPos, aPrefSize ) ); + maPreviewBackground.Left() = aPixDiff.Width(); + maPreviewBackground.Top() = aPixDiff.Height(); + maPreviewBackground.Right() = aPixDiff.Width() + nPreviewLength; + maPreviewBackground.Bottom() = maPreviewCtrlRow.getManagedArea().Bottom() + aPixDiff.Height(); + + // and do the preview; however the metafile does not need to be gotten anew + preparePreview( false ); + } // ----------------------------------------------------------------------------- -- cgit From a597b3e1f953fb9185e51cd24952026401dc9c11 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 9 Jun 2009 15:06:16 +0000 Subject: #i92516# adapt to new printer API --- padmin/source/padialog.cxx | 149 +++++++++++++++++++++++++++------------------ padmin/source/padialog.hxx | 2 - 2 files changed, 91 insertions(+), 60 deletions(-) diff --git a/padmin/source/padialog.cxx b/padmin/source/padialog.cxx index 5b49409a1c8a..7c8ed6d39fe3 100644 --- a/padmin/source/padialog.cxx +++ b/padmin/source/padialog.cxx @@ -60,11 +60,16 @@ #include "unotools/localedatawrapper.hxx" #include "unotools/configitem.hxx" #include "unotools/configmgr.hxx" + +#include "com/sun/star/awt/Size.hpp" + using namespace psp; using namespace rtl; using namespace padmin; using namespace osl; +using namespace com::sun::star; using namespace com::sun::star::uno; +using namespace com::sun::star::beans; PADialog* PADialog::Create( Window* pParent, BOOL bAdmin ) { @@ -96,7 +101,6 @@ PADialog::PADialog( Window* pParent, BOOL /*bAdmin*/ ) : m_aCancelButton( this, PaResId( RID_PA_BTN_CANCEL ) ), m_aDefPrt( PaResId( RID_PA_STR_DEFPRT ) ), m_aRenameStr( PaResId( RID_PA_STR_RENAME ) ), - m_pPrinter( 0 ), m_rPIManager( PrinterInfoManager::get() ) { FreeResource(); @@ -248,18 +252,6 @@ IMPL_LINK( PADialog, SelectHdl, ListBox*, pListBox ) return 0; } -IMPL_LINK( PADialog, EndPrintHdl, void*, EMPTYARG ) -{ - String aInfoString( PaResId( RID_PA_TXT_TESTPAGE_PRINTED ) ); - InfoBox aInfoBox( this, aInfoString ); - aInfoBox.SetText( String( PaResId( RID_BXT_TESTPAGE ) ) ); - aInfoBox.Execute(); - - delete m_pPrinter; - m_pPrinter = NULL; - return 0; -} - void PADialog::UpdateDefPrt() { m_rPIManager.setDefaultPrinter( getSelectedDevice() ); @@ -369,66 +361,77 @@ static Color approachColor( const Color& rFrom, const Color& rTo ) return aColor; } -#define DELTA 5.0 -void PADialog::PrintTestPage() +class SpaPrinterListener : public vcl::PrinterListener { - if( m_pPrinter ) // already printing; user pressed button twice - return; +public: + SpaPrinterListener( const boost::shared_ptr& i_pPrinter ) + : vcl::PrinterListener( i_pPrinter ) + {} + virtual ~SpaPrinterListener() + {} + + virtual int getPageCount() const { return 1; } + virtual Sequence< PropertyValue > getPageParameters( int i_nPage ) const; + virtual void printPage( int i_nPage ) const; + virtual void jobFinished(); +}; + +Sequence< PropertyValue > SpaPrinterListener::getPageParameters( int ) const +{ + Sequence< PropertyValue > aRet( 1 ); - String sPrinter( getSelectedDevice() ); + Size aPageSize( getPrinter()->GetPaperSizePixel() ); + aPageSize = getPrinter()->PixelToLogic( aPageSize, MapMode( MAP_100TH_MM ) ); + + awt::Size aSize; + aSize.Width = aPageSize.Width(); + aSize.Height = aPageSize.Height(); + aRet[0].Value = makeAny(aSize); - m_pPrinter = new Printer( sPrinter ); + return aRet; +} - PrinterInfo aInfo( m_rPIManager.getPrinterInfo( sPrinter ) ); +void SpaPrinterListener::printPage( int ) const +{ + const double DELTA = 5.0; + + boost::shared_ptr pPrinter( getPrinter() ); + + PrinterInfo aInfo( psp::PrinterInfoManager::get().getPrinterInfo( pPrinter->GetName() ) ); const PPDParser* pPrintParser = aInfo.m_pParser; MapMode aMapMode( MAP_100TH_MM ); Bitmap aButterfly( PaResId( RID_BUTTERFLY ) ); - m_pPrinter->SetMapMode( aMapMode ); - m_pPrinter->SetEndPrintHdl( LINK( this, PADialog, EndPrintHdl ) ); + pPrinter->SetMapMode( aMapMode ); Any aRet = utl::ConfigManager::GetDirectConfigProperty( utl::ConfigManager::PRODUCTNAME ); OUString aJobName; aRet >>= aJobName; aJobName = aJobName + OUString( RTL_CONSTASCII_USTRINGPARAM( " Testpage" ) ); - if( m_pPrinter->GetName() != sPrinter || ! m_pPrinter->StartJob( aJobName ) ) - { - String aString( PaResId( RID_ERR_NOPRINTER ) ); - aString.SearchAndReplaceAscii( "%s", sPrinter ); - ErrorBox aErrorBox( this, WB_OK | WB_DEF_OK, aString ); - aErrorBox.SetText( String( PaResId( RID_BXT_ENVIRONMENT ) ) ); - aErrorBox.Execute(); - delete m_pPrinter; - m_pPrinter = 0; - return; - } - m_pPrinter->StartPage(); - - Size aPaperSize=m_pPrinter->GetOutputSize(); + Size aPaperSize=pPrinter->GetOutputSize(); Point aCenter( aPaperSize.Width()/2-300, aPaperSize.Height() - aPaperSize.Width()/2 ); Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint; - m_pPrinter->DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) ); - m_pPrinter->DrawRect( Rectangle( Point( 100,100 ), + pPrinter->DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) ); + pPrinter->DrawRect( Rectangle( Point( 100,100 ), Size( aPaperSize.Width()-200, aPaperSize.Height()-200 ) ) ); - m_pPrinter->DrawRect( Rectangle( Point( 200,200 ), + pPrinter->DrawRect( Rectangle( Point( 200,200 ), Size( aPaperSize.Width()-400, aPaperSize.Height()-400 ) ) ); - m_pPrinter->DrawRect( Rectangle( Point( 300,300 ), + pPrinter->DrawRect( Rectangle( Point( 300,300 ), Size( aPaperSize.Width()-600, aPaperSize.Height()-600 ) ) ); - Font aFont( m_pPrinter->GetFont() ); - aFont.SetName( String( RTL_CONSTASCII_USTRINGPARAM( "Courier" ) ) ); + Font aFont( String( RTL_CONSTASCII_USTRINGPARAM( "Courier" ) ), Size( 0, 400 ) ); aFont.SetWeight( WEIGHT_NORMAL ); aFont.SetItalic( ITALIC_NONE ); - m_pPrinter->SetFont( aFont ); + pPrinter->SetFont( aFont ); OUStringBuffer aPrintText(1024); long nWidth = 0, nMaxWidth = 0; @@ -455,12 +458,12 @@ void PADialog::PrintTestPage() aToken = String::CreateFromAscii( aResIds[i].pDirect ); else aToken = String( PaResId( aResIds[i].nResId ) ); - nMaxWidth = ( nWidth = m_pPrinter->GetTextWidth( aToken ) ) > nMaxWidth ? nWidth : nMaxWidth; + nMaxWidth = ( nWidth = pPrinter->GetTextWidth( aToken ) ) > nMaxWidth ? nWidth : nMaxWidth; aPrintText.append( aToken ); aPrintText.append( (sal_Unicode)'\n' ); }; - m_pPrinter->DrawText( Rectangle( Point( 1000, 2000 ), + pPrinter->DrawText( Rectangle( Point( 1000, 1000 ), Size( aPaperSize.Width() - 2000, aPaperSize.Height() - 4000 ) ), aPrintText.makeStringAndClear(), @@ -470,7 +473,7 @@ void PADialog::PrintTestPage() const LocaleDataWrapper& rLocaleWrapper( aSettings.GetLocaleDataWrapper() ); aPrintText.appendAscii( ": " ); - aPrintText.append( sPrinter ); + aPrintText.append( pPrinter->GetName() ); aPrintText.appendAscii( "\n: " ); if( pPrintParser ) aPrintText.append( pPrintParser->getPrinterName() ); @@ -487,17 +490,17 @@ void PADialog::PrintTestPage() aPrintText.appendAscii( "\n: " ); aPrintText.append( rLocaleWrapper.getTime( Time() ) ); - m_pPrinter->DrawText( Rectangle( Point( 1100 + nMaxWidth, 2000 ), + pPrinter->DrawText( Rectangle( Point( 1100 + nMaxWidth, 1000 ), Size( aPaperSize.Width() - 2100 - nMaxWidth, aPaperSize.Height() - 4000 ) ), aPrintText.makeStringAndClear(), TEXT_DRAW_MULTILINE ); - m_pPrinter->DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ), + pPrinter->DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ), Size( 3000,3000 ), aButterfly ); - m_pPrinter->SetFillColor(); - m_pPrinter->DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ), + pPrinter->SetFillColor(); + pPrinter->DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ), Size( 3000,3000 ) ) ); Color aWhite( 0xff, 0xff, 0xff ); @@ -511,22 +514,22 @@ void PADialog::PrintTestPage() Gradient aGradient( GRADIENT_LINEAR, aBlack, aWhite ); aGradient.SetAngle( 900 ); - m_pPrinter->DrawGradient( Rectangle( Point( 1000, 5500 ), + pPrinter->DrawGradient( Rectangle( Point( 1000, 5500 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkRed ); aGradient.SetEndColor( aLightBlue ); - m_pPrinter->DrawGradient( Rectangle( Point( 1000, 6300 ), + pPrinter->DrawGradient( Rectangle( Point( 1000, 6300 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkBlue ); aGradient.SetEndColor( aLightGreen ); - m_pPrinter->DrawGradient( Rectangle( Point( 1000, 7100 ), + pPrinter->DrawGradient( Rectangle( Point( 1000, 7100 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkGreen ); aGradient.SetEndColor( aLightRed ); - m_pPrinter->DrawGradient( Rectangle( Point( 1000, 7900 ), + pPrinter->DrawGradient( Rectangle( Point( 1000, 7900 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); @@ -543,7 +546,7 @@ void PADialog::PrintTestPage() { aLineInfo.SetWidth( n/3 ); aLineColor = approachColor( aLineColor, aApproachColor ); - m_pPrinter->SetLineColor( aLineColor ); + pPrinter->SetLineColor( aLineColor ); // switch aproach color if( aApproachColor.IsRGBEqual( aLineColor ) ) @@ -556,7 +559,7 @@ void PADialog::PrintTestPage() aApproachColor = Color( 0, 200, 0 ); } - m_pPrinter->DrawLine( project( aP1 ) + aCenter, + pPrinter->DrawLine( project( aP1 ) + aCenter, project( aP2 ) + aCenter, aLineInfo ); aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor); @@ -569,8 +572,38 @@ void PADialog::PrintTestPage() #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL fprintf( stderr, "%d lines\n",n ); #endif - m_pPrinter->EndPage(); - m_pPrinter->EndJob(); +} + +void SpaPrinterListener::jobFinished() +{ + String aInfoString( PaResId( RID_PA_TXT_TESTPAGE_PRINTED ) ); + InfoBox aInfoBox( NULL, aInfoString ); + aInfoBox.SetText( String( PaResId( RID_BXT_TESTPAGE ) ) ); + aInfoBox.Execute(); +} + +void PADialog::PrintTestPage() +{ + String sPrinter( getSelectedDevice() ); + + boost::shared_ptr pPrinter( new Printer( sPrinter ) ); + + if( pPrinter->GetName() != sPrinter ) + { + String aString( PaResId( RID_ERR_NOPRINTER ) ); + aString.SearchAndReplaceAscii( "%s", sPrinter ); + + ErrorBox aErrorBox( this, WB_OK | WB_DEF_OK, aString ); + aErrorBox.SetText( String( PaResId( RID_BXT_ENVIRONMENT ) ) ); + aErrorBox.Execute(); + return; + } + + boost::shared_ptr pListener( new SpaPrinterListener( pPrinter ) ); + JobSetup aJobSetup( pPrinter->GetJobSetup() ); + aJobSetup.SetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ), + String( RTL_CONSTASCII_USTRINGPARAM( "true" ) ) ); + Printer::PrintJob( pListener, aJobSetup ); } void PADialog::AddDevice() diff --git a/padmin/source/padialog.hxx b/padmin/source/padialog.hxx index ac6ee8f4279f..0350f66a2905 100644 --- a/padmin/source/padialog.hxx +++ b/padmin/source/padialog.hxx @@ -83,7 +83,6 @@ namespace padmin { String m_aDefPrt; String m_aRenameStr; - Printer* m_pPrinter; ::psp::PrinterInfoManager& m_rPIManager; ::std::list< ::rtl::OUString > m_aPrinters; @@ -94,7 +93,6 @@ namespace padmin { DECL_LINK( ClickBtnHdl, PushButton* ); DECL_LINK( DoubleClickHdl, ListBox* ); DECL_LINK( SelectHdl, ListBox* ); - DECL_LINK( EndPrintHdl, void* ); DECL_LINK( DelPressedHdl, ListBox* ); PADialog( Window*, BOOL ); -- cgit From 793ffd2b60a7b8c864e38928f8e169cf304e7bb3 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 9 Jun 2009 15:06:57 +0000 Subject: #i92516# allow for already available printer --- vcl/inc/vcl/print.hxx | 2 ++ vcl/source/gdi/print3.cxx | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 83e4e984a1d3..ecf3b8aa1a46 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -443,6 +443,8 @@ class ImplPrinterListenerData; class VCL_DLLPUBLIC PrinterListener { ImplPrinterListenerData* mpImplData; +protected: + PrinterListener( const boost::shared_ptr& ); public: PrinterListener(); virtual ~PrinterListener(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index ed1080a70e7b..e50b345c4a7f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -100,6 +100,12 @@ PrinterListener::PrinterListener() { } +PrinterListener::PrinterListener( const boost::shared_ptr& i_pPrinter ) + : mpImplData( new ImplPrinterListenerData ) +{ + mpImplData->mpPrinter = i_pPrinter; +} + static rtl::OUString queryFile( Printer* pPrinter ) { rtl::OUString aResult; -- cgit From 808c249f8c1ed5c8b583ac9d33e928d1f2dff81d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 9 Jun 2009 18:58:38 +0000 Subject: #i92516# additional N-Up functionality --- vcl/inc/vcl/print.hxx | 27 +++++++++- vcl/inc/vcl/prndlg.hxx | 17 ++++++ vcl/inc/vcl/svids.hrc | 14 +++++ vcl/source/gdi/print3.cxx | 82 +++++++++++++++++------------ vcl/source/src/print.src | 117 ++++++++++++++++++++++++++++++++++++++--- vcl/source/window/printdlg.cxx | 85 ++++++++++++++++++++++++++++-- 6 files changed, 296 insertions(+), 46 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index ecf3b8aa1a46..6d63d7a6ab23 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -446,6 +446,30 @@ class VCL_DLLPUBLIC PrinterListener protected: PrinterListener( const boost::shared_ptr& ); public: + struct MultiPageSetup + { + // all metrics in 100th mm + int nRows; + int nColumns; + Size aPaperSize; + long nLeftMargin; + long nTopMargin; + long nRightMargin; + long nBottomMargin; + long nHorizontalSpacing; + long nVerticalSpacing; + bool bDrawBorder; + + MultiPageSetup() + : nRows( 1 ), nColumns( 1 ), aPaperSize( 21000, 29700 ) + , nLeftMargin( 0 ), nTopMargin( 0 ) + , nRightMargin( 0 ), nBottomMargin( 0 ) + , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) + , bDrawBorder( true ) + { + } + }; + PrinterListener(); virtual ~PrinterListener(); @@ -497,7 +521,8 @@ public: void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); void SAL_DLLPRIVATE createProgressDialog(); - void SAL_DLLPRIVATE setMultipage( int nRows, int nColumns, const Size& rPaperSize ); + void SAL_DLLPRIVATE setMultipage( const MultiPageSetup& ); + const MultiPageSetup& getMultipage() const; void SAL_DLLPRIVATE setLastPage( sal_Bool i_bLastPage ); }; diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 64bfa65a8d23..384dcd2451e3 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -86,14 +86,31 @@ namespace vcl NumericField maNupRowsEdt; FixedText maNupColTxt; NumericField maNupColEdt; + CheckBox maBorderCB; RadioButton maNupPortrait; RadioButton maNupLandscape; + FixedLine maMargins; + FixedText maLeftMarginTxt; + MetricField maLeftMarginEdt; + FixedText maRightMarginTxt; + MetricField maRightMarginEdt; + FixedText maTopMarginTxt; + MetricField maTopMarginEdt; + FixedText maBottomMarginTxt; + MetricField maBottomMarginEdt; + + FixedText maHSpaceTxt; + MetricField maHSpaceEdt; + FixedText maVSpaceTxt; + MetricField maVSpaceEdt; + NUpTabPage( Window*, const ResId& ); virtual ~NUpTabPage(); void readFromSettings(); void storeToSettings(); + void initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& ); }; class JobTabPage : public TabPage diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index c42435344d34..4c512d056153 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -96,6 +96,20 @@ #define SV_PRINT_PRT_NUP_COLUMNS_EDT 5 #define SV_PRINT_PRT_NUP_PORTRAIT 6 #define SV_PRINT_PRT_NUP_LANDSCAPE 7 +#define SV_PRINT_PRT_NUP_MARGINS_FL 8 +#define SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT 9 +#define SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT 10 +#define SV_PRINT_PRT_NUP_MARGINS_TOP_TXT 11 +#define SV_PRINT_PRT_NUP_MARGINS_TOP_EDT 12 +#define SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT 13 +#define SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT 14 +#define SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT 15 +#define SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT 16 +#define SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT 17 +#define SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT 18 +#define SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT 19 +#define SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT 20 +#define SV_PRINT_PRT_NUP_BORDER_CB 21 #define SV_PRINT_TAB_JOB 2 #define SV_PRINT_PRINTERS 1 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e50b345c4a7f..e873b1cc068d 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -80,16 +80,12 @@ public: ControlDependencyMap maControlDependencies; sal_Bool mbLastPage; - int mnMultiPageRows; - int mnMultiPageColumns; - Size maMultiPageSize; + vcl::PrinterListener::MultiPageSetup maMultiPage; vcl::PrintProgressDialog* mpProgress; ImplPrinterListenerData() : mbLastPage( sal_False ), - mnMultiPageRows( 1 ), - mnMultiPageColumns( 1 ), mpProgress( NULL ) {} ~ImplPrinterListenerData() { delete mpProgress; } @@ -383,7 +379,6 @@ void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; Size aPaperSize( i_rPrinter->PixelToLogic( i_rPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); - mpImplData->maMultiPageSize = aPaperSize; } static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) @@ -446,7 +441,7 @@ Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) return aPageSize; } -static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GDIMetaFile& io_rSubPage ) +static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GDIMetaFile& io_rSubPage, bool i_bDrawBorder ) { // intersect all clipregion actions with our clip rect io_rSubPage.WindStart(); @@ -456,14 +451,17 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION | PUSH_MAPMODE ) ); // draw a border - Rectangle aBorderRect( i_rClipRect ); - aBorderRect.Left() -= 100; - aBorderRect.Top() -= 100; - aBorderRect.Right() += 100; - aBorderRect.Bottom() += 100; - o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); - o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); - o_rMtf.AddAction( new MetaRectAction( aBorderRect ) ); + if( i_bDrawBorder ) + { + Rectangle aBorderRect( i_rClipRect ); + aBorderRect.Left() -= 100; + aBorderRect.Top() -= 100; + aBorderRect.Right() += 100; + aBorderRect.Bottom() += 100; + o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); + o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); + o_rMtf.AddAction( new MetaRectAction( aBorderRect ) ); + } // clip to page rect o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); @@ -478,21 +476,36 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ) { - int nSubPages = mpImplData->mnMultiPageRows * mpImplData->mnMultiPageColumns; + const MultiPageSetup& rMPS( mpImplData->maMultiPage ); + int nSubPages = rMPS.nRows * rMPS.nColumns; if( nSubPages < 1 ) nSubPages = 1; - if( nSubPages == 1 ) + // there is no filtering to be done (and especially the page size of the + // original page is to be set), when N-Up is "neutral" that is there is + // only one subpage and the margins are 0 + if( nSubPages == 1 && + rMPS.nLeftMargin == 0 && rMPS.nRightMargin == 0 && + rMPS.nTopMargin == 0 && rMPS.nBottomMargin == 0 ) + { return getPageFile( i_nFilteredPage, o_rMtf ); + } - Size aPaperSize( mpImplData->maMultiPageSize ); + Size aPaperSize( mpImplData->maMultiPage.aPaperSize ); + // multi page area: paper size minus margins + one time spacing right and down + // the added spacing is so each subpage can be calculated including its spacing + Size aMPArea( aPaperSize ); + aMPArea.Width() -= rMPS.nLeftMargin + rMPS.nRightMargin; + aMPArea.Width() += rMPS.nHorizontalSpacing; + aMPArea.Height() -= rMPS.nTopMargin + rMPS.nBottomMargin; + aMPArea.Height() += rMPS.nVerticalSpacing; // determine offsets - long nAdvX = aPaperSize.Width() / mpImplData->mnMultiPageColumns; - long nAdvY = aPaperSize.Height() / mpImplData->mnMultiPageRows; + long nAdvX = aMPArea.Width() / rMPS.nColumns; + long nAdvY = aMPArea.Height() / rMPS.nRows; // determine size of a "cell" subpage, leave a little space around pages - Size aSubPageSize( nAdvX - 500, nAdvY - 500 ); + Size aSubPageSize( nAdvX - rMPS.nHorizontalSpacing, nAdvY - rMPS.nVerticalSpacing ); o_rMtf.Clear(); o_rMtf.SetPrefSize( aPaperSize ); @@ -516,10 +529,10 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r aPageFile.WindStart(); // move the subpage so it is centered in its "cell" - long nOffX = (nAdvX - long(double(aPageSize.Width()) * fScale)) / 2; - long nOffY = (nAdvY - long(double(aPageSize.Height()) * fScale)) / 2; - long nX = nOffX + nAdvX * (nSubP % mpImplData->mnMultiPageColumns); - long nY = nOffY + nAdvY * (nSubP / mpImplData->mnMultiPageColumns); + long nOffX = (aSubPageSize.Width() - long(double(aPageSize.Width()) * fScale)) / 2; + long nOffY = (aSubPageSize.Height() - long(double(aPageSize.Height()) * fScale)) / 2; + long nX = rMPS.nLeftMargin + nOffX + nAdvX * (nSubP % rMPS.nColumns); + long nY = rMPS.nTopMargin + nOffY + nAdvY * (nSubP / rMPS.nColumns); aPageFile.Move( nX, nY ); aPageFile.WindStart(); // calculate border rectangle @@ -528,7 +541,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r long(double(aPageSize.Height())*fScale) ) ); // append subpage to page - appendSubPage( o_rMtf, aSubPageRect, aPageFile ); + appendSubPage( o_rMtf, aSubPageRect, aPageFile, rMPS.bDrawBorder ); } } o_rMtf.WindStart(); @@ -538,7 +551,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r int PrinterListener::getFilteredPageCount() { - int nDiv = mpImplData->mnMultiPageRows * mpImplData->mnMultiPageColumns; + int nDiv = mpImplData->maMultiPage.nRows * mpImplData->maMultiPage.nColumns; if( nDiv < 1 ) nDiv = 1; return (getPageCount() + (nDiv-1)) / nDiv; @@ -556,7 +569,7 @@ void PrinterListener::printFilteredPage( int i_nPage ) return; } - bool bMultiPageOutput = mpImplData->mnMultiPageRows != 1 || mpImplData->mnMultiPageColumns != 1; + bool bMultiPageOutput = mpImplData->maMultiPage.nRows != 1 || mpImplData->maMultiPage.nColumns != 1; ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); @@ -613,7 +626,7 @@ void PrinterListener::printFilteredPage( int i_nPage ) // in N-Up printing set the correct page size mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); if( bMultiPageOutput ) - mpImplData->mpPrinter->SetPaperSizeUser( aPageSize = mpImplData->maMultiPageSize ); + mpImplData->mpPrinter->SetPaperSizeUser( aPageSize = mpImplData->maMultiPage.aPaperSize ); // actually print the page mpImplData->mpPrinter->StartPage(); @@ -830,11 +843,14 @@ void PrinterListener::createProgressDialog() } } -void PrinterListener::setMultipage( int i_nRows, int i_nColumns, const Size& rPaperSize ) +void PrinterListener::setMultipage( const MultiPageSetup& i_rMPS ) +{ + mpImplData->maMultiPage = i_rMPS; +} + +const PrinterListener::MultiPageSetup& PrinterListener::getMultipage() const { - mpImplData->mnMultiPageRows = i_nRows; - mpImplData->mnMultiPageColumns = i_nColumns; - mpImplData->maMultiPageSize = rPaperSize; + return mpImplData->maMultiPage; } /* diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 58d8010f0a2c..148af441b8ec 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -124,19 +124,19 @@ ModalDialog SV_DLG_PRINT FixedLine SV_PRINT_PRT_NUP { - Pos = MAP_APPFONT( 5, 10 ); + Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "N-Up printing"; }; FixedText SV_PRINT_PRT_NUP_ROWS_TXT { - Pos = MAP_APPFONT( 10, 25 ); + Pos = MAP_APPFONT( 10, 20 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Rows"; }; NumericField SV_PRINT_PRT_NUP_ROWS_EDT { - Pos = MAP_APPFONT( 55, 25 ); + Pos = MAP_APPFONT( 55, 20 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -146,13 +146,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_COLUMNS_TXT { - Pos = MAP_APPFONT( 10, 50 ); + Pos = MAP_APPFONT( 10, 35 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "C~olumns"; }; NumericField SV_PRINT_PRT_NUP_COLUMNS_EDT { - Pos = MAP_APPFONT( 55, 50 ); + Pos = MAP_APPFONT( 55, 35 ); Size = MAP_APPFONT( 40, 12 ); Border = TRUE; Spin = TRUE; @@ -160,18 +160,121 @@ ModalDialog SV_DLG_PRINT Maximum = 32; Value = 1; }; + CheckBox SV_PRINT_PRT_NUP_BORDER_CB + { + Pos = MAP_APPFONT( 10, 50 ); + Size = MAP_APPFONT( 150, 12 ); + Text [en-US] = "~Draw a Border around each page"; + }; RadioButton SV_PRINT_PRT_NUP_PORTRAIT { - Pos = MAP_APPFONT( 110, 25 ); + Pos = MAP_APPFONT( 110, 20 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "Po~rtrait"; }; RadioButton SV_PRINT_PRT_NUP_LANDSCAPE { - Pos = MAP_APPFONT( 110, 35 ); + Pos = MAP_APPFONT( 110, 30 ); Size = MAP_APPFONT( 90, 10 ); Text [en-US] = "~Landscape"; }; + FixedLine SV_PRINT_PRT_NUP_MARGINS_FL + { + Pos = MAP_APPFONT( 5, 65 ); + Size = MAP_APPFONT( 150, 10 ); + Text [en-US] = "Margins"; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT + { + Pos = MAP_APPFONT( 10, 80 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Left"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT + { + Pos = MAP_APPFONT( 55, 80 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT + { + Pos = MAP_APPFONT( 110, 80 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Right"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT + { + Pos = MAP_APPFONT( 155, 80 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_TOP_TXT + { + Pos = MAP_APPFONT( 10, 95 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Top"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_TOP_EDT + { + Pos = MAP_APPFONT( 55, 95 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT + { + Pos = MAP_APPFONT( 110, 95 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Bottom"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT + { + Pos = MAP_APPFONT( 155, 95 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; + + FixedText SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT + { + Pos = MAP_APPFONT( 10, 115 ); + Size = MAP_APPFONT( 80, 10 ); + Text [en-US] = "~Horizontal spacing"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT + { + Pos = MAP_APPFONT( 95, 115 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT + { + Pos = MAP_APPFONT( 10, 130 ); + Size = MAP_APPFONT( 80, 10 ); + Text [en-US] = "~Vertical spacing"; + }; + MetricField SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT + { + Pos = MAP_APPFONT( 95, 130 ); + Size = MAP_APPFONT( 40, 12 ); + Spin = TRUE; + Border = TRUE; + Value = 0; + Unit = FUNIT_MM; + }; }; TabPage SV_PRINT_TAB_JOB diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index e94b0803df4a..14bd0eb1c26d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -115,8 +115,22 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) , maNupColTxt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_TXT ) ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_EDT ) ) + , maBorderCB( this, VclResId( SV_PRINT_PRT_NUP_BORDER_CB ) ) , maNupPortrait( this, VclResId( SV_PRINT_PRT_NUP_PORTRAIT ) ) , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) + , maMargins( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_FL ) ) + , maLeftMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT ) ) + , maLeftMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT) ) + , maRightMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT ) ) + , maRightMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT ) ) + , maTopMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_TOP_TXT ) ) + , maTopMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_TOP_EDT ) ) + , maBottomMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT ) ) + , maBottomMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT ) ) + , maHSpaceTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT ) ) + , maHSpaceEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT ) ) + , maVSpaceTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT ) ) + , maVSpaceEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT ) ) { FreeResource(); maNupLine.SMHID2( "NUpPage", "NUPline" ); @@ -126,14 +140,42 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maNupColEdt.SMHID2( "NUpPage", "NUPColumns" ); maNupPortrait.SMHID2( "NUpPage", "NUPPortrait" ); maNupLandscape.SMHID2( "NUpPage", "NUPLandscape" ); + maBorderCB.SMHID2( "NUpPage", "NUPBorder" ); + maMargins.SMHID2( "NUpPage", "NUPMargins" ); + maLeftMarginTxt.SMHID2( "NUpPage", "NUPLeftText" ); + maLeftMarginEdt.SMHID2( "NUpPage", "NUPLeft" ); + maTopMarginTxt.SMHID2( "NUpPage", "NUPTopText" ); + maTopMarginEdt.SMHID2( "NUpPage", "NUPTop" ); + maRightMarginTxt.SMHID2( "NUpPage", "NUPRightText" ); + maRightMarginEdt.SMHID2( "NUpPage", "NUPRight" ); + maBottomMarginTxt.SMHID2( "NUpPage", "NUPBottomText" ); + maBottomMarginEdt.SMHID2( "NUpPage", "NUPBottom" ); + maHSpaceTxt.SMHID2( "NUpPage", "NUPHSpaceText" ); + maHSpaceEdt.SMHID2( "NUpPage", "NUPHSpace" ); + maVSpaceTxt.SMHID2( "NUpPage", "NUPVSpaceText" ); + maVSpaceEdt.SMHID2( "NUpPage", "NUPVSpace" ); } PrintDialog::NUpTabPage::~NUpTabPage() { } +void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& i_rMPS ) +{ + maLeftMarginEdt.SetValue( i_rMPS.nLeftMargin, FUNIT_100TH_MM ); + maTopMarginEdt.SetValue( i_rMPS.nTopMargin, FUNIT_100TH_MM ); + maRightMarginEdt.SetValue( i_rMPS.nRightMargin, FUNIT_100TH_MM ); + maBottomMarginEdt.SetValue( i_rMPS.nBottomMargin, FUNIT_100TH_MM ); + maHSpaceEdt.SetValue( i_rMPS.nHorizontalSpacing, FUNIT_100TH_MM ); + maVSpaceEdt.SetValue( i_rMPS.nVerticalSpacing, FUNIT_100TH_MM ); + maBorderCB.Check( i_rMPS.bDrawBorder ); + maNupRowsEdt.SetValue( i_rMPS.nRows ); + maNupColEdt.SetValue( i_rMPS.nColumns ); +} + void PrintDialog::NUpTabPage::readFromSettings() { + #if 0 SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; @@ -153,10 +195,12 @@ void PrintDialog::NUpTabPage::readFromSettings() maNupPortrait.Check(); else maNupLandscape.Check(); + #endif } void PrintDialog::NUpTabPage::storeToSettings() { + #if 0 SettingsConfigItem* pItem = SettingsConfigItem::get(); pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ), @@ -167,6 +211,7 @@ void PrintDialog::NUpTabPage::storeToSettings() pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ), rtl::OUString::createFromAscii( maNupPortrait.IsChecked() ? "true" : "false" ) ); + #endif } PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) @@ -208,10 +253,14 @@ void PrintDialog::JobTabPage::readFromSettings() rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); + #if 0 + // do not actually make copy count persistent + // the assumption is that this would lead to a lot of unwanted copies aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Copies" ) ) ); sal_Int32 nVal = aValue.toInt32(); maCopyCountField.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); + #endif aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); @@ -336,6 +385,8 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetMultipage() ); + // setup click handler on the various buttons maOKButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); @@ -348,12 +399,19 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetMultipage( nRows, nCols, - maNUpPage.maNupPortrait.IsChecked() - ? maNupPortraitSize : maNupLandscapeSize ); + PrinterListener::MultiPageSetup aMPS; + aMPS.nRows = nRows; + aMPS.nColumns = nCols; + aMPS.aPaperSize = maNUpPage.maNupPortrait.IsChecked() + ? maNupPortraitSize : maNupLandscapeSize; + aMPS.nLeftMargin = long(maNUpPage.maLeftMarginEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nTopMargin = long(maNUpPage.maTopMarginEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nRightMargin = long(maNUpPage.maRightMarginEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nBottomMargin = long(maNUpPage.maBottomMarginEdt.GetValue( FUNIT_100TH_MM )); + + aMPS.nHorizontalSpacing = long(maNUpPage.maHSpaceEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nVerticalSpacing = long(maNUpPage.maVSpaceEdt.GetValue( FUNIT_100TH_MM )); + + aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); + + maPListener->setMultipage( aMPS ); preparePreview(); } @@ -1123,7 +1194,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maPListener->getPrinter()->Setup( this ); } checkControlDependencies(); - if( pButton == &maNUpPage.maNupPortrait || pButton == &maNUpPage.maNupLandscape ) + if( pButton == &maNUpPage.maNupPortrait || pButton == &maNUpPage.maNupLandscape || pButton == &maNUpPage.maBorderCB ) updateNup(); } return 0; @@ -1132,7 +1203,11 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { checkControlDependencies(); - if( pEdit == &maNUpPage.maNupRowsEdt || pEdit == &maNUpPage.maNupColEdt ) + if( pEdit == &maNUpPage.maNupRowsEdt || pEdit == &maNUpPage.maNupColEdt || + pEdit == &maNUpPage.maLeftMarginEdt || pEdit == &maNUpPage.maTopMarginEdt || + pEdit == &maNUpPage.maRightMarginEdt || pEdit == &maNUpPage.maBottomMarginEdt || + pEdit == &maNUpPage.maHSpaceEdt || pEdit == &maNUpPage.maVSpaceEdt + ) { updateNup(); } -- cgit From 706d4c761e10840fc03458896a0360c514b6cae1 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 10 Jun 2009 12:10:29 +0000 Subject: locale dependent metric field unit --- vcl/source/window/printdlg.cxx | 52 ++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 14bd0eb1c26d..a79537aacf27 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -45,6 +45,8 @@ #include "vcl/help.hxx" #include "vcl/decoview.hxx" +#include "unotools/localedatawrapper.hxx" + #include "rtl/ustrbuf.hxx" #include "com/sun/star/awt/Size.hpp" @@ -133,6 +135,32 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maVSpaceEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT ) ) { FreeResource(); + + // setup field units for metric fields + const LocaleDataWrapper& rLocWrap( maLeftMarginEdt.GetLocaleDataWrapper() ); + FieldUnit eUnit = FUNIT_MM; + USHORT nDigits = 0; + if( rLocWrap.getMeasurementSystemEnum() == MEASURE_US ) + { + eUnit = FUNIT_INCH; + nDigits = 2; + } + // set units + maLeftMarginEdt.SetUnit( eUnit ); + maTopMarginEdt.SetUnit( eUnit ); + maRightMarginEdt.SetUnit( eUnit ); + maBottomMarginEdt.SetUnit( eUnit ); + maHSpaceEdt.SetUnit( eUnit ); + maVSpaceEdt.SetUnit( eUnit ); + + // set precision + maLeftMarginEdt.SetDecimalDigits( nDigits ); + maTopMarginEdt.SetDecimalDigits( nDigits ); + maRightMarginEdt.SetDecimalDigits( nDigits ); + maBottomMarginEdt.SetDecimalDigits( nDigits ); + maHSpaceEdt.SetDecimalDigits( nDigits ); + maVSpaceEdt.SetDecimalDigits( nDigits ); + maNupLine.SMHID2( "NUpPage", "NUPline" ); maNupRowsTxt.SMHID2( "NUpPage", "NUPRowsText" ); maNupRowsEdt.SMHID2( "NUpPage", "NUPRows" ); @@ -162,12 +190,12 @@ PrintDialog::NUpTabPage::~NUpTabPage() void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& i_rMPS ) { - maLeftMarginEdt.SetValue( i_rMPS.nLeftMargin, FUNIT_100TH_MM ); - maTopMarginEdt.SetValue( i_rMPS.nTopMargin, FUNIT_100TH_MM ); - maRightMarginEdt.SetValue( i_rMPS.nRightMargin, FUNIT_100TH_MM ); - maBottomMarginEdt.SetValue( i_rMPS.nBottomMargin, FUNIT_100TH_MM ); - maHSpaceEdt.SetValue( i_rMPS.nHorizontalSpacing, FUNIT_100TH_MM ); - maVSpaceEdt.SetValue( i_rMPS.nVerticalSpacing, FUNIT_100TH_MM ); + maLeftMarginEdt.SetValue( maLeftMarginEdt.Normalize( i_rMPS.nLeftMargin ), FUNIT_100TH_MM ); + maTopMarginEdt.SetValue( maTopMarginEdt.Normalize( i_rMPS.nTopMargin ), FUNIT_100TH_MM ); + maRightMarginEdt.SetValue( maRightMarginEdt.Normalize( i_rMPS.nRightMargin ), FUNIT_100TH_MM ); + maBottomMarginEdt.SetValue( maBottomMarginEdt.Normalize( i_rMPS.nBottomMargin ), FUNIT_100TH_MM ); + maHSpaceEdt.SetValue( maHSpaceEdt.Normalize( i_rMPS.nHorizontalSpacing ), FUNIT_100TH_MM ); + maVSpaceEdt.SetValue( maVSpaceEdt.Normalize( i_rMPS.nVerticalSpacing ), FUNIT_100TH_MM ); maBorderCB.Check( i_rMPS.bDrawBorder ); maNupRowsEdt.SetValue( i_rMPS.nRows ); maNupColEdt.SetValue( i_rMPS.nColumns ); @@ -1143,13 +1171,13 @@ void PrintDialog::updateNup() aMPS.nColumns = nCols; aMPS.aPaperSize = maNUpPage.maNupPortrait.IsChecked() ? maNupPortraitSize : maNupLandscapeSize; - aMPS.nLeftMargin = long(maNUpPage.maLeftMarginEdt.GetValue( FUNIT_100TH_MM )); - aMPS.nTopMargin = long(maNUpPage.maTopMarginEdt.GetValue( FUNIT_100TH_MM )); - aMPS.nRightMargin = long(maNUpPage.maRightMarginEdt.GetValue( FUNIT_100TH_MM )); - aMPS.nBottomMargin = long(maNUpPage.maBottomMarginEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nLeftMargin = long(maNUpPage.maLeftMarginEdt.Denormalize(maNUpPage.maLeftMarginEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nTopMargin = long(maNUpPage.maTopMarginEdt.Denormalize(maNUpPage.maTopMarginEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nRightMargin = long(maNUpPage.maRightMarginEdt.Denormalize(maNUpPage.maRightMarginEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nBottomMargin = long(maNUpPage.maBottomMarginEdt.Denormalize(maNUpPage.maBottomMarginEdt.GetValue( FUNIT_100TH_MM ))); - aMPS.nHorizontalSpacing = long(maNUpPage.maHSpaceEdt.GetValue( FUNIT_100TH_MM )); - aMPS.nVerticalSpacing = long(maNUpPage.maVSpaceEdt.GetValue( FUNIT_100TH_MM )); + aMPS.nHorizontalSpacing = long(maNUpPage.maHSpaceEdt.Denormalize(maNUpPage.maHSpaceEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nVerticalSpacing = long(maNUpPage.maVSpaceEdt.Denormalize(maNUpPage.maVSpaceEdt.GetValue( FUNIT_100TH_MM ))); aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); -- cgit From 2651918016923f6f9cd617aa84c1b7d40c1ed914 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 10 Jun 2009 12:18:55 +0000 Subject: avoid overpainting of border --- vcl/source/window/printdlg.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index a79537aacf27..121278bf21df 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1428,9 +1428,9 @@ void PrintDialog::Resize() aPrefSize.Width() = nPreviewLength - 2* aPixDiff.Width(); Point aCtrlPos( 2*aPixDiff.Width(), 3*aPixDiff.Height() + nPreviewLength ); maPreviewCtrlRow.setManagedArea( Rectangle( aCtrlPos, aPrefSize ) ); - maPreviewBackground.Left() = aPixDiff.Width(); - maPreviewBackground.Top() = aPixDiff.Height(); - maPreviewBackground.Right() = aPixDiff.Width() + nPreviewLength; + maPreviewBackground.Left() = aPixDiff.Width() - 2; + maPreviewBackground.Top() = aPixDiff.Height() - 2; + maPreviewBackground.Right() = aPixDiff.Width() + nPreviewLength + 2; maPreviewBackground.Bottom() = maPreviewCtrlRow.getManagedArea().Bottom() + aPixDiff.Height(); // and do the preview; however the metafile does not need to be gotten anew -- cgit From 00f2ce881250398b2eb892deac038aa85fbf1636 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 10 Jun 2009 13:22:04 +0000 Subject: add: page repeat for N-Up --- vcl/inc/vcl/print.hxx | 3 ++- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/inc/vcl/svids.hrc | 2 ++ vcl/source/gdi/print3.cxx | 59 ++++++++++++++++++++++-------------------- vcl/source/src/print.src | 54 ++++++++++++++++++++++++-------------- vcl/source/window/printdlg.cxx | 14 +++++++--- 6 files changed, 83 insertions(+), 51 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 6d63d7a6ab23..8b5d711d129f 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -451,6 +451,7 @@ public: // all metrics in 100th mm int nRows; int nColumns; + int nRepeat; Size aPaperSize; long nLeftMargin; long nTopMargin; @@ -461,7 +462,7 @@ public: bool bDrawBorder; MultiPageSetup() - : nRows( 1 ), nColumns( 1 ), aPaperSize( 21000, 29700 ) + : nRows( 1 ), nColumns( 1 ), nRepeat( 1 ), aPaperSize( 21000, 29700 ) , nLeftMargin( 0 ), nTopMargin( 0 ) , nRightMargin( 0 ), nBottomMargin( 0 ) , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 384dcd2451e3..4d1ead6018e2 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -86,6 +86,8 @@ namespace vcl NumericField maNupRowsEdt; FixedText maNupColTxt; NumericField maNupColEdt; + FixedText maNupRepTxt; + NumericField maNupRepEdt; CheckBox maBorderCB; RadioButton maNupPortrait; RadioButton maNupLandscape; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 4c512d056153..0edbd5661335 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -110,6 +110,8 @@ #define SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT 19 #define SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT 20 #define SV_PRINT_PRT_NUP_BORDER_CB 21 +#define SV_PRINT_PRT_NUP_PAGEREPEAT_TXT 22 +#define SV_PRINT_PRT_NUP_PAGEREPEAT_EDT 23 #define SV_PRINT_TAB_JOB 2 #define SV_PRINT_PRINTERS 1 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e873b1cc068d..00fda02135a3 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -513,35 +513,38 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r o_rMtf.AddAction( new MetaMapModeAction( MapMode( MAP_100TH_MM ) ) ); int nDocPages = getPageCount(); - for( int nPage = i_nFilteredPage * nSubPages, nSubP = 0; - nPage < (i_nFilteredPage+1)*nSubPages && nPage < nDocPages; - nPage++, nSubP++ ) + for( int nSubPage = 0; nSubPage < nSubPages; nSubPage++ ) { - GDIMetaFile aPageFile; - Size aPageSize = getPageFile( nPage, aPageFile ); - if( aPageSize.Width() && aPageSize.Height() ) + // map current sub page to real page + int nPage = (i_nFilteredPage * nSubPages + nSubPage) / rMPS.nRepeat; + if( nPage < nDocPages ) { - // scale the metafile down to a sub page size - double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); - double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); - double fScale = std::min( fScaleX, fScaleY ); - aPageFile.Scale( fScale, fScale ); - aPageFile.WindStart(); - - // move the subpage so it is centered in its "cell" - long nOffX = (aSubPageSize.Width() - long(double(aPageSize.Width()) * fScale)) / 2; - long nOffY = (aSubPageSize.Height() - long(double(aPageSize.Height()) * fScale)) / 2; - long nX = rMPS.nLeftMargin + nOffX + nAdvX * (nSubP % rMPS.nColumns); - long nY = rMPS.nTopMargin + nOffY + nAdvY * (nSubP / rMPS.nColumns); - aPageFile.Move( nX, nY ); - aPageFile.WindStart(); - // calculate border rectangle - Rectangle aSubPageRect( Point( nX, nY ), - Size( long(double(aPageSize.Width())*fScale), - long(double(aPageSize.Height())*fScale) ) ); - - // append subpage to page - appendSubPage( o_rMtf, aSubPageRect, aPageFile, rMPS.bDrawBorder ); + GDIMetaFile aPageFile; + Size aPageSize = getPageFile( nPage, aPageFile ); + if( aPageSize.Width() && aPageSize.Height() ) + { + // scale the metafile down to a sub page size + double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); + double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); + double fScale = std::min( fScaleX, fScaleY ); + aPageFile.Scale( fScale, fScale ); + aPageFile.WindStart(); + + // move the subpage so it is centered in its "cell" + long nOffX = (aSubPageSize.Width() - long(double(aPageSize.Width()) * fScale)) / 2; + long nOffY = (aSubPageSize.Height() - long(double(aPageSize.Height()) * fScale)) / 2; + long nX = rMPS.nLeftMargin + nOffX + nAdvX * (nSubPage % rMPS.nColumns); + long nY = rMPS.nTopMargin + nOffY + nAdvY * (nSubPage / rMPS.nColumns); + aPageFile.Move( nX, nY ); + aPageFile.WindStart(); + // calculate border rectangle + Rectangle aSubPageRect( Point( nX, nY ), + Size( long(double(aPageSize.Width())*fScale), + long(double(aPageSize.Height())*fScale) ) ); + + // append subpage to page + appendSubPage( o_rMtf, aSubPageRect, aPageFile, rMPS.bDrawBorder ); + } } } o_rMtf.WindStart(); @@ -554,7 +557,7 @@ int PrinterListener::getFilteredPageCount() int nDiv = mpImplData->maMultiPage.nRows * mpImplData->maMultiPage.nColumns; if( nDiv < 1 ) nDiv = 1; - return (getPageCount() + (nDiv-1)) / nDiv; + return (getPageCount() * mpImplData->maMultiPage.nRepeat + (nDiv-1)) / nDiv; } void PrinterListener::printFilteredPage( int i_nPage ) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 148af441b8ec..d629ba7c04d2 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -38,18 +38,18 @@ ModalDialog SV_DLG_PRINT Moveable = TRUE; SVLook = TRUE; - Size = MAP_APPFONT( 350, 205 ); + Size = MAP_APPFONT( 350, 215 ); OKButton SV_PRINT_OK { DefButton = TRUE; - Pos = MAP_APPFONT( 240, 185 ); + Pos = MAP_APPFONT( 240, 195 ); Size = MAP_APPFONT( 50, 15 ); Text [en-US] = "~Print"; }; CancelButton SV_PRINT_CANCEL { - Pos = MAP_APPFONT( 295, 185 ); + Pos = MAP_APPFONT( 295, 195 ); Size = MAP_APPFONT( 50, 15 ); }; @@ -87,12 +87,12 @@ ModalDialog SV_DLG_PRINT TabControl SV_PRINT_TABCTRL { Pos = MAP_APPFONT( 140, 5 ); - Size = MAP_APPFONT( 205, 165 ); + Size = MAP_APPFONT( 205, 175 ); // DropDown = TRUE; }; FixedLine SV_PRINT_BUTTONLINE { - Pos = MAP_APPFONT( 0, 175 ); + Pos = MAP_APPFONT( 0, 185 ); Size = MAP_APPFONT( 350, 8 ); }; String SV_PRINT_NOPAGES @@ -160,9 +160,25 @@ ModalDialog SV_DLG_PRINT Maximum = 32; Value = 1; }; - CheckBox SV_PRINT_PRT_NUP_BORDER_CB + FixedText SV_PRINT_PRT_NUP_PAGEREPEAT_TXT { Pos = MAP_APPFONT( 10, 50 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "~Repeat"; + }; + NumericField SV_PRINT_PRT_NUP_PAGEREPEAT_EDT + { + Pos = MAP_APPFONT( 55, 50 ); + Size = MAP_APPFONT( 40, 12 ); + Border = TRUE; + Spin = TRUE; + Minimum = 1; + Maximum = 32; + Value = 1; + }; + CheckBox SV_PRINT_PRT_NUP_BORDER_CB + { + Pos = MAP_APPFONT( 10, 65 ); Size = MAP_APPFONT( 150, 12 ); Text [en-US] = "~Draw a Border around each page"; }; @@ -180,19 +196,19 @@ ModalDialog SV_DLG_PRINT }; FixedLine SV_PRINT_PRT_NUP_MARGINS_FL { - Pos = MAP_APPFONT( 5, 65 ); + Pos = MAP_APPFONT( 5, 80 ); Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Margins"; }; FixedText SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT { - Pos = MAP_APPFONT( 10, 80 ); + Pos = MAP_APPFONT( 10, 95 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Left"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT { - Pos = MAP_APPFONT( 55, 80 ); + Pos = MAP_APPFONT( 55, 95 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; @@ -201,13 +217,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT { - Pos = MAP_APPFONT( 110, 80 ); + Pos = MAP_APPFONT( 110, 95 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Right"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT { - Pos = MAP_APPFONT( 155, 80 ); + Pos = MAP_APPFONT( 155, 95 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; @@ -216,13 +232,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_MARGINS_TOP_TXT { - Pos = MAP_APPFONT( 10, 95 ); + Pos = MAP_APPFONT( 10, 110 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Top"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_TOP_EDT { - Pos = MAP_APPFONT( 55, 95 ); + Pos = MAP_APPFONT( 55, 110 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; @@ -231,13 +247,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT { - Pos = MAP_APPFONT( 110, 95 ); + Pos = MAP_APPFONT( 110, 110 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~Bottom"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT { - Pos = MAP_APPFONT( 155, 95 ); + Pos = MAP_APPFONT( 155, 110 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; @@ -247,13 +263,13 @@ ModalDialog SV_DLG_PRINT FixedText SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT { - Pos = MAP_APPFONT( 10, 115 ); + Pos = MAP_APPFONT( 10, 130 ); Size = MAP_APPFONT( 80, 10 ); Text [en-US] = "~Horizontal spacing"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT { - Pos = MAP_APPFONT( 95, 115 ); + Pos = MAP_APPFONT( 95, 130 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; @@ -262,13 +278,13 @@ ModalDialog SV_DLG_PRINT }; FixedText SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT { - Pos = MAP_APPFONT( 10, 130 ); + Pos = MAP_APPFONT( 10, 145 ); Size = MAP_APPFONT( 80, 10 ); Text [en-US] = "~Vertical spacing"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT { - Pos = MAP_APPFONT( 95, 130 ); + Pos = MAP_APPFONT( 95, 145 ); Size = MAP_APPFONT( 40, 12 ); Spin = TRUE; Border = TRUE; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 121278bf21df..6d9772f8b5f2 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -117,6 +117,8 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) , maNupColTxt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_TXT ) ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_EDT ) ) + , maNupRepTxt( this, VclResId( SV_PRINT_PRT_NUP_PAGEREPEAT_TXT ) ) + , maNupRepEdt( this, VclResId( SV_PRINT_PRT_NUP_PAGEREPEAT_EDT ) ) , maBorderCB( this, VclResId( SV_PRINT_PRT_NUP_BORDER_CB ) ) , maNupPortrait( this, VclResId( SV_PRINT_PRT_NUP_PORTRAIT ) ) , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) @@ -166,6 +168,8 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maNupRowsEdt.SMHID2( "NUpPage", "NUPRows" ); maNupColTxt.SMHID2( "NUpPage", "NUPColumnsText" ); maNupColEdt.SMHID2( "NUpPage", "NUPColumns" ); + maNupRepTxt.SMHID2( "NUpPage", "NUPRepeatText" ); + maNupRepEdt.SMHID2( "NUpPage", "NUPRepeat" ); maNupPortrait.SMHID2( "NUpPage", "NUPPortrait" ); maNupLandscape.SMHID2( "NUpPage", "NUPLandscape" ); maBorderCB.SMHID2( "NUpPage", "NUPBorder" ); @@ -199,6 +203,7 @@ void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterListener maBorderCB.Check( i_rMPS.bDrawBorder ); maNupRowsEdt.SetValue( i_rMPS.nRows ); maNupColEdt.SetValue( i_rMPS.nColumns ); + maNupRepEdt.SetValue( i_rMPS.nRepeat ); } void PrintDialog::NUpTabPage::readFromSettings() @@ -434,6 +439,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Wed, 10 Jun 2009 17:21:10 +0000 Subject: page cache for faster preview --- vcl/inc/vcl/print.hxx | 4 +- vcl/inc/vcl/prndlg.hxx | 2 +- vcl/source/gdi/print3.cxx | 98 ++++++++++++++++++++++++++++++++++++++++-- vcl/source/window/printdlg.cxx | 10 ++--- 4 files changed, 102 insertions(+), 12 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 8b5d711d129f..5e9f0834c574 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -516,8 +516,8 @@ public: // implementation details, not usable outside vcl int SAL_DLLPRIVATE getFilteredPageCount(); - Size SAL_DLLPRIVATE getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf ); - Size SAL_DLLPRIVATE getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ); + Size SAL_DLLPRIVATE getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); + Size SAL_DLLPRIVATE getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache = false ); void SAL_DLLPRIVATE printFilteredPage( int i_nPage ); void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 4d1ead6018e2..c2e8beaa16e9 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -180,7 +180,7 @@ namespace vcl Rectangle maPreviewBackground; void updateNup(); - void preparePreview( bool i_bPrintChanged = true ); + void preparePreview( bool i_bPrintChanged = true, bool i_bMayUseCache = false ); void setPreviewText( sal_Int32 ); void updatePrinterText(); void checkControlDependencies(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 00fda02135a3..1ef2e18b996a 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -57,6 +57,79 @@ using namespace com::sun::star::uno; using namespace com::sun::star::beans; using namespace vcl; +class ImplPageCache +{ + std::vector< GDIMetaFile > maPages; + std::vector< sal_Int32 > maPageNumbers; + std::vector< sal_Int32 > maCacheRanking; + + static const sal_Int32 nCacheSize = 6; + + void updateRanking( sal_Int32 nLastHit ) + { + if( maCacheRanking[0] != nLastHit ) + { + bool bMove = false; + for( sal_Int32 i = nCacheSize-1; i > 0; i-- ) + { + if( maCacheRanking[i] == nLastHit ) + bMove = true; + maCacheRanking[i] = maCacheRanking[i-1]; + } + maCacheRanking[0] = nLastHit; + } + } + +public: + ImplPageCache() + : maPages( nCacheSize ) + , maPageNumbers( nCacheSize, -1 ) + , maCacheRanking( nCacheSize ) + { + for( sal_Int32 i = 0; i < nCacheSize; i++ ) + maCacheRanking[i] = nCacheSize - i - 1; + } + + // caution: does not ensure uniqueness + void insert( sal_Int32 i_nPageNo, const GDIMetaFile& i_rPage ) + { + sal_Int32 nReplacePage = maCacheRanking.back(); + maPages[ nReplacePage ] = i_rPage; + maPageNumbers[ nReplacePage ] = i_nPageNo; + // cache insertion means in our case, the page was just queried + // so update the ranking + updateRanking( nReplacePage ); + } + + // caution: bad algorithm; should there ever be reason to increase the cache size beyond 6 + // this needs to be urgently rewritten. However do NOT increase the cache size lightly, + // whole pages can be rather memory intensive + const GDIMetaFile* get( sal_Int32 i_nPageNo ) + { + const GDIMetaFile* pRet = NULL; + for( sal_Int32 i = 0; i < nCacheSize; ++i ) + { + if( maPageNumbers[i] == i_nPageNo ) + { + updateRanking( i ); + pRet = &maPages[i]; + break; + } + } + return pRet; + } + + void invalidate() + { + for( sal_Int32 i = 0; i < nCacheSize; ++i ) + { + maPageNumbers[i] = -1; + maPages[i].Clear(); + maCacheRanking[i] = nCacheSize - i - 1; + } + } +}; + class vcl::ImplPrinterListenerData { public: @@ -84,6 +157,8 @@ public: vcl::PrintProgressDialog* mpProgress; + ImplPageCache maPageCache; + ImplPrinterListenerData() : mbLastPage( sal_False ), mpProgress( NULL ) @@ -401,7 +476,7 @@ static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& return aPageSize; } -Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) +Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { // update progress if necessary if( mpImplData->mpProgress ) @@ -413,6 +488,18 @@ Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) Application::Reschedule( true ); } + if( i_bMayUseCache ) + { + const GDIMetaFile* pCached = mpImplData->maPageCache.get( i_nUnfilteredPage ); + if( pCached ) + { + o_rMtf = *pCached; + return pCached->GetPrefSize(); + } + } + else + mpImplData->maPageCache.invalidate(); + o_rMtf.Clear(); // get page parameters @@ -438,6 +525,9 @@ Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf ) o_rMtf.WindStart(); mpImplData->mpPrinter->Pop(); + if( i_bMayUseCache ) + mpImplData->maPageCache.insert( i_nUnfilteredPage, o_rMtf ); + return aPageSize; } @@ -474,7 +564,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD o_rMtf.AddAction( new MetaPopAction() ); } -Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf ) +Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { const MultiPageSetup& rMPS( mpImplData->maMultiPage ); int nSubPages = rMPS.nRows * rMPS.nColumns; @@ -488,7 +578,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r rMPS.nLeftMargin == 0 && rMPS.nRightMargin == 0 && rMPS.nTopMargin == 0 && rMPS.nBottomMargin == 0 ) { - return getPageFile( i_nFilteredPage, o_rMtf ); + return getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); } Size aPaperSize( mpImplData->maMultiPage.aPaperSize ); @@ -520,7 +610,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r if( nPage < nDocPages ) { GDIMetaFile aPageFile; - Size aPageSize = getPageFile( nPage, aPageFile ); + Size aPageSize = getPageFile( nPage, aPageFile, i_bMayUseCache ); if( aPageSize.Width() && aPageSize.Height() ) { // scale the metafile down to a sub page size diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 6d9772f8b5f2..7bc771e7493e 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -365,7 +365,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& rQueues( Printer::GetPrinterQueues() ); @@ -1114,7 +1114,7 @@ void PrintDialog::setPreviewText( sal_Int32 ) maNumPagesText.SetText( maNoPageStr ); } -void PrintDialog::preparePreview( bool i_bNewPage ) +void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) { // page range may have changed depending on options sal_Int32 nPages = maPListener->getFilteredPageCount(); @@ -1138,7 +1138,7 @@ void PrintDialog::preparePreview( bool i_bNewPage ) const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; if( nPages > 0 ) - maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf ); + maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); maPreviewWindow.setPreview( aMtf ); } @@ -1191,7 +1191,7 @@ void PrintDialog::updateNup() maPListener->setMultipage( aMPS ); - preparePreview(); + preparePreview( true, true ); } IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) @@ -1250,7 +1250,7 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) else if( pEdit == &maPageEdit ) { mnCurPage = sal_Int32( maPageEdit.GetValue() - 1 ); - preparePreview(); + preparePreview( true, true ); } return 0; } -- cgit From 4eef171d081c2ebf0005798f1ae038fb2d899441 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 11 Jun 2009 08:54:51 +0000 Subject: make old Start/EndJob Start/EndPage dll private --- vcl/inc/vcl/arrange.hxx | 4 ++-- vcl/inc/vcl/print.hxx | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 1f085521c818..2005418fe740 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -212,8 +212,8 @@ namespace vcl virtual void resize() {} virtual void setParentWindow( Window* ) {} virtual size_t countElements() const { return 1; } - virtual boost::shared_ptr getChild( size_t i_nIndex ) const { return boost::shared_ptr(); } - virtual Window* getWindow( size_t i_nIndex ) const { return NULL; } + virtual boost::shared_ptr getChild( size_t ) const { return boost::shared_ptr(); } + virtual Window* getWindow( size_t ) const { return NULL; } virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } }; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 5e9f0834c574..104e51cb4f24 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -279,6 +279,10 @@ private: public: SAL_DLLPRIVATE void ImplEndPrint(); SAL_DLLPRIVATE void ImplUpdateQuickStatus(); + SAL_DLLPRIVATE BOOL StartJob( const XubString& rJobName ); + SAL_DLLPRIVATE BOOL EndJob(); + SAL_DLLPRIVATE BOOL StartPage(); + SAL_DLLPRIVATE BOOL EndPage(); private: SAL_DLLPRIVATE Printer( const Printer& rPrinter ); SAL_DLLPRIVATE Printer& operator =( const Printer& rPrinter ); @@ -374,14 +378,10 @@ public: const XubString& GetPrintFile() const { return maPrintFile; } void EnablePrintFile( BOOL bEnable ) { mbPrintFile = bEnable; } BOOL IsPrintFileEnabled() const { return mbPrintFile; } - BOOL StartJob( const XubString& rJobName ); - BOOL EndJob(); BOOL AbortJob(); const XubString& GetCurJobName() const { return maJobName; } USHORT GetCurPage() const { return mnCurPage; } BOOL IsJobActive() const { return mbJobActive; } - BOOL StartPage(); - BOOL EndPage(); void SetPageQueueSize( USHORT nPages ) { mnPageQueueSize = nPages; } USHORT GetPageQueueSize() const { return mnPageQueueSize; } -- cgit From 68e6ca91d58be4b05cc2cd8d95acaf70665d3b22 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 11 Jun 2009 14:54:05 +0000 Subject: make compile, need to build an adaptor to new print API --- toolkit/source/awt/vclxprinter.cxx | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/toolkit/source/awt/vclxprinter.cxx b/toolkit/source/awt/vclxprinter.cxx index 69d8dd827497..f57fd8803adf 100644 --- a/toolkit/source/awt/vclxprinter.cxx +++ b/toolkit/source/awt/vclxprinter.cxx @@ -332,7 +332,10 @@ sal_Bool VCLXPrinter::start( const ::rtl::OUString& rJobName, sal_Int16 /*nCopie sal_Bool bDone = sal_True; if ( GetPrinter() ) - bDone = GetPrinter()->StartJob( rJobName ); + { + // FIXME: adapt to new interface + // bDone = GetPrinter()->StartJob( rJobName ); + } return bDone; } @@ -342,7 +345,10 @@ void VCLXPrinter::end( ) throw(::com::sun::star::awt::PrinterException, ::com:: ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); if ( GetPrinter() ) - GetPrinter()->EndJob(); + { + // FIXME: adapt to new interface + // GetPrinter()->EndJob(); + } } void VCLXPrinter::terminate( ) throw(::com::sun::star::uno::RuntimeException) @@ -358,7 +364,10 @@ void VCLXPrinter::terminate( ) throw(::com::sun::star::uno::RuntimeException) ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); if ( GetPrinter() ) - GetPrinter()->StartPage(); + { + // FIXME: adapt to new interface + // GetPrinter()->StartPage(); + } return GetDevice(); } @@ -367,7 +376,10 @@ void VCLXPrinter::endPage( ) throw(::com::sun::star::awt::PrinterException, ::c ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); if ( GetPrinter() ) - GetPrinter()->EndPage(); + { + // FIXME: adapt to new interface + // GetPrinter()->EndPage(); + } } -- cgit From 2280881e946919001cb89ee16ad5b37c210c7cbd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 11 Jun 2009 15:01:42 +0000 Subject: fix warning --- toolkit/source/awt/vclxprinter.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toolkit/source/awt/vclxprinter.cxx b/toolkit/source/awt/vclxprinter.cxx index f57fd8803adf..a0d4de43fe0f 100644 --- a/toolkit/source/awt/vclxprinter.cxx +++ b/toolkit/source/awt/vclxprinter.cxx @@ -326,7 +326,7 @@ IMPL_XTYPEPROVIDER_START( VCLXPrinter ) VCLXPrinterPropertySet::getTypes() IMPL_XTYPEPROVIDER_END -sal_Bool VCLXPrinter::start( const ::rtl::OUString& rJobName, sal_Int16 /*nCopies*/, sal_Bool /*bCollate*/ ) throw(::com::sun::star::awt::PrinterException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException) +sal_Bool VCLXPrinter::start( const ::rtl::OUString& /*rJobName*/, sal_Int16 /*nCopies*/, sal_Bool /*bCollate*/ ) throw(::com::sun::star::awt::PrinterException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); -- cgit From 81249233487670c90d1c40c62c9d4241b178d17f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 12 Jun 2009 15:22:27 +0000 Subject: #i92516# remove old StartPage/EndPage API --- vcl/aqua/source/gdi/salprn.cxx | 1 - vcl/inc/vcl/impprn.hxx | 3 +- vcl/inc/vcl/print.h | 12 -- vcl/inc/vcl/print.hxx | 48 +----- vcl/source/gdi/makefile.mk | 2 - vcl/source/gdi/print.cxx | 362 +++++++++-------------------------------- vcl/source/gdi/print2.cxx | 2 - vcl/source/gdi/print3.cxx | 11 +- 8 files changed, 86 insertions(+), 355 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index f58c63b19079..8e22a83e1403 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -38,7 +38,6 @@ #include "saldata.hxx" #include "vcl/jobset.h" #include "vcl/salptype.hxx" -#include "vcl/impprn.hxx" #include "vcl/print.hxx" #include "vcl/unohelp.hxx" diff --git a/vcl/inc/vcl/impprn.hxx b/vcl/inc/vcl/impprn.hxx index c86090e8b49f..0cd6e9688201 100644 --- a/vcl/inc/vcl/impprn.hxx +++ b/vcl/inc/vcl/impprn.hxx @@ -28,7 +28,7 @@ * ************************************************************************/ -#ifndef _SV_IMPPRN_HXX +#if 0 #define _SV_IMPPRN_HXX #include @@ -107,7 +107,6 @@ public: /** used by pull implementation to emit the next page */ - using Printer::PrintPage; void PrintPage( unsigned int nPage ); /** used by pull implementation to get the number of physical pages diff --git a/vcl/inc/vcl/print.h b/vcl/inc/vcl/print.h index bc74b6441f28..12c7439aa5b3 100644 --- a/vcl/inc/vcl/print.h +++ b/vcl/inc/vcl/print.h @@ -44,18 +44,6 @@ class JobSetup; namespace vcl { class PrinterListener; } -// ------------------------ -// - private printer data - -// ------------------------ -struct ImplPrivatePrinterData -{ - bool mbNextJobIsQuick; - - ImplPrivatePrinterData() : - mbNextJobIsQuick( false ) - {} -}; - // -------------------- // - ImplPrnQueueData - // -------------------- diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 104e51cb4f24..18529c07b432 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -53,8 +53,6 @@ struct SalPrinterQueueInfo; class SalPrinter; class VirtualDevice; class Window; -class ImplQPrinter; -struct ImplPrivatePrinterData; namespace vcl { class PrinterListener; @@ -224,16 +222,12 @@ class VCL_DLLPUBLIC Printer : public OutputDevice friend class ImplQPrinter; private: - ImplPrivatePrinterData* mpPrinterData; SalInfoPrinter* mpInfoPrinter; SalPrinter* mpPrinter; - Printer* mpJobPrinter; SalGraphics* mpJobGraphics; Printer* mpPrev; Printer* mpNext; VirtualDevice* mpDisplayDev; - ImplQPrinter* mpQPrinter; - GDIMetaFile* mpQMtf; PrinterOptions* mpPrinterOptions; XubString maPrinterName; XubString maDriver; @@ -258,9 +252,6 @@ private: BOOL mbUserSetupCompleted; BOOL mbUserSetupResult; Link maErrorHdl; - Link maStartPrintHdl; - Link maEndPrintHdl; - Link maPrintPageHdl; SAL_DLLPRIVATE void ImplInitData(); SAL_DLLPRIVATE void ImplInit( SalPrinterQueueInfo* pInfo ); @@ -276,24 +267,19 @@ private: static SAL_DLLPRIVATE ULONG ImplSalPrinterErrorCodeToVCL( ULONG nError ); -public: +private: SAL_DLLPRIVATE void ImplEndPrint(); - SAL_DLLPRIVATE void ImplUpdateQuickStatus(); SAL_DLLPRIVATE BOOL StartJob( const XubString& rJobName ); SAL_DLLPRIVATE BOOL EndJob(); - SAL_DLLPRIVATE BOOL StartPage(); - SAL_DLLPRIVATE BOOL EndPage(); -private: SAL_DLLPRIVATE Printer( const Printer& rPrinter ); SAL_DLLPRIVATE Printer& operator =( const Printer& rPrinter ); - -#ifdef _SPOOLPRINTER_EXT +public: + SAL_DLLPRIVATE void ImplStartPage(); + SAL_DLLPRIVATE void ImplEndPage(); public: void DrawGradientEx( OutputDevice* pOut, const Rectangle& rRect, const Gradient& rGradient ); void DrawGradientEx( OutputDevice* pOut, const PolyPolygon& rPolyPoly, const Gradient& rGradient ); -#endif // _SPOOLPRINTER_EXT - protected: void SetSelfAsQueuePrinter( BOOL bQueuePrinter ) { mbIsQueuePrinter = bQueuePrinter; } @@ -312,9 +298,6 @@ public: static XubString GetDefaultPrinterName(); virtual void Error(); - virtual void StartPrint(); - virtual void EndPrint(); - virtual void PrintPage(); const XubString& GetName() const { return maPrinterName; } const XubString& GetDriverName() const { return maDriver; } @@ -371,7 +354,6 @@ public: USHORT GetCopyCount() const { return mnCopyCount; } BOOL IsCollateCopy() const { return mbCollateCopy; } - USHORT GetCurPrintPage() const { return mnCurPrintPage; } BOOL IsPrinting() const { return mbPrinting; } void SetPrintFile( const XubString& rFileName ) { maPrintFile = rFileName; } @@ -383,36 +365,14 @@ public: USHORT GetCurPage() const { return mnCurPage; } BOOL IsJobActive() const { return mbJobActive; } - void SetPageQueueSize( USHORT nPages ) { mnPageQueueSize = nPages; } - USHORT GetPageQueueSize() const { return mnPageQueueSize; } - ULONG GetError() const { return ERRCODE_TOERROR(mnError); } ULONG GetErrorCode() const { return mnError; } void SetErrorHdl( const Link& rLink ) { maErrorHdl = rLink; } const Link& GetErrorHdl() const { return maErrorHdl; } - void SetStartPrintHdl( const Link& rLink ) { maStartPrintHdl = rLink; } - const Link& GetStartPrintHdl() const { return maStartPrintHdl; } - void SetEndPrintHdl( const Link& rLink ) { maEndPrintHdl = rLink; } - const Link& GetEndPrintHdl() const { return maEndPrintHdl; } - void SetPrintPageHdl( const Link& rLink ) { maPrintPageHdl = rLink; } - const Link& GetPrintPageHdl() const { return maPrintPageHdl; } void Compat_OldPrinterMetrics( bool bSet ); - /** Notify that the next StartJob belongs to a UI less "direct print" job - * - * deprecated: the canonical way to notify a UI less job is to set the - * JobSetup value "IsQuickJob" to "true". If set at all, the "IsQuickJob" value - * on JobSetup will be preferred. However if no "IsQuickJob" value is set, - * setting SetNextJobIsQuick will cause the following StartJob to set this value - * to "true" in the current JobSetup. - * - * the paramter can be set to "false" again in case a job was not started and the - * printer is to be reused. - */ - void SetNextJobIsQuick( bool bQuick = true ); - /** checks the printer list and updates it necessary * * sends a DataChanged event of type DATACHANGED_PRINTER diff --git a/vcl/source/gdi/makefile.mk b/vcl/source/gdi/makefile.mk index 57d5804a8afa..05dc998d6651 100644 --- a/vcl/source/gdi/makefile.mk +++ b/vcl/source/gdi/makefile.mk @@ -76,7 +76,6 @@ SLOFILES= $(SLO)$/salmisc.obj \ $(SLO)$/impgraph.obj \ $(SLO)$/impimagetree.obj \ $(SLO)$/imagerepository.obj \ - $(SLO)$/impprn.obj \ $(SLO)$/impvect.obj \ $(SLO)$/implncvt.obj \ $(SLO)$/jobset.obj \ @@ -138,7 +137,6 @@ EXCEPTIONSFILES= $(SLO)$/salmisc.obj \ $(SLO)$/pngread.obj \ $(SLO)$/pngwrite.obj \ $(SLO)$/virdev.obj \ - $(SLO)$/impprn.obj \ $(SLO)$/graphictools.obj diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index a74038c4eaaa..a3e33f236166 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -31,8 +31,6 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#define _SPOOLPRINTER_EXT -#define _RMPRINTER_EXT #define ENABLE_BYTESTRING_STREAM_OPERATORS #include @@ -58,7 +56,6 @@ #include #include #include -#include #include #include @@ -369,7 +366,6 @@ XubString Printer::GetDefaultPrinterName() void Printer::ImplInitData() { - mpPrinterData = new ImplPrivatePrinterData(); mbDevOutput = FALSE; meOutDevType = OUTDEV_PRINTER; mbDefPrinter = FALSE; @@ -387,8 +383,6 @@ void Printer::ImplInitData() mpInfoPrinter = NULL; mpPrinter = NULL; mpDisplayDev = NULL; - mpQPrinter = NULL; - mpQMtf = NULL; mbIsQueuePrinter = FALSE; mpPrinterOptions = new PrinterOptions; @@ -435,7 +429,6 @@ void Printer::ImplInit( SalPrinterQueueInfo* pInfo ) mpInfoPrinter = pSVData->mpDefInst->CreateInfoPrinter( pInfo, pJobSetup ); mpPrinter = NULL; - mpJobPrinter = NULL; mpJobGraphics = NULL; ImplUpdateJobSetupPaper( maJobSetup ); @@ -467,7 +460,6 @@ void Printer::ImplInitDisplay( const Window* pWindow ) mpInfoPrinter = NULL; mpPrinter = NULL; - mpJobPrinter = NULL; mpJobGraphics = NULL; if ( pWindow ) @@ -623,11 +615,6 @@ Printer::~Printer() { DBG_ASSERT( !IsPrinting(), "Printer::~Printer() - Job is printing" ); DBG_ASSERT( !IsJobActive(), "Printer::~Printer() - Job is active" ); - DBG_ASSERT( !mpQPrinter, "Printer::~Printer() - QueuePrinter not destroyed" ); - DBG_ASSERT( !mpQMtf, "Printer::~Printer() - QueueMetafile not destroyed" ); - - delete mpPrinterData; - mpPrinterData = NULL; delete mpPrinterOptions; @@ -673,22 +660,12 @@ Printer::~Printer() pSVData->maGDIData.mpLastPrinter = mpPrev; } -// ----------------------------------------------------------------------- -void Printer::SetNextJobIsQuick( bool bQuick ) -{ - mpPrinterData->mbNextJobIsQuick = bQuick; - if( mpQPrinter ) - mpQPrinter->SetNextJobIsQuick( bQuick ); -} - // ----------------------------------------------------------------------- void Printer::Compat_OldPrinterMetrics( bool bSet ) { // propagate flag if( mpInfoPrinter ) mpInfoPrinter->m_bCompatMetrics = bSet; - if( mpQPrinter ) - mpQPrinter->Compat_OldPrinterMetrics( bSet ); // get new font data ImplUpdateFontData( TRUE ); @@ -1326,27 +1303,6 @@ void Printer::Error() // ----------------------------------------------------------------------- -void Printer::StartPrint() -{ - maStartPrintHdl.Call( this ); -} - -// ----------------------------------------------------------------------- - -void Printer::EndPrint() -{ - maEndPrintHdl.Call( this ); -} - -// ----------------------------------------------------------------------- - -void Printer::PrintPage() -{ - maPrintPageHdl.Call( this ); -} - -// ----------------------------------------------------------------------- - ULONG Printer::ImplSalPrinterErrorCodeToVCL( ULONG nError ) { @@ -1374,12 +1330,6 @@ void Printer::ImplEndPrint() mbPrinting = FALSE; mnCurPrintPage = 0; maJobName.Erase(); - if( mpQPrinter ) // not necessarily filled e.g. after AbortJob - { - mpQPrinter->Destroy(); - mpQPrinter = NULL; - } - EndPrint(); } // ----------------------------------------------------------------------- @@ -1394,31 +1344,6 @@ IMPL_LINK( Printer, ImplDestroyPrinterAsync, void*, pSalPrinter ) // ----------------------------------------------------------------------- -void Printer::ImplUpdateQuickStatus() -{ - // remove possibly added "IsQuickJob" - if( mpPrinterData->mbNextJobIsQuick ) - { - rtl::OUString aKey( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ); - // const data means not really const, but change all references - // to refcounted job setup - ImplJobSetup* pImpSetup = maJobSetup.ImplGetConstData(); - pImpSetup->maValueMap.erase( aKey ); - mpPrinterData->mbNextJobIsQuick = false; - } -} - -class QuickGuard -{ - Printer* mpPrinter; - public: - QuickGuard( Printer* pPrn ) : mpPrinter( pPrn ) {} - ~QuickGuard() - { - mpPrinter->ImplUpdateQuickStatus(); - } -}; - BOOL Printer::StartJob( const XubString& rJobName ) { mnError = PRINTER_OK; @@ -1429,139 +1354,72 @@ BOOL Printer::StartJob( const XubString& rJobName ) if ( IsJobActive() || IsPrinting() ) return FALSE; - if( mpPrinterData->mbNextJobIsQuick ) - { - String aKey( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ); - if( maJobSetup.GetValue( aKey ).Len() == 0 ) - maJobSetup.SetValue( aKey, String( RTL_CONSTASCII_USTRINGPARAM( "true" ) ) ); - } - - QuickGuard aQGuard( this ); - ULONG nCopies = mnCopyCount; BOOL bCollateCopy = mbCollateCopy; BOOL bUserCopy = FALSE; - if ( IsQueuePrinter() ) + if ( nCopies > 1 ) { - if ( ((ImplQPrinter*)this)->IsUserCopy() ) + ULONG nDevCopy; + + if ( bCollateCopy ) + nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COLLATECOPIES ); + else + nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COPIES ); + + // Muessen Kopien selber gemacht werden? + if ( nCopies > nDevCopy ) { + bUserCopy = TRUE; nCopies = 1; bCollateCopy = FALSE; } } else - { - if ( nCopies > 1 ) - { - ULONG nDevCopy; - - if ( bCollateCopy ) - nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COLLATECOPIES ); - else - nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COPIES ); + bCollateCopy = FALSE; - // Muessen Kopien selber gemacht werden? - if ( nCopies > nDevCopy ) - { - bUserCopy = TRUE; - nCopies = 1; - bCollateCopy = FALSE; - } - } - else - bCollateCopy = FALSE; - - // we need queue printing - if( !mnPageQueueSize ) - mnPageQueueSize = 1; - } - - if ( !mnPageQueueSize ) - { - ImplSVData* pSVData = ImplGetSVData(); - mpPrinter = pSVData->mpDefInst->CreatePrinter( mpInfoPrinter ); - - if ( !mpPrinter ) - return FALSE; + ImplSVData* pSVData = ImplGetSVData(); + mpPrinter = pSVData->mpDefInst->CreatePrinter( mpInfoPrinter ); - XubString* pPrintFile; - if ( mbPrintFile ) - pPrintFile = &maPrintFile; - else - pPrintFile = NULL; - - // #125075# StartJob can Reschedule on Windows, sfx - // depends on IsPrinting() in case of closing a document - BOOL bSaveNewJobSetup = mbNewJobSetup; - mbNewJobSetup = FALSE; - String aSaveJobName = maJobName; - maJobName = rJobName; - mnCurPage = 1; - mnCurPrintPage = 1; - mbPrinting = TRUE; - - if( ! ImplGetSVData()->maGDIData.mbPrinterPullModel ) - { - // in the pull model the job can only be started when - // we have collected all pages to be printed - if ( !mpPrinter->StartJob( pPrintFile, rJobName, Application::GetDisplayName(), - nCopies, bCollateCopy, - maJobSetup.ImplGetConstData() ) ) - { - mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); - if ( !mnError ) - mnError = PRINTER_GENERALERROR; - pSVData->mpDefInst->DestroyPrinter( mpPrinter ); - mbNewJobSetup = bSaveNewJobSetup; - maJobName = aSaveJobName; - mnCurPage = 0; - mnCurPrintPage = 0; - mbPrinting = FALSE; - mpPrinter = NULL; - return FALSE; - } - } + if ( !mpPrinter ) + return FALSE; - mbJobActive = TRUE; - StartPrint(); - } + XubString* pPrintFile; + if ( mbPrintFile ) + pPrintFile = &maPrintFile; else + pPrintFile = NULL; + + // #125075# StartJob can Reschedule on Windows, sfx + // depends on IsPrinting() in case of closing a document + BOOL bSaveNewJobSetup = mbNewJobSetup; + mbNewJobSetup = FALSE; + String aSaveJobName = maJobName; + maJobName = rJobName; + mnCurPage = 1; + mnCurPrintPage = 1; + mbPrinting = TRUE; + + if( ! ImplGetSVData()->maGDIData.mbPrinterPullModel ) { - mpQPrinter = new ImplQPrinter( this ); - if( mpInfoPrinter ) - mpQPrinter->Compat_OldPrinterMetrics( mpInfoPrinter->m_bCompatMetrics ); - mpQPrinter->SetDigitLanguage( GetDigitLanguage() ); - mpQPrinter->SetUserCopy( bUserCopy ); - mpQPrinter->SetPrinterOptions( *mpPrinterOptions ); - - // #125075# StartJob can Reschedule on Windows, sfx - // depends on IsPrinting() in case of closing a document - BOOL bSaveNewJobSetup = mbNewJobSetup; - mbNewJobSetup = FALSE; - String aSaveJobName = maJobName; - maJobName = rJobName; - mnCurPage = 1; - mbPrinting = TRUE; - - if ( mpQPrinter->StartJob( rJobName ) ) - { - mbJobActive = TRUE; - StartPrint(); - mpQPrinter->StartQueuePrint(); - } - else + if ( !mpPrinter->StartJob( pPrintFile, rJobName, Application::GetDisplayName(), + nCopies, bCollateCopy, + maJobSetup.ImplGetConstData() ) ) { - mbNewJobSetup = bSaveNewJobSetup; - maJobName = aSaveJobName; - mnCurPage = 0; - mbPrinting = FALSE; - mnError = mpQPrinter->GetErrorCode(); - mpQPrinter->Destroy(); - mpQPrinter = NULL; + mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); + if ( !mnError ) + mnError = PRINTER_GENERALERROR; + pSVData->mpDefInst->DestroyPrinter( mpPrinter ); + mbNewJobSetup = bSaveNewJobSetup; + maJobName = aSaveJobName; + mnCurPage = 0; + mnCurPrintPage = 0; + mbPrinting = FALSE; + mpPrinter = NULL; return FALSE; } } + mbJobActive = TRUE; return TRUE; } @@ -1578,7 +1436,7 @@ BOOL Printer::EndJob() mbJobActive = FALSE; - if ( mpPrinter || mpQPrinter ) + if ( mpPrinter ) { ImplReleaseGraphics(); @@ -1586,23 +1444,17 @@ BOOL Printer::EndJob() bRet = TRUE; - if ( mpPrinter ) - { - mbPrinting = FALSE; - mnCurPrintPage = 0; - maJobName.Erase(); - - mbDevOutput = FALSE; - bRet = mpPrinter->EndJob(); - // Hier den Drucker nicht asyncron zerstoeren, da es - // W95 nicht verkraftet, wenn gleichzeitig gedruckt wird - // und ein Druckerobjekt zerstoert wird - ImplGetSVData()->mpDefInst->DestroyPrinter( mpPrinter ); - mpPrinter = NULL; - EndPrint(); - } - else - mpQPrinter->EndQueuePrint(); + mbPrinting = FALSE; + mnCurPrintPage = 0; + maJobName.Erase(); + + mbDevOutput = FALSE; + bRet = mpPrinter->EndJob(); + // Hier den Drucker nicht asyncron zerstoeren, da es + // W95 nicht verkraftet, wenn gleichzeitig gedruckt wird + // und ein Druckerobjekt zerstoert wird + ImplGetSVData()->mpDefInst->DestroyPrinter( mpPrinter ); + mpPrinter = NULL; } return bRet; @@ -1621,35 +1473,18 @@ BOOL Printer::AbortJob() mbInPrintPage = FALSE; mpJobGraphics = NULL; - if ( mpPrinter || mpQPrinter ) + if ( mpPrinter ) { mbPrinting = FALSE; mnCurPage = 0; mnCurPrintPage = 0; maJobName.Erase(); - if ( mpPrinter ) - { - ImplReleaseGraphics(); - mbDevOutput = FALSE; - mpPrinter->AbortJob(); - Application::PostUserEvent( LINK( this, Printer, ImplDestroyPrinterAsync ), mpPrinter ); - mpPrinter = NULL; - EndPrint(); - } - else - { - mpQPrinter->AbortQueuePrint(); - mpQPrinter->Destroy(); - mpQPrinter = NULL; - if ( mpQMtf ) - { - mpQMtf->Clear(); - delete mpQMtf; - mpQMtf = NULL; - } - EndPrint(); - } + ImplReleaseGraphics(); + mbDevOutput = FALSE; + mpPrinter->AbortJob(); + Application::PostUserEvent( LINK( this, Printer, ImplDestroyPrinterAsync ), mpPrinter ); + mpPrinter = NULL; return TRUE; } @@ -1659,88 +1494,49 @@ BOOL Printer::AbortJob() // ----------------------------------------------------------------------- -BOOL Printer::StartPage() +void Printer::ImplStartPage() { if ( !IsJobActive() ) - return FALSE; + return; - if ( mpPrinter || mpQPrinter ) + if ( mpPrinter ) { - if ( mpPrinter ) + SalGraphics* pGraphics = mpPrinter->StartPage( maJobSetup.ImplGetConstData(), mbNewJobSetup ); + if ( pGraphics ) { - SalGraphics* pGraphics = mpPrinter->StartPage( maJobSetup.ImplGetConstData(), mbNewJobSetup ); - if ( pGraphics ) - { - ImplReleaseGraphics(); - mpJobGraphics = pGraphics; - } - mbDevOutput = TRUE; - } - else - { - ImplGetGraphics(); - mpJobGraphics = mpGraphics; + ImplReleaseGraphics(); + mpJobGraphics = pGraphics; } + mbDevOutput = TRUE; // PrintJob not aborted ??? if ( IsJobActive() ) { mbInPrintPage = TRUE; mnCurPage++; - if ( mpQPrinter ) - { - mpQPrinter->SetPrinterOptions( *mpPrinterOptions ); - mpQMtf = new GDIMetaFile; - mpQMtf->Record( this ); - mpQMtf->SaveStatus(); - } - else - { - mnCurPrintPage++; - PrintPage(); - } + mnCurPrintPage++; } - - return TRUE; } - - return FALSE; } // ----------------------------------------------------------------------- -BOOL Printer::EndPage() +void Printer::ImplEndPage() { if ( !IsJobActive() ) - return FALSE; + return; mbInPrintPage = FALSE; - if ( mpPrinter || mpQPrinter ) + if ( mpPrinter ) { - if ( mpPrinter ) - { - mpPrinter->EndPage(); - ImplReleaseGraphics(); - mbDevOutput = FALSE; - } - else if ( mpQPrinter ) - { - // Eigentuemeruebergang an QPrinter - mpQMtf->Stop(); - mpQMtf->WindStart(); - GDIMetaFile* pPage = mpQMtf; - mpQMtf = NULL; - mpQPrinter->AddQueuePage( pPage, mnCurPage, mbNewJobSetup ); - } + mpPrinter->EndPage(); + ImplReleaseGraphics(); + mbDevOutput = FALSE; mpJobGraphics = NULL; mbNewJobSetup = FALSE; - - return TRUE; } - - return FALSE; } // ----------------------------------------------------------------------- diff --git a/vcl/source/gdi/print2.cxx b/vcl/source/gdi/print2.cxx index 685f68fe7af3..21c6b59f53a4 100644 --- a/vcl/source/gdi/print2.cxx +++ b/vcl/source/gdi/print2.cxx @@ -31,8 +31,6 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#define _SPOOLPRINTER_EXT - #include #include #include diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 1ef2e18b996a..b7344d073386 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -330,13 +330,6 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrmbNextJobIsQuick ) - { - String aKey( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ); - if( maJobSetup.GetValue( aKey ).Len() == 0 ) - maJobSetup.SetValue( aKey, String( RTL_CONSTASCII_USTRINGPARAM( "true" ) ) ); - } - ULONG nCopies = mnCopyCount; BOOL bCollateCopy = mbCollateCopy; BOOL bUserCopy = FALSE; @@ -722,14 +715,14 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->SetPaperSizeUser( aPageSize = mpImplData->maMultiPage.aPaperSize ); // actually print the page - mpImplData->mpPrinter->StartPage(); + mpImplData->mpPrinter->ImplStartPage(); mpImplData->mpPrinter->Push(); aCleanedFile.WindStart(); aCleanedFile.Play( mpImplData->mpPrinter.get() ); mpImplData->mpPrinter->Pop(); - mpImplData->mpPrinter->EndPage(); + mpImplData->mpPrinter->ImplEndPage(); mpImplData->mpPrinter->SetDrawMode( nRestoreDrawMode ); } -- cgit From bf2e454176da56effb2161ce5fa2d7267b07fc19 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 12 Jun 2009 16:34:50 +0000 Subject: #i92516# helper class to fix old style printing routines --- vcl/inc/vcl/oldprintadaptor.hxx | 52 ++++++++++++++++++ vcl/prj/d.lst | 1 + vcl/source/gdi/makefile.mk | 2 + vcl/source/gdi/oldprintadaptor.cxx | 107 +++++++++++++++++++++++++++++++++++++ 4 files changed, 162 insertions(+) create mode 100644 vcl/inc/vcl/oldprintadaptor.hxx create mode 100644 vcl/source/gdi/oldprintadaptor.cxx diff --git a/vcl/inc/vcl/oldprintadaptor.hxx b/vcl/inc/vcl/oldprintadaptor.hxx new file mode 100644 index 000000000000..9a0cb9a1d083 --- /dev/null +++ b/vcl/inc/vcl/oldprintadaptor.hxx @@ -0,0 +1,52 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _VCL_OLDPRINTADAPTOR +#define _VCL_OLDPRINTADAPTOR + +#include "vcl/print.hxx" + +namespace vcl +{ + struct ImplOldStyleAdaptorData; + class VCL_DLLPUBLIC OldStylePrintAdaptor : public PrinterListener + { + ImplOldStyleAdaptorData* mpData; + public: + OldStylePrintAdaptor( const boost::shared_ptr< Printer >& ); + virtual ~OldStylePrintAdaptor(); + + void StartPage(); + void EndPage(); + + virtual int getPageCount() const; + virtual com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getPageParameters( int i_nPage ) const; + virtual void printPage( int i_nPage ) const; + }; +} + +#endif diff --git a/vcl/prj/d.lst b/vcl/prj/d.lst index 6718a9c267de..a8b308aea462 100644 --- a/vcl/prj/d.lst +++ b/vcl/prj/d.lst @@ -82,6 +82,7 @@ mkdir: %_DEST%\inc%_EXT%\vcl\plug\vcl ..\inc\vcl\morebtn.hxx %_DEST%\inc%_EXT%\vcl\morebtn.hxx ..\inc\vcl\msgbox.hxx %_DEST%\inc%_EXT%\vcl\msgbox.hxx ..\inc\vcl\octree.hxx %_DEST%\inc%_EXT%\vcl\octree.hxx +..\inc\vcl\oldprintadaptor.hxx %_DEST%\inc%_EXT%\vcl\oldprintadaptor.hxx ..\inc\vcl\outdev.hxx %_DEST%\inc%_EXT%\vcl\outdev.hxx ..\inc\vcl\pointr.hxx %_DEST%\inc%_EXT%\vcl\pointr.hxx ..\inc\vcl\print.hxx %_DEST%\inc%_EXT%\vcl\print.hxx diff --git a/vcl/source/gdi/makefile.mk b/vcl/source/gdi/makefile.mk index 05dc998d6651..ed22a4ac6764 100644 --- a/vcl/source/gdi/makefile.mk +++ b/vcl/source/gdi/makefile.mk @@ -84,6 +84,7 @@ SLOFILES= $(SLO)$/salmisc.obj \ $(SLO)$/metaact.obj \ $(SLO)$/metric.obj \ $(SLO)$/octree.obj \ + $(SLO)$/oldprintadaptor.obj \ $(SLO)$/outmap.obj \ $(SLO)$/outdev.obj \ $(SLO)$/outdev2.obj \ @@ -126,6 +127,7 @@ EXCEPTIONSFILES= $(SLO)$/salmisc.obj \ $(SLO)$/impimage.obj \ $(SLO)$/impgraph.obj \ $(SLO)$/metric.obj \ + $(SLO)$/oldprintadaptor.obj \ $(SLO)$/pdfwriter_impl.obj \ $(SLO)$/pdffontcache.obj\ $(SLO)$/fontcfg.obj \ diff --git a/vcl/source/gdi/oldprintadaptor.cxx b/vcl/source/gdi/oldprintadaptor.cxx new file mode 100644 index 000000000000..3ff6ce27c4d4 --- /dev/null +++ b/vcl/source/gdi/oldprintadaptor.cxx @@ -0,0 +1,107 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "vcl/oldprintadaptor.hxx" +#include "vcl/gdimtf.hxx" + +#include "com/sun/star/awt/Size.hpp" + +#include + +namespace vcl +{ + struct AdaptorPage + { + GDIMetaFile maPage; + com::sun::star::awt::Size maPageSize; + }; + + struct ImplOldStyleAdaptorData + { + std::vector< AdaptorPage > maPages; + }; +}; + +using namespace vcl; +using namespace cppu; +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; + +OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter ) + : PrinterListener( i_pPrinter ) + , mpData( new ImplOldStyleAdaptorData() ) +{ +} + +OldStylePrintAdaptor::~OldStylePrintAdaptor() +{ +} + +void OldStylePrintAdaptor::StartPage() +{ + Size aPaperSize( getPrinter()->PixelToLogic( getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + mpData->maPages.push_back( AdaptorPage() ); + mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth(); + mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight(); + getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage ); +} + +void OldStylePrintAdaptor::EndPage() +{ + getPrinter()->SetConnectMetaFile( NULL ); + mpData->maPages.back().maPage.WindStart(); +} + +int OldStylePrintAdaptor::getPageCount() const +{ + return int(mpData->maPages.size()); +} + +Sequence< PropertyValue > OldStylePrintAdaptor::getPageParameters( int i_nPage ) const +{ + Sequence< PropertyValue > aRet( 1 ); + aRet[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("PageSize") ); + if( i_nPage < int(mpData->maPages.size() ) ) + aRet[0].Value = makeAny( mpData->maPages[i_nPage].maPageSize ); + else + { + awt::Size aEmpty( 0, 0 ); + aRet[0].Value = makeAny( aEmpty ); + } + return aRet; +} + +void OldStylePrintAdaptor::printPage( int i_nPage ) const +{ + if( i_nPage < int(mpData->maPages.size()) ) + { + mpData->maPages[ i_nPage ].maPage.WindStart(); + mpData->maPages[ i_nPage ].maPage.Play( getPrinter().get() ); + } +} + -- cgit From 0c7e5dafaf360b1fac76c26c0a95cb0322c3c341 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 12 Jun 2009 16:44:24 +0000 Subject: fix a warning --- vcl/source/gdi/oldprintadaptor.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/gdi/oldprintadaptor.cxx b/vcl/source/gdi/oldprintadaptor.cxx index 3ff6ce27c4d4..a83a5cbc0a09 100644 --- a/vcl/source/gdi/oldprintadaptor.cxx +++ b/vcl/source/gdi/oldprintadaptor.cxx @@ -44,7 +44,7 @@ namespace vcl { std::vector< AdaptorPage > maPages; }; -}; +} using namespace vcl; using namespace cppu; -- cgit From 47d8f3b65172271f386a64d1a983b46dd1de0e9f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 13 Jun 2009 10:45:00 +0000 Subject: add missing precompiled header --- vcl/source/gdi/oldprintadaptor.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/source/gdi/oldprintadaptor.cxx b/vcl/source/gdi/oldprintadaptor.cxx index a83a5cbc0a09..a2286172a88d 100644 --- a/vcl/source/gdi/oldprintadaptor.cxx +++ b/vcl/source/gdi/oldprintadaptor.cxx @@ -25,6 +25,8 @@ * ************************************************************************/ +#include "precompiled_vcl.hxx" + #include "vcl/oldprintadaptor.hxx" #include "vcl/gdimtf.hxx" -- cgit From c65c7c60ac0c12558f4fe96206b40f29ab41afb4 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 17 Jun 2009 14:07:26 +0000 Subject: #i92516# adapt old deprecated interface to new API --- toolkit/inc/toolkit/awt/vclxprinter.hxx | 15 ++++++--------- toolkit/source/awt/vclxprinter.cxx | 30 +++++++++++++----------------- 2 files changed, 19 insertions(+), 26 deletions(-) diff --git a/toolkit/inc/toolkit/awt/vclxprinter.hxx b/toolkit/inc/toolkit/awt/vclxprinter.hxx index e94864b51280..4db43a3c5d77 100644 --- a/toolkit/inc/toolkit/awt/vclxprinter.hxx +++ b/toolkit/inc/toolkit/awt/vclxprinter.hxx @@ -43,9 +43,7 @@ #include #include -class Printer; -class String; - +#include "vcl/oldprintadaptor.hxx" // Fuer den Drucker relevante Properties: /* @@ -65,20 +63,17 @@ class VCLXPrinterPropertySet : public ::com::sun::star::awt::XPrinterPropertySe public MutexAndBroadcastHelper, public ::cppu::OPropertySetHelper { -private: - Printer* mpPrinter; +protected: + boost::shared_ptr mpPrinter; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice > mxPrnDevice; sal_Int16 mnOrientation; sal_Bool mbHorizontal; - -protected: - public: VCLXPrinterPropertySet( const String& rPrinterName ); virtual ~VCLXPrinterPropertySet(); - Printer* GetPrinter() const { return mpPrinter; } + Printer* GetPrinter() const { return mpPrinter.get(); } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice > GetDevice(); // ::com::sun::star::uno::XInterface @@ -120,6 +115,8 @@ class VCLXPrinter: public ::com::sun::star::awt::XPrinter, public VCLXPrinterPropertySet, public ::cppu::OWeakObject { + boost::shared_ptr mpListener; + JobSetup maInitJobSetup; public: VCLXPrinter( const String& rPrinterName ); ~VCLXPrinter(); diff --git a/toolkit/source/awt/vclxprinter.cxx b/toolkit/source/awt/vclxprinter.cxx index a0d4de43fe0f..a8059463a297 100644 --- a/toolkit/source/awt/vclxprinter.cxx +++ b/toolkit/source/awt/vclxprinter.cxx @@ -102,10 +102,10 @@ IMPL_XTYPEPROVIDER_END VCLXPrinterPropertySet::VCLXPrinterPropertySet( const String& rPrinterName ) : OPropertySetHelper( BrdcstHelper ) + , mpPrinter( new Printer( rPrinterName ) ) { osl::Guard< vos::IMutex > aSolarGuard( Application::GetSolarMutex() ); - mpPrinter = new Printer( rPrinterName ); mnOrientation = 0; mbHorizontal = sal_False; } @@ -113,8 +113,7 @@ VCLXPrinterPropertySet::VCLXPrinterPropertySet( const String& rPrinterName ) VCLXPrinterPropertySet::~VCLXPrinterPropertySet() { osl::Guard< vos::IMutex > aSolarGuard( Application::GetSolarMutex() ); - - delete mpPrinter; + mpPrinter.reset(); } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice > VCLXPrinterPropertySet::GetDevice() @@ -331,10 +330,10 @@ sal_Bool VCLXPrinter::start( const ::rtl::OUString& /*rJobName*/, sal_Int16 /*nC ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); sal_Bool bDone = sal_True; - if ( GetPrinter() ) + if ( mpListener.get() ) { - // FIXME: adapt to new interface - // bDone = GetPrinter()->StartJob( rJobName ); + maInitJobSetup = mpPrinter->GetJobSetup(); + mpListener.reset( new vcl::OldStylePrintAdaptor( mpPrinter ) ); } return bDone; @@ -344,10 +343,10 @@ void VCLXPrinter::end( ) throw(::com::sun::star::awt::PrinterException, ::com:: { ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); - if ( GetPrinter() ) + if ( mpListener.get() ) { - // FIXME: adapt to new interface - // GetPrinter()->EndJob(); + Printer::PrintJob( mpListener, maInitJobSetup ); + mpListener.reset(); } } @@ -355,18 +354,16 @@ void VCLXPrinter::terminate( ) throw(::com::sun::star::uno::RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); - if ( GetPrinter() ) - GetPrinter()->AbortJob(); + mpListener.reset(); } ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice > VCLXPrinter::startPage( ) throw(::com::sun::star::awt::PrinterException, ::com::sun::star::uno::RuntimeException) { ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); - if ( GetPrinter() ) + if ( mpListener.get() ) { - // FIXME: adapt to new interface - // GetPrinter()->StartPage(); + mpListener->StartPage(); } return GetDevice(); } @@ -375,10 +372,9 @@ void VCLXPrinter::endPage( ) throw(::com::sun::star::awt::PrinterException, ::c { ::osl::Guard< ::osl::Mutex > aGuard( Mutex ); - if ( GetPrinter() ) + if ( mpListener.get() ) { - // FIXME: adapt to new interface - // GetPrinter()->EndPage(); + mpListener->EndPage(); } } -- cgit From cc0801b55d5504dc7a71f4c8322b2286390ff18e Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 17 Jun 2009 15:16:29 +0000 Subject: #i92516# copy state to metafile --- vcl/source/gdi/oldprintadaptor.cxx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vcl/source/gdi/oldprintadaptor.cxx b/vcl/source/gdi/oldprintadaptor.cxx index a2286172a88d..e0250d2832ba 100644 --- a/vcl/source/gdi/oldprintadaptor.cxx +++ b/vcl/source/gdi/oldprintadaptor.cxx @@ -71,6 +71,14 @@ void OldStylePrintAdaptor::StartPage() mpData->maPages.back().maPageSize.Width = aPaperSize.getWidth(); mpData->maPages.back().maPageSize.Height = aPaperSize.getHeight(); getPrinter()->SetConnectMetaFile( &mpData->maPages.back().maPage ); + + // copy state into metafile + boost::shared_ptr pPrinter( getPrinter() ); + pPrinter->SetMapMode( pPrinter->GetMapMode() ); + pPrinter->SetFont( pPrinter->GetFont() ); + pPrinter->SetDrawMode( pPrinter->GetDrawMode() ); + pPrinter->SetLineColor( pPrinter->GetLineColor() ); + pPrinter->SetFillColor( pPrinter->GetFillColor() ); } void OldStylePrintAdaptor::EndPage() -- cgit From a6e3e2a5a75bc7f41cc5fcf5b5661c7996af327c Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 18 Jun 2009 18:26:15 +0000 Subject: #i92516# autoarrange of N-Up page --- vcl/inc/vcl/arrange.hxx | 67 +++++++++++++ vcl/inc/vcl/prndlg.hxx | 2 + vcl/source/window/arrange.cxx | 214 +++++++++++++++++++++++++++++++++++++++++ vcl/source/window/printdlg.cxx | 59 ++++++++++++ 4 files changed, 342 insertions(+) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 2005418fe740..f350b9ae110d 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -34,6 +34,7 @@ #include "vcl/window.hxx" #include +#include #include namespace vcl @@ -217,6 +218,72 @@ namespace vcl virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } }; + + class MatrixArranger : public WindowArranger + { + long m_nBorderX; + long m_nBorderY; + + struct MatrixElement : public WindowArranger::Element + { + sal_uInt32 m_nX; + sal_uInt32 m_nY; + + MatrixElement() + : WindowArranger::Element() + , m_nX( 0 ) + , m_nY( 0 ) + {} + + MatrixElement( Window* i_pWin, + sal_uInt32 i_nX, sal_uInt32 i_nY, + boost::shared_ptr const & i_pChild = boost::shared_ptr(), + sal_Int32 i_nExpandPriority = 0 + ) + : WindowArranger::Element( i_pWin, i_pChild, i_nExpandPriority ) + , m_nX( i_nX ) + , m_nY( i_nY ) + { + } + }; + + std::vector< MatrixElement > m_aElements; + std::map< sal_uInt64, size_t > m_aMatrixMap; // maps (x | (y << 32)) to index in m_aElements + + sal_uInt64 getMap( sal_uInt32 i_nX, sal_uInt32 i_nY ) + { return static_cast< sal_uInt64 >(i_nX) | (static_cast< sal_uInt64>(i_nY) << 32 ); } + + Size getOptimalSize( WindowSizeType, std::vector& o_rColumnWidths, std::vector& o_rRowHeights ) const; + public: + MatrixArranger( WindowArranger* i_pParent = NULL, + long i_nBorderX = 5, + long i_nBorderY = 5 ) + : WindowArranger( i_pParent ) + , m_nBorderX( i_nBorderX ) + , m_nBorderY( i_nBorderY ) + {} + + virtual ~MatrixArranger(); + + virtual Size getOptimalSize( WindowSizeType ) const; + virtual void resize(); + virtual void setParentWindow( Window* ); + virtual size_t countElements() const { return m_aElements.size(); } + virtual boost::shared_ptr getChild( size_t i_nIndex ) const; + virtual Window* getWindow( size_t i_nIndex ) const; + virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const; + + // add a managed window at the given matrix position + void addWindow( Window*, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); + void remove( Window* ); + + void addChild( boost::shared_ptr const &, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); + // convenience: use for addChild( new WindowArranger( ... ) ) constructs + void addChild( WindowArranger* i_pNewChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ) + { addChild( boost::shared_ptr( i_pNewChild ), i_nX, i_nY, i_nExpandPrio ); } + void remove( boost::shared_ptr const & ); + }; + } #endif diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index c2e8beaa16e9..67f38e45540f 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -113,6 +113,8 @@ namespace vcl void readFromSettings(); void storeToSettings(); void initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& ); + + virtual void Resize(); }; class JobTabPage : public TabPage diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index ba1a89eb79da..917b04fcc855 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -388,3 +388,217 @@ void Indenter::setParentWindow( Window* i_pNewParent ) if( m_aElement.m_pChild ) m_aElement.m_pChild->setParentWindow( i_pNewParent ); } + +// ---------------------------------------- +// vcl::MatrixArranger +//----------------------------------------- +MatrixArranger::~MatrixArranger() +{ +} + +Size MatrixArranger::getOptimalSize( WindowSizeType i_eType, std::vector& o_rColumnWidths, std::vector& o_rRowHeights ) const +{ + Size aMatrixSize( 2*m_nOuterBorder, 2*m_nOuterBorder ); + + // first find out the current number of rows and columns + sal_uInt32 nRows = 0, nColumns = 0; + for( std::vector< MatrixElement >::const_iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + if( it->m_nX >= nColumns ) + nColumns = it->m_nX+1; + if( it->m_nY >= nRows ) + nRows = it->m_nY+1; + } + + // now allocate row and column depth vectors + o_rColumnWidths = std::vector< long >( nColumns, 0 ); + o_rRowHeights = std::vector< long >( nRows, 0 ); + + // get sizes an allocate them into rows/columns + for( std::vector< MatrixElement >::const_iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + Size aSize; + if( it->m_pElement ) + aSize = it->m_pElement->GetOptimalSize( i_eType ); + else if( it->m_pChild ) + aSize = it->m_pChild->getOptimalSize( i_eType ); + if( aSize.Width() > o_rColumnWidths[ it->m_nX ] ) + o_rColumnWidths[ it->m_nX ] = aSize.Width(); + if( aSize.Height() > o_rRowHeights[ it->m_nY ] ) + o_rRowHeights[ it->m_nY ] = aSize.Height(); + } + + // add up sizes + for( sal_uInt32 i = 0; i < nColumns; i++ ) + aMatrixSize.Width() += o_rColumnWidths[i] + m_nBorderX; + if( nColumns > 0 ) + aMatrixSize.Width() -= m_nBorderX; + + for( sal_uInt32 i = 0; i < nRows; i++ ) + aMatrixSize.Height() += o_rRowHeights[i] + m_nBorderY; + if( nRows > 0 ) + aMatrixSize.Height() -= m_nBorderY; + + return aMatrixSize; +} + +Size MatrixArranger::getOptimalSize( WindowSizeType i_eType ) const +{ + std::vector aColumnWidths, aRowHeights; + return getOptimalSize( i_eType, aColumnWidths, aRowHeights ); +} + +void MatrixArranger::resize() +{ + // assure that we have at least one row and column + if( m_aElements.empty() ) + return; + + // check if we can get optimal size, else fallback to minimal size + std::vector aColumnWidths, aRowHeights; + Size aOptSize( getOptimalSize( WINDOWSIZE_PREFERRED, aColumnWidths, aRowHeights ) ); + if( aOptSize.Height() > m_aManagedArea.GetHeight() || + aOptSize.Width() > m_aManagedArea.GetWidth() ) + { + std::vector aMinColumnWidths, aMinRowHeights; + getOptimalSize( WINDOWSIZE_MINIMUM, aMinColumnWidths, aMinRowHeights ); + if( aOptSize.Height() > m_aManagedArea.GetHeight() ) + aRowHeights = aMinRowHeights; + if( aOptSize.Width() > m_aManagedArea.GetWidth() ) + aColumnWidths = aMinColumnWidths; + } + + // FIXME: distribute extra space available + + // prepare offsets + std::vector aColumnX( aColumnWidths.size() ); + aColumnX[0] = m_aManagedArea.Left() + m_nOuterBorder; + for( size_t i = 1; i < aColumnX.size(); i++ ) + aColumnX[i] = aColumnX[i-1] + aColumnWidths[i-1] + m_nBorderX; + + std::vector aRowY( aRowHeights.size() ); + aRowY[0] = m_aManagedArea.Top() + m_nOuterBorder; + for( size_t i = 1; i < aRowY.size(); i++ ) + aRowY[i] = aRowY[i-1] + aRowHeights[i-1] + m_nBorderY; + + // now iterate over the elements and assign their positions + for( std::vector< MatrixElement >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + Point aCellPos( aColumnX[it->m_nX], aRowY[it->m_nY] ); + Size aCellSize( aColumnWidths[it->m_nX], aRowHeights[it->m_nY] ); + if( it->m_pElement ) + it->m_pElement->SetPosSizePixel( aCellPos, aCellSize ); + else if( it->m_pChild ) + it->m_pChild->setManagedArea( Rectangle( aCellPos, aCellSize ) ); + } +} + +void MatrixArranger::setParentWindow( Window* i_pNewParent ) +{ + m_pParentWindow = i_pNewParent; + for( std::vector< MatrixElement >::const_iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + #if OSL_DEBUG_LEVEL > 0 + if( it->m_pElement ) + { + OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent ); + } + #endif + if( it->m_pChild ) + it->m_pChild->setParentWindow( i_pNewParent ); + } +} + +boost::shared_ptr MatrixArranger::getChild( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : boost::shared_ptr(); +} + +Window* MatrixArranger::getWindow( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL; +} + +sal_Int32 MatrixArranger::getExpandPriority( size_t i_nIndex ) const +{ + return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].getExpandPriority() : 0; +} + +void MatrixArranger::addWindow( Window* i_pWindow, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) +{ + sal_uInt64 nMapValue = getMap( i_nX, i_nY ); + std::map< sal_uInt64, size_t >::const_iterator it = m_aMatrixMap.find( nMapValue ); + if( it == m_aMatrixMap.end() ) + { + m_aMatrixMap[ nMapValue ] = m_aElements.size(); + m_aElements.push_back( MatrixElement( i_pWindow, i_nX, i_nY, boost::shared_ptr(), i_nExpandPrio ) ); + } + else + { + MatrixElement& rEle( m_aElements[ it->second ] ); + rEle.m_pElement = i_pWindow; + rEle.m_pChild.reset(); + rEle.m_nExpandPriority = i_nExpandPrio; + rEle.m_nX = i_nX; + rEle.m_nY = i_nY; + } +} + +void MatrixArranger::remove( Window* i_pWindow ) +{ + if( i_pWindow ) + { + for( std::vector< MatrixElement >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + if( it->m_pElement == i_pWindow ) + { + m_aMatrixMap.erase( getMap( it->m_nX, it->m_nY ) ); + m_aElements.erase( it ); + return; + } + } + } +} + +void MatrixArranger::addChild( boost::shared_ptr const &i_pChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) +{ + sal_uInt64 nMapValue = getMap( i_nX, i_nY ); + std::map< sal_uInt64, size_t >::const_iterator it = m_aMatrixMap.find( nMapValue ); + if( it == m_aMatrixMap.end() ) + { + m_aMatrixMap[ nMapValue ] = m_aElements.size(); + m_aElements.push_back( MatrixElement( NULL, i_nX, i_nY, i_pChild, i_nExpandPrio ) ); + } + else + { + MatrixElement& rEle( m_aElements[ it->second ] ); + rEle.m_pElement = 0; + rEle.m_pChild = i_pChild; + rEle.m_nExpandPriority = i_nExpandPrio; + rEle.m_nX = i_nX; + rEle.m_nY = i_nY; + } +} + +void MatrixArranger::remove( boost::shared_ptr const &i_pChild ) +{ + if( i_pChild ) + { + for( std::vector< MatrixElement >::iterator it = m_aElements.begin(); + it != m_aElements.end(); ++it ) + { + if( it->m_pChild == i_pChild ) + { + m_aMatrixMap.erase( getMap( it->m_nX, it->m_nY ) ); + m_aElements.erase( it ); + return; + } + } + } +} + diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 7bc771e7493e..fd6a2422defc 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -192,6 +192,65 @@ PrintDialog::NUpTabPage::~NUpTabPage() { } +void PrintDialog::NUpTabPage::Resize() +{ + Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); + + boost::shared_ptr aPage( new vcl::RowOrColumn() ); + aPage->setParentWindow( this ); + aPage->setOuterBorder( aBorder.Width() ); + aPage->addWindow( &maNupLine ); + + boost::shared_ptr aNupIndent( new vcl::Indenter( aPage.get(), aBorder.Width() ) ); + aPage->addChild( aNupIndent ); + boost::shared_ptr aNupColumn( new vcl::RowOrColumn( aNupIndent.get() ) ); + aNupIndent->setChild( aNupColumn ); + + boost::shared_ptr aNupRow( new vcl::RowOrColumn( aNupColumn.get(), false ) ); + aNupColumn->addChild( aNupRow ); + boost::shared_ptr aNupMat( new vcl::MatrixArranger( aNupRow.get(), aBorder.Width(), aBorder.Height() ) ); + aNupRow->addChild( aNupMat ); + aNupMat->addWindow( &maNupRowsTxt, 0, 0 ); + aNupMat->addWindow( &maNupRowsEdt, 1, 0 ); + aNupMat->addWindow( &maNupColTxt, 0, 1 ); + aNupMat->addWindow( &maNupColEdt, 1, 1 ); + aNupMat->addWindow( &maNupRepTxt, 0, 2 ); + aNupMat->addWindow( &maNupRepEdt, 1, 2 ); + boost::shared_ptr aOriCol( new vcl::RowOrColumn( aNupRow.get() ) ); + aNupRow->addChild( aOriCol ); + aOriCol->addWindow( &maNupPortrait ); + aOriCol->addWindow( &maNupLandscape ); + + aNupColumn->addWindow( &maBorderCB ); + + aPage->addWindow( &maMargins ); + + boost::shared_ptr aMargIndent( new vcl::Indenter( aPage.get(), aBorder.Width() ) ); + aPage->addChild( aMargIndent ); + boost::shared_ptr aMargColumn( new vcl::RowOrColumn( aMargIndent.get(), true, 2*aBorder.Height() ) ); + aMargIndent->setChild( aMargColumn ); + + boost::shared_ptr aMargMat( new vcl::MatrixArranger( aMargIndent.get(), aBorder.Width(), aBorder.Height() ) ); + aMargColumn->addChild( aMargMat ); + aMargMat->addWindow( &maLeftMarginTxt, 0, 0 ); + aMargMat->addWindow( &maLeftMarginEdt, 1, 0 ); + aMargMat->addWindow( &maRightMarginTxt, 3, 0 ); + aMargMat->addWindow( &maRightMarginEdt, 4, 0 ); + aMargMat->addWindow( &maTopMarginTxt, 0, 1 ); + aMargMat->addWindow( &maTopMarginEdt, 1, 1 ); + aMargMat->addWindow( &maBottomMarginTxt, 3, 1 ); + aMargMat->addWindow( &maBottomMarginEdt, 4, 1 ); + + boost::shared_ptr aSpacingMat( new vcl::MatrixArranger( aPage.get(), aBorder.Width(), aBorder.Height() ) ); + aMargColumn->addChild( aSpacingMat ); + aSpacingMat->addWindow( &maHSpaceTxt, 0, 0 ); + aSpacingMat->addWindow( &maHSpaceEdt, 1, 0 ); + aSpacingMat->addWindow( &maVSpaceTxt, 0, 1 ); + aSpacingMat->addWindow( &maVSpaceEdt, 1, 1 ); + + aPage->setManagedArea( Rectangle( Point(), GetOutputSizePixel() ) ); +} + void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& i_rMPS ) { maLeftMarginEdt.SetValue( maLeftMarginEdt.Normalize( i_rMPS.nLeftMargin ), FUNIT_100TH_MM ); -- cgit From e38ba906f787d79e8042f3a97bf44372cad4c0aa Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 24 Jun 2009 15:18:33 +0000 Subject: add: PrinterListener::setValue --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 6 ++++ vcl/inc/vcl/print.hxx | 11 +++++-- vcl/source/gdi/print3.cxx | 42 ++++++++++++++++++++++----- 3 files changed, 49 insertions(+), 10 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index b016920ae18e..f746f0462778 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -95,6 +95,7 @@ class ListenerProperties mnLastPageCount = nPages; if( mpState->bNeedRestart ) { + #if 0 // Warning: bad hack ahead // Apple does not give as a chance of changing the page count, // and they don't let us cancel the dialog either @@ -113,6 +114,11 @@ class ListenerProperties } } } + #else + NSWindow* pWindow = [NSApp modalWindow]; + if( pWindow ) + [pWindow cancelOperation: nil]; + #endif [[mpOp printInfo] setJobDisposition: NSPrintCancelJob]; } } diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 18529c07b432..ca3c6030f4e4 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -446,10 +446,15 @@ public: /* get the PropertyValue of a Property */ - com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ); - const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& rPropertyName ) const; + com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& i_rPropertyName ); + const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& i_rPropertyName ) const; - /* return the currently active UI options. These are the same passed to setUIOptions. + /* set a property value - can also be used to add another UI property + */ + void setValue( const rtl::OUString& i_rPropertyName, const com::sun::star::uno::Any& i_rValue ); + void setValue( const com::sun::star::beans::PropertyValue& i_rValue ); + + /* return the currently active UI options. These are the same that were passed to setUIOptions. */ const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& getUIOptions() const; /* set possible UI options. should only be done once before passing the PrinterListener diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index b7344d073386..24618e6162e3 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -791,14 +791,35 @@ const com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; } +void PrinterListener::setValue( const rtl::OUString& i_rName, const Any& i_rValue ) +{ + beans::PropertyValue aVal; + aVal.Name = i_rName; + aVal.Value = i_rValue; + + setValue( aVal ); +} + +void PrinterListener::setValue( const beans::PropertyValue& i_rValue ) +{ + std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = + mpImplData->maPropertyToIndex.find( i_rValue.Name ); + if( it != mpImplData->maPropertyToIndex.end() ) + mpImplData->maUIProperties[ it->second ] = i_rValue; + else + { + // insert correct index into property map + mpImplData->maPropertyToIndex[ i_rValue.Name ] = mpImplData->maUIProperties.size(); + mpImplData->maUIProperties.push_back( i_rValue ); + mpImplData->maUIPropertyEnabled.push_back( true ); + } +} + void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rOptions ) { DBG_ASSERT( mpImplData->maUIOptions.getLength() == 0, "setUIOptions called twice !" ); mpImplData->maUIOptions = i_rOptions; - mpImplData->maUIProperties.clear(); - mpImplData->maPropertyToIndex.clear(); - mpImplData->maUIPropertyEnabled.clear(); for( int i = 0; i < i_rOptions.getLength(); i++ ) { @@ -806,6 +827,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO i_rOptions[i].Value >>= aOptProp; bool bIsEnabled = true; bool bHaveProperty = false; + rtl::OUString aPropName; vcl::ImplPrinterListenerData::ControlDependency aDep; for( int n = 0; n < aOptProp.getLength(); n++ ) { @@ -816,8 +838,8 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO rEntry.Value >>= aVal; DBG_ASSERT( mpImplData->maPropertyToIndex.find( aVal.Name ) == mpImplData->maPropertyToIndex.end(), "duplicate property entry" ); - mpImplData->maPropertyToIndex[ aVal.Name ] = mpImplData->maUIProperties.size(); - mpImplData->maUIProperties.push_back( aVal ); + setValue( aVal ); + aPropName = aVal.Name; bHaveProperty = true; } else if( rEntry.Name.equalsAscii( "Enabled" ) ) @@ -837,9 +859,15 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO } if( bHaveProperty ) { - mpImplData->maUIPropertyEnabled.push_back( bIsEnabled ); + vcl::ImplPrinterListenerData::PropertyToIndexMap::const_iterator it = + mpImplData->maPropertyToIndex.find( aPropName ); + // sanity check + if( it != mpImplData->maPropertyToIndex.end() ) + { + mpImplData->maUIPropertyEnabled[ it->second ] = bIsEnabled; + } if( aDep.maDependsOnName.getLength() > 0 ) - mpImplData->maControlDependencies[ mpImplData->maUIProperties.back().Name ] = aDep; + mpImplData->maControlDependencies[ aPropName ] = aDep; } } } -- cgit From a22cd6b9c89f9d1bac898596942af3e889ee94d6 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 24 Jun 2009 15:59:36 +0000 Subject: save to file should be PDF --- vcl/aqua/source/gdi/salprn.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 8e22a83e1403..347e57aa8380 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -444,6 +444,8 @@ ULONG AquaSalInfoPrinter::GetCapabilities( const ImplJobSetup* i_pSetupData, USH return 1; case PRINTER_CAPABILITIES_EXTERNALDIALOG: return getUseNativeDialog() ? 1 : 0; + case PRINTER_CAPABILITIES_PDF: + return 1; default: break; }; return 0; -- cgit From d3afbfc954cd9e3f99e3bd77fa87d70055447e03 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 24 Jun 2009 17:37:07 +0000 Subject: prepare for more properties from the outside (e.g. API printing) --- vcl/inc/vcl/print.hxx | 21 +++++++++++---------- vcl/source/gdi/print3.cxx | 19 ++++++++++++++++++- vcl/source/window/printdlg.cxx | 9 +++++++-- 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index ca3c6030f4e4..941feb97b8e3 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -480,16 +480,17 @@ public: virtual void jobFinished(); // optionally release resources bound to the job // implementation details, not usable outside vcl - int SAL_DLLPRIVATE getFilteredPageCount(); - Size SAL_DLLPRIVATE getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); - Size SAL_DLLPRIVATE getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache = false ); - void SAL_DLLPRIVATE printFilteredPage( int i_nPage ); - void SAL_DLLPRIVATE setPrinter( const boost::shared_ptr& ); - void SAL_DLLPRIVATE setOptionChangeHdl( const Link& ); - void SAL_DLLPRIVATE createProgressDialog(); - void SAL_DLLPRIVATE setMultipage( const MultiPageSetup& ); - const MultiPageSetup& getMultipage() const; - void SAL_DLLPRIVATE setLastPage( sal_Bool i_bLastPage ); + SAL_DLLPRIVATE int getFilteredPageCount(); + SAL_DLLPRIVATE Size getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); + SAL_DLLPRIVATE Size getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache = false ); + SAL_DLLPRIVATE void printFilteredPage( int i_nPage ); + SAL_DLLPRIVATE void setPrinter( const boost::shared_ptr& ); + SAL_DLLPRIVATE void setOptionChangeHdl( const Link& ); + SAL_DLLPRIVATE void createProgressDialog(); + SAL_DLLPRIVATE void setMultipage( const MultiPageSetup& ); + SAL_DLLPRIVATE const MultiPageSetup& getMultipage() const; + SAL_DLLPRIVATE void setLastPage( sal_Bool i_bLastPage ); + SAL_DLLPRIVATE void pushPropertiesToPrinter(); }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 24618e6162e3..6ab34439b5e4 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -307,13 +307,14 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->getPrinter()->EnablePrintFile( TRUE ); pListener->getPrinter()->SetPrintFile( aFile ); } - pListener->getPrinter()->SetCopyCount( static_cast(aDlg.getCopyCount()), aDlg.isCollate() ); } catch( std::bad_alloc& ) { } } + pListener->pushPropertiesToPrinter(); + pListener->getPrinter()->StartJob( String( RTL_CONSTASCII_USTRINGPARAM( "FIXME: no job name" ) ), pListener ); @@ -447,6 +448,8 @@ void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; Size aPaperSize( i_rPrinter->PixelToLogic( i_rPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Name" ) ), + makeAny( rtl::OUString( i_rPrinter->GetName() ) ) ); } static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) @@ -967,6 +970,20 @@ const PrinterListener::MultiPageSetup& PrinterListener::getMultipage() const return mpImplData->maMultiPage; } +void PrinterListener::pushPropertiesToPrinter() +{ + sal_Int32 nCopyCount = 1; + // set copycount and collate + const beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ) ); + if( pVal ) + pVal->Value >>= nCopyCount; + sal_Bool bCollate = sal_False; + pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ) ); + if( pVal ) + pVal->Value >>= bCollate; + mpImplData->mpPrinter->SetCopyCount( static_cast(nCopyCount), bCollate ); +} + /* * PrinterOptionsHelper **/ diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index fd6a2422defc..138c75427d6d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -349,7 +349,7 @@ void PrintDialog::JobTabPage::readFromSettings() // do not actually make copy count persistent // the assumption is that this would lead to a lot of unwanted copies aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Copies" ) ) ); + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ) ); sal_Int32 nVal = aValue.toInt32(); maCopyCountField.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); #endif @@ -366,7 +366,7 @@ void PrintDialog::JobTabPage::storeToSettings() rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ), rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Copies" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), maCopyCountField.GetText() ); pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), @@ -1311,6 +1311,11 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) mnCurPage = sal_Int32( maPageEdit.GetValue() - 1 ); preparePreview( true, true ); } + else if( pEdit == &maJobPage.maCopyCountField ) + { + maPListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), + makeAny( sal_Int32(maJobPage.maCopyCountField.GetValue()) ) ); + } return 0; } -- cgit From de8ad26685ea2b9ed62433563670de0e7ebfa942 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 26 Jun 2009 10:50:42 +0000 Subject: #i92516# add: jobStarted, PrintableState --- vcl/aqua/source/gdi/salprn.cxx | 9 +++++++++ vcl/inc/vcl/print.hxx | 7 ++++++- vcl/source/gdi/print3.cxx | 43 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 347e57aa8380..ce213c1c042b 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -512,6 +512,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, return FALSE; BOOL bSuccess = FALSE; + bool bWasAborted = false; AquaSalInstance* pInst = GetSalData()->mpFirstInstance; PrintAccessoryViewState aAccViewState; sal_Int32 nAllPages = 0; @@ -525,6 +526,9 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( i_pSetupData ) SetData( ~0, i_pSetupData ); + // FIXME: jobStarted() should be done after the print dialog has ended (if there is one) + // how do I know when that might be ? + i_rListener.jobStarted(); do { if( aAccViewState.bNeedRestart ) @@ -603,6 +607,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, pInst->startedPrintJob(); [pPrintOperation runOperation]; pInst->endedPrintJob(); + bWasAborted = [[[pPrintOperation printInfo] jobDisposition] compare: NSPrintCancelJob] == NSOrderedSame; mbJob = false; if( pReleaseAfterUse ) [pReleaseAfterUse release]; @@ -624,6 +629,10 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, i_rListener.getFilteredPageFile( 0, aPageFile ); } + i_rListener.setJobState( bWasAborted + ? view::PrintableState_JOB_ABORTED + : view::PrintableState_JOB_SPOOLED ); + mnCurPageRangeStart = mnCurPageRangeCount = 0; return bSuccess; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 941feb97b8e3..c9fa42238c2f 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -42,6 +42,7 @@ #include "tools/multisel.hxx" #include "com/sun/star/beans/PropertyValue.hpp" +#include "com/sun/star/view/PrintableState.hpp" #include #include @@ -477,7 +478,10 @@ public: // must be overloaded by the app, return page size in 1/100th mm virtual com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getPageParameters( int i_nPage ) const = 0; virtual void printPage( int i_nPage ) const = 0; // must be overloaded by the app - virtual void jobFinished(); // optionally release resources bound to the job + virtual void jobStarted(); // will be called after a possible dialog has been shown and the real printjob starts + virtual void jobFinished( com::sun::star::view::PrintableState ); + + com::sun::star::view::PrintableState getJobState() const; // implementation details, not usable outside vcl SAL_DLLPRIVATE int getFilteredPageCount(); @@ -491,6 +495,7 @@ public: SAL_DLLPRIVATE const MultiPageSetup& getMultipage() const; SAL_DLLPRIVATE void setLastPage( sal_Bool i_bLastPage ); SAL_DLLPRIVATE void pushPropertiesToPrinter(); + SAL_DLLPRIVATE void setJobState( com::sun::star::view::PrintableState ); }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 6ab34439b5e4..12ef70ee958b 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -152,6 +152,7 @@ public: Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; sal_Bool mbLastPage; + view::PrintableState meJobState; vcl::PrinterListener::MultiPageSetup maMultiPage; @@ -161,6 +162,7 @@ public: ImplPrinterListenerData() : mbLastPage( sal_False ), + meJobState( view::PrintableState_JOB_STARTED ), mpProgress( NULL ) {} ~ImplPrinterListenerData() { delete mpProgress; } @@ -316,9 +318,9 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->pushPropertiesToPrinter(); pListener->getPrinter()->StartJob( String( RTL_CONSTASCII_USTRINGPARAM( "FIXME: no job name" ) ), - pListener ); + pListener ); - pListener->jobFinished(); + pListener->jobFinished( pListener->getJobState() ); } bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptr& i_pListener ) @@ -376,6 +378,9 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrStartJob( pPrintFile, Application::GetDisplayName(), maJobSetup.ImplGetConstData(), @@ -399,6 +404,11 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrsetJobState( view::PrintableState_JOB_STARTED ); + i_pListener->jobStarted(); + if( mpPrinter->StartJob( pPrintFile, i_rJobName, Application::GetDisplayName(), @@ -415,9 +425,14 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrprintFilteredPage( nPage ); } EndJob(); + + if( i_pListener->getJobState() == view::PrintableState_JOB_STARTED ) + i_pListener->setJobState( view::PrintableState_JOB_SPOOLED ); } else { + i_pListener->setJobState( view::PrintableState_JOB_FAILED ); + mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); if ( !mnError ) mnError = PRINTER_GENERALERROR; @@ -439,6 +454,16 @@ PrinterListener::~PrinterListener() delete mpImplData; } +view::PrintableState PrinterListener::getJobState() const +{ + return mpImplData->meJobState; +} + +void PrinterListener::setJobState( view::PrintableState i_eState ) +{ + mpImplData->meJobState = i_eState; +} + const boost::shared_ptr& PrinterListener::getPrinter() const { return mpImplData->mpPrinter; @@ -648,6 +673,9 @@ int PrinterListener::getFilteredPageCount() void PrinterListener::printFilteredPage( int i_nPage ) { + if( mpImplData->meJobState != view::PrintableState_JOB_STARTED ) + return; + GDIMetaFile aPageFile; Size aPageSize = getFilteredPageFile( i_nPage, aPageFile ); @@ -655,7 +683,10 @@ void PrinterListener::printFilteredPage( int i_nPage ) { // do nothing if printing is canceled if( mpImplData->mpProgress->isCanceled() ) - return; + { + setJobState( view::PrintableState_JOB_ABORTED ); + return; + } } bool bMultiPageOutput = mpImplData->maMultiPage.nRows != 1 || mpImplData->maMultiPage.nColumns != 1; @@ -730,7 +761,11 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->SetDrawMode( nRestoreDrawMode ); } -void PrinterListener::jobFinished() +void PrinterListener::jobStarted() +{ +} + +void PrinterListener::jobFinished( view::PrintableState ) { } -- cgit From 135137e4930fd36174007520755fc62a30d520aa Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 26 Jun 2009 11:35:24 +0000 Subject: #i92516# add: LocalFileName --- vcl/source/gdi/print3.cxx | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 12ef70ee958b..7c97946cb3f3 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -306,8 +306,8 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene rtl::OUString aFile = queryFile( pListener->getPrinter().get() ); if( ! aFile.getLength() ) return; - pListener->getPrinter()->EnablePrintFile( TRUE ); - pListener->getPrinter()->SetPrintFile( aFile ); + pListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ), + makeAny( aFile ) ); } } catch( std::bad_alloc& ) @@ -364,11 +364,25 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrgetValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ) ); + if( pFileValue ) + { + rtl::OUString aFile; + pFileValue->Value >>= aFile; + if( aFile.getLength() ) + { + mbPrintFile = TRUE; + maPrintFile = aFile; + } + } + + XubString* pPrintFile = NULL; if ( mbPrintFile ) pPrintFile = &maPrintFile; - else - pPrintFile = NULL; maJobName = i_rJobName; mnCurPage = 1; -- cgit From 497f21a8d0142c70d1c188a77055c509fd7cb690 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 26 Jun 2009 12:32:01 +0000 Subject: #i92516# add: MonitorVisible --- vcl/aqua/source/gdi/salprn.cxx | 8 +++++++- vcl/source/gdi/print3.cxx | 12 ++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index ce213c1c042b..1131fb54ccd5 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -526,6 +526,12 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( i_pSetupData ) SetData( ~0, i_pSetupData ); + // do we want a progress panel ? + sal_Bool bShowProgressPanel = sal_True; + beans::PropertyValue* pMonitor = i_rListener.getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); + if( pMonitor ) + pMonitor->Value >>= bShowProgressPanel; + // FIXME: jobStarted() should be done after the print dialog has ended (if there is one) // how do I know when that might be ? i_rListener.jobStarted(); @@ -598,7 +604,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, NSObject* pReleaseAfterUse = nil; bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; - [pPrintOperation setShowsProgressPanel: YES]; + [pPrintOperation setShowsProgressPanel: bShowProgressPanel ? YES : NO]; if( bShowPanel && mnCurPageRangeStart == 0 ) // only the first range of pages gets the accesory view pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withState: &aAccViewState]; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 7c97946cb3f3..7e5c68c700bb 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1004,8 +1004,16 @@ void PrinterListener::createProgressDialog() { if( ! mpImplData->mpProgress ) { - mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCount() ); - mpImplData->mpProgress->Show(); + sal_Bool bShow = sal_True; + beans::PropertyValue* pMonitor = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); + if( pMonitor ) + pMonitor->Value >>= bShow; + + if( bShow ) + { + mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCount() ); + mpImplData->mpProgress->Show(); + } } } -- cgit From 61e5696463d074e6bba86a12300f9623a32f71e7 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 26 Jun 2009 13:31:24 +0000 Subject: #i92516# add: Pages, Wait --- vcl/source/gdi/print3.cxx | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 7e5c68c700bb..1d6a614f847d 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -264,8 +264,18 @@ void Printer::PrintJob( const boost::shared_ptr& i_pListener, const JobSetup& i_rInitSetup ) { - PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup ); - Application::PostUserEvent( LINK( pAsync, PrintJobAsync, ExecJob ) ); + sal_Bool bSynchronous = sal_False; + beans::PropertyValue* pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + if( pVal ) + pVal->Value >>= bSynchronous; + + if( bSynchronous ) + ImplPrintJob( i_pListener, i_rInitSetup ); + else + { + PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup ); + Application::PostUserEvent( LINK( pAsync, PrintJobAsync, ExecJob ) ); + } } void Printer::ImplPrintJob( const boost::shared_ptr& i_pListener, @@ -284,6 +294,27 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene // reset last page property i_pListener->setLastPage( sal_False ); + beans::PropertyValue* pPagesVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pages" ) ) ); + if( pPagesVal ) + { + rtl::OUString aPagesVal; + pPagesVal->Value >>= aPagesVal; + if( aPagesVal.getLength() ) + { + // "Pages" attribute from API is now equivalent to "PageRange" + // AND "PrintContent" = 1 except calc where it is "PrintRange" = 1 + // Argh ! That sure needs cleaning up + beans::PropertyValue* pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + if( ! pVal ) + pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintContent" ) ) ); + if( pVal ) + { + pVal->Value = makeAny( sal_Int32( 1 ) ); + i_pListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PageRange" ) ), pPagesVal->Value ); + } + } + } + // check if the printer brings up its own dialog // in that case leave the work to that dialog const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); -- cgit From eabda9293f16222f50be0495de945d1df909010a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 26 Jun 2009 14:03:31 +0000 Subject: #i92516# add: JobName --- vcl/aqua/inc/salprn.h | 2 ++ vcl/aqua/source/gdi/salprn.cxx | 17 ++++++++++++----- vcl/inc/vcl/print.hxx | 2 +- vcl/inc/vcl/salprn.hxx | 7 ++++--- vcl/source/app/salvtables.cxx | 2 +- vcl/source/gdi/print3.cxx | 13 +++++++++---- 6 files changed, 29 insertions(+), 14 deletions(-) diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index 3a486d901ddc..a22503c22e78 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -103,6 +103,7 @@ class AquaSalInfoPrinter : public SalInfoPrinter // and concentrate the real work in one class // implement pull model print system BOOL StartJob( const String* i_pFileName, + const String& rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, vcl::PrinterListener& i_rListener, @@ -145,6 +146,7 @@ class AquaSalPrinter : public SalPrinter ImplJobSetup* i_pSetupData ); // implement pull model print system virtual BOOL StartJob( const String* i_pFileName, + const String& rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, vcl::PrinterListener& i_rListener ); diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 1131fb54ccd5..e06e8c48fd8b 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -503,6 +503,7 @@ static Size getPageSize( vcl::PrinterListener& i_rListener, sal_Int32 i_nPage ) } BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, + const String& i_rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, vcl::PrinterListener& i_rListener, @@ -605,6 +606,11 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: bShowProgressPanel ? YES : NO]; + + // set job title (since MacOSX 10.5) + if( [pPrintOperation respondsToSelector: @selector(setJobTitle:)] ) + [pPrintOperation performSelector: @selector(setJobTitle:) withObject: [CreateNSString( i_rJobName ) autorelease]]; + if( bShowPanel && mnCurPageRangeStart == 0 ) // only the first range of pages gets the accesory view pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withState: &aAccViewState]; @@ -707,6 +713,7 @@ AquaSalPrinter::~AquaSalPrinter() // ----------------------------------------------------------------------- BOOL AquaSalPrinter::StartJob( const String* i_pFileName, + const String& i_rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, vcl::PrinterListener& i_rListener ) @@ -721,16 +728,16 @@ BOOL AquaSalPrinter::StartJob( const String* i_pFileName, bIsQuickJob = true; } - return mpInfoPrinter->StartJob( i_pFileName, i_rAppName, i_pSetupData, i_rListener, bIsQuickJob ); + return mpInfoPrinter->StartJob( i_pFileName, i_rJobName, i_rAppName, i_pSetupData, i_rListener, bIsQuickJob ); } // ----------------------------------------------------------------------- BOOL AquaSalPrinter::StartJob( const XubString* i_pFileName, - const XubString& i_rJobName, - const XubString& i_rAppName, - ULONG i_nCopies, BOOL i_bCollate, - ImplJobSetup* i_pSetupData ) + const XubString& i_rJobName, + const XubString& i_rAppName, + ULONG i_nCopies, BOOL i_bCollate, + ImplJobSetup* i_pSetupData ) { DBG_ERROR( "should never be called" ); return FALSE; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index c9fa42238c2f..4cbd24dc02bd 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -264,7 +264,7 @@ private: SAL_DLLPRIVATE void ImplFindPaperFormatForUserSize( JobSetup& ); DECL_DLLPRIVATE_LINK( ImplDestroyPrinterAsync, void* ); - SAL_DLLPRIVATE bool StartJob( const XubString& rJobName, boost::shared_ptr& ); + SAL_DLLPRIVATE bool StartJob( const rtl::OUString& rJobName, boost::shared_ptr& ); static SAL_DLLPRIVATE ULONG ImplSalPrinterErrorCodeToVCL( ULONG nError ); diff --git a/vcl/inc/vcl/salprn.hxx b/vcl/inc/vcl/salprn.hxx index 923b3a750e36..a53adfe3518e 100644 --- a/vcl/inc/vcl/salprn.hxx +++ b/vcl/inc/vcl/salprn.hxx @@ -113,15 +113,16 @@ public: // public for Sal Implementation SalPrinter() {} virtual ~SalPrinter(); - virtual BOOL StartJob( const XubString* pFileName, - const XubString& rJobName, - const XubString& rAppName, + virtual BOOL StartJob( const String* pFileName, + const String& rJobName, + const String& rAppName, ULONG nCopies, BOOL bCollate, ImplJobSetup* pSetupData ) = 0; // implement for pull model print systems only, // default implementations (see salvtables.cxx) just returns FALSE virtual BOOL StartJob( const String* pFileName, + const String& rJobName, const String& rAppName, ImplJobSetup* pSetupData, vcl::PrinterListener& rListener ); diff --git a/vcl/source/app/salvtables.cxx b/vcl/source/app/salvtables.cxx index fe1ef6e7b992..7f872d0a9b63 100644 --- a/vcl/source/app/salvtables.cxx +++ b/vcl/source/app/salvtables.cxx @@ -90,7 +90,7 @@ SalPrinter::~SalPrinter() { } -BOOL SalPrinter::StartJob( const String*, const String&, +BOOL SalPrinter::StartJob( const String*, const String&, const String&, ImplJobSetup*, vcl::PrinterListener& ) { return FALSE; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 1d6a614f847d..d0ff5814aa51 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -348,13 +348,17 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene pListener->pushPropertiesToPrinter(); - pListener->getPrinter()->StartJob( String( RTL_CONSTASCII_USTRINGPARAM( "FIXME: no job name" ) ), - pListener ); + rtl::OUString aJobName; + beans::PropertyValue* pJobNameVal = pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "JobName" ) ) ); + if( pJobNameVal ) + pJobNameVal->Value >>= aJobName; + + pListener->getPrinter()->StartJob( String( aJobName ), pListener ); pListener->jobFinished( pListener->getJobState() ); } -bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptr& i_pListener ) +bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptr& i_pListener ) { mnError = PRINTER_OK; @@ -377,7 +381,7 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptr nDevCopy ) { bUserCopy = TRUE; @@ -427,6 +431,7 @@ bool Printer::StartJob( const XubString& i_rJobName, boost::shared_ptrStartJob( pPrintFile, + i_rJobName, Application::GetDisplayName(), maJobSetup.ImplGetConstData(), *i_pListener ) ) -- cgit From 51df7ffd3ff8107524ab2b238196a3ff91e7ad77 Mon Sep 17 00:00:00 2001 From: thb Date: Mon, 29 Jun 2009 15:15:41 +0200 Subject: #103174# Code from the ecntablet and eraser CWS; optionally improves user paint interactions in slideshow --- cppcanvas/inc/cppcanvas/color.hxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cppcanvas/inc/cppcanvas/color.hxx b/cppcanvas/inc/cppcanvas/color.hxx index 7441f6f2937a..e1cb30900e5e 100644 --- a/cppcanvas/inc/cppcanvas/color.hxx +++ b/cppcanvas/inc/cppcanvas/color.hxx @@ -83,6 +83,11 @@ namespace cppcanvas return (nRed << 24U)|(nGreen << 16U)|(nBlue << 8U)|(nAlpha); } + inline sal_Int32 makeColorARGB( sal_uInt8 nAlpha, sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue) + { + return (nAlpha << 24U)|(nRed << 16U)|(nGreen << 8U)|(nBlue); + } + } #endif /* _CPPCANVAS_COLOR_HXX */ -- cgit From a06a9f6d94bc1338fc68f01abfb6516fbf184918 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 29 Jun 2009 17:52:53 +0000 Subject: #i92516# replace missing preview in native mac dialog by our own --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 248 +++++++++++++++++++++++--- vcl/inc/vcl/svids.hrc | 1 + vcl/source/src/print.src | 10 ++ 3 files changed, 233 insertions(+), 26 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index f746f0462778..30811a1e0219 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -34,6 +34,13 @@ #include "aquaprintview.h" #include "salinst.h" #include "vcl/print.hxx" +#include "vcl/image.hxx" +#include "vcl/virdev.hxx" +#include "vcl/svdata.hxx" + +#include "vcl/svids.hrc" + +#include "tools/resary.hxx" #include @@ -44,10 +51,24 @@ using namespace com::sun::star::uno; /* Note: the accesory view as implemented here is already deprecated in Leopard. Unfortunately as long as our baseline is Tiger we cannot gain the advantages over multiple accessory views - as well havs haing accessory views AND a preview (as long as you are linked vs. 10.4 libraries + as well havs having accessory views AND a preview (as long as you are linked vs. 10.4 libraries the preview insists on not being present. This is unfortunate. */ +class ListenerProperties; + +@interface ControlTarget : NSObject +{ + ListenerProperties* mpListener; +} +-(id)initWithListenerMap: (ListenerProperties*)pListener; +-(void)triggered:(id)pSender; +-(void)triggeredNumeric:(id)pSender; +-(void)triggeredPreview:(id)pSender; +-(void)dealloc; +@end + + class ListenerProperties { vcl::PrinterListener* mpListener; @@ -59,11 +80,18 @@ class ListenerProperties sal_Int32 mnLastPageCount; PrintAccessoryViewState* mpState; NSPrintOperation* mpOp; + NSView* mpAccessoryView; NSTabView* mpTabView; + NSBox* mpPreviewBox; + NSImageView* mpPreview; + NSTextField* mpPageEdit; + NSStepper* mpStepper; + NSTextView* mpPagesLabel; public: ListenerProperties( vcl::PrinterListener* i_pListener, NSPrintOperation* i_pOp, + NSView* i_pAccessoryView, NSTabView* i_pTabView, PrintAccessoryViewState* i_pState ) : mpListener( i_pListener ), @@ -71,7 +99,13 @@ class ListenerProperties mnLastPageCount( i_pListener->getPageCount() ), mpState( i_pState ), mpOp( i_pOp ), - mpTabView( i_pTabView ) + mpAccessoryView( i_pAccessoryView ), + mpTabView( i_pTabView ), + mpPreviewBox( nil ), + mpPreview( nil ), + mpPageEdit( nil ), + mpStepper( nil ), + mpPagesLabel( nil ) { mpState->bNeedRestart = false; } @@ -121,6 +155,11 @@ class ListenerProperties #endif [[mpOp printInfo] setJobDisposition: NSPrintCancelJob]; } + else + { + sal_Int32 nPage = [mpStepper intValue]; + updatePreviewImage( nPage-1 ); + } } int addNameTag( const rtl::OUString& i_rPropertyName ) @@ -248,6 +287,153 @@ class ListenerProperties } } } + + void updatePreviewImage( sal_Int32 i_nPage ) + { + sal_Int32 nPages = mpListener->getFilteredPageCount(); + NSRect aViewFrame = [mpPreview frame]; + Size aPixelSize( static_cast(aViewFrame.size.width), + static_cast(aViewFrame.size.height) ); + if( i_nPage >= 0 && nPages > i_nPage ) + { + GDIMetaFile aMtf; + Size aPageSize( mpListener->getFilteredPageFile( i_nPage, aMtf, false ) ); + VirtualDevice aDev; + Size aLogicSize( aDev.PixelToLogic( aPixelSize, MapMode( MAP_100TH_MM ) ) ); + double fScaleX = double(aLogicSize.Width())/double(aPageSize.Width()); + double fScaleY = double(aLogicSize.Height())/double(aPageSize.Height()); + double fScale = (fScaleX < fScaleY) ? fScaleX : fScaleY; + aMtf.WindStart(); + aMtf.Scale( fScale, fScale ); + aMtf.WindStart(); + aLogicSize.Width() = long(double(aPageSize.Width()) * fScale); + aLogicSize.Height() = long(double(aPageSize.Height()) * fScale); + aPixelSize = aDev.LogicToPixel( aLogicSize, MapMode( MAP_100TH_MM ) ); + aDev.SetOutputSizePixel( aPixelSize ); + aMtf.WindStart(); + aDev.SetMapMode( MapMode( MAP_100TH_MM ) ); + aMtf.Play( &aDev, Point( 0, 0 ), aLogicSize ); + aDev.EnableMapMode( FALSE ); + Image aImage( aDev.GetBitmap( Point( 0, 0 ), aPixelSize ) ); + NSImage* pImage = CreateNSImage( aImage ); + [mpPreview setImage: [pImage autorelease]]; + } + else + [mpPreview setImage: nil]; + } + + void setupPreview( ControlTarget* i_pCtrlTarget ) + { + // get some needed resources + ResStringArray aStrings( VclResId( SV_PRINT_NATIVE_STRINGS ) ); + + DBG_ASSERT( aStrings.Count() >= 3, "resources not found !" ); + if( aStrings.Count() < 3 ) + return; + + // get the preview control + NSRect aPreviewFrame = [mpAccessoryView frame]; + aPreviewFrame.origin.x = 0; + aPreviewFrame.origin.y = 5; + aPreviewFrame.size.width = 190; + aPreviewFrame.size.height -= 7; + + // create a box to put the preview controls in + mpPreviewBox = [[NSBox alloc] initWithFrame: aPreviewFrame]; + [mpPreviewBox setTitle: [CreateNSString( aStrings.GetString( 0 ) ) autorelease]]; + [mpAccessoryView addSubview: [mpPreviewBox autorelease]]; + + // now create the image view of the preview + NSSize aMargins = [mpPreviewBox contentViewMargins]; + aPreviewFrame.origin.x = 0; + aPreviewFrame.origin.y = 34; + aPreviewFrame.size.height -= 61; + mpPreview = [[NSImageView alloc] initWithFrame: aPreviewFrame]; + [mpPreview setImageScaling: NSScaleNone]; + [mpPreview setImageAlignment: NSImageAlignCenter]; + [mpPreview setImageFrameStyle: NSImageFrameNone]; + [mpPreviewBox addSubview: [mpPreview autorelease]]; + + // add a label + sal_Int32 nPages = mpListener->getFilteredPageCount(); + rtl::OUStringBuffer aBuf( 16 ); + aBuf.appendAscii( "/ " ); + aBuf.append( rtl::OUString::valueOf( nPages ) ); + + NSString* pText = CreateNSString( aBuf.makeStringAndClear() ); + NSRect aTextRect = { { 100, 5 }, { 100, 22 } }; + mpPagesLabel = [[NSTextView alloc] initWithFrame: aTextRect]; + [mpPagesLabel setFont: [NSFont controlContentFontOfSize: 0]]; + [mpPagesLabel setEditable: NO]; + [mpPagesLabel setSelectable: NO]; + [mpPagesLabel setDrawsBackground: NO]; + [mpPagesLabel setString: [pText autorelease]]; + [mpPagesLabel setToolTip: [CreateNSString( aStrings.GetString( 2 ) ) autorelease]]; + [mpPreviewBox addSubview: [mpPagesLabel autorelease]]; + + NSRect aFieldRect = { { 45, 5 }, { 35, 25 } }; + mpPageEdit = [[NSTextField alloc] initWithFrame: aFieldRect]; + [mpPageEdit setEditable: YES]; + [mpPageEdit setSelectable: YES]; + [mpPageEdit setDrawsBackground: YES]; + [mpPageEdit setToolTip: [CreateNSString( aStrings.GetString( 1 ) ) autorelease]]; + [mpPreviewBox addSubview: [mpPageEdit autorelease]]; + + // add a stepper control + NSRect aStepFrame = { { 85, 5 }, { 15, 25 } }; + mpStepper = [[NSStepper alloc] initWithFrame: aStepFrame]; + [mpStepper setIncrement: 1]; + [mpStepper setValueWraps: NO]; + [mpPreviewBox addSubview: [mpStepper autorelease]]; + + // constrain the text field to decimal numbers + NSNumberFormatter* pFormatter = [[NSNumberFormatter alloc] init]; + [pFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4]; + [pFormatter setMinimum: [[NSNumber numberWithInt: 1] autorelease]]; + [pFormatter setMaximum: [[NSNumber numberWithInt: nPages] autorelease]]; + [pFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; + [pFormatter setAllowsFloats: NO]; + [pFormatter setMaximumFractionDigits: 0]; + [mpPageEdit setFormatter: pFormatter]; + [mpStepper setMinValue: 1]; + [mpStepper setMaxValue: nPages]; + + [mpPageEdit setIntValue: 1]; + [mpStepper setIntValue: 1]; + + // connect target and action + [mpStepper setTarget: i_pCtrlTarget]; + [mpStepper setAction: @selector(triggeredPreview:)]; + [mpPageEdit setTarget: i_pCtrlTarget]; + [mpPageEdit setAction: @selector(triggeredPreview:)]; + + // set first preview image + updatePreviewImage( 0 ); + } + + void changePreview( NSObject* i_pSender ) + { + if( [i_pSender isMemberOfClass: [NSTextField class]] ) + { + NSTextField* pField = (NSTextField*)i_pSender; + if( pField == mpPageEdit ) // sanity check + { + sal_Int32 nPage = [pField intValue]; + [mpStepper setIntValue: nPage]; + updatePreviewImage( nPage-1 ); + } + } + else if( [i_pSender isMemberOfClass: [NSStepper class]] ) + { + NSStepper* pStepper = (NSStepper*)i_pSender; + if( pStepper == mpStepper ) // sanity check + { + sal_Int32 nPage = [pStepper intValue]; + [mpPageEdit setIntValue: nPage]; + updatePreviewImage( nPage-1 ); + } + } + } }; static void filterAccelerator( rtl::OUString& io_rText ) @@ -258,16 +444,6 @@ static void filterAccelerator( rtl::OUString& io_rText ) io_rText = aBuf.makeStringAndClear(); } -@interface ControlTarget : NSObject -{ - ListenerProperties* mpListener; -} --(id)initWithListenerMap: (ListenerProperties*)pListener; --(void)triggered:(id)pSender; --(void)triggeredNumeric:(id)pSender; --(void)dealloc; -@end - @implementation ControlTarget -(id)initWithListenerMap: (ListenerProperties*)pListener { @@ -350,6 +526,10 @@ static void filterAccelerator( rtl::OUString& io_rText ) } mpListener->updateEnableState(); } +-(void)triggeredPreview:(id)pSender +{ + mpListener->changePreview( pSender ); +} -(void)dealloc { delete mpListener; @@ -390,6 +570,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rMaxSize.height = aUnion.size.height; } + @implementation AquaPrintAccessoryView +(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withState: (PrintAccessoryViewState*)pState; { @@ -400,12 +581,16 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSView* pCurParent = 0; long nCurY = 0; long nCurX = 0; - NSRect aViewFrame = { { 0, 0 }, {400, 400 } }; + NSRect aViewFrame = { { 0, 0 }, {600, 400 } }; + NSRect aTabViewFrame = { { 200, 0 }, {400, 400 } }; NSSize aMaxTabSize = { 0, 0 }; - NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aViewFrame]; + NSView* pAccessoryView = [[NSView alloc] initWithFrame: aViewFrame]; + NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aTabViewFrame]; + [pAccessoryView addSubview: [pTabView autorelease]]; + sal_Bool bIgnoreSubgroup = sal_False; - ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pTabView, pState ); + ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pAccessoryView, pTabView, pState ); ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; for( int i = 0; i < rOptions.getLength(); i++ ) @@ -492,7 +677,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSTabViewItem* pItem = [[NSTabViewItem alloc] initWithIdentifier: pLabel ]; [pItem setLabel: pLabel]; [pTabView addTabViewItem: pItem]; - pCurParent = [[NSView alloc] initWithFrame: aViewFrame]; + pCurParent = [[NSView alloc] initWithFrame: aTabViewFrame]; [pItem setView: pCurParent]; [pLabel release]; @@ -509,12 +694,13 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSString* pText = CreateNSString( aText ); NSRect aTextRect = { { 0, 0 }, { 300, 15 } }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; [pTextView setDrawsBackground: NO]; [pTextView setString: pText]; [pTextView sizeToFit]; // FIXME: this does nothing - [pCurParent addSubview: pTextView]; + [pCurParent addSubview: [pTextView autorelease]]; aTextRect = [pTextView frame]; // move to nCurY @@ -542,7 +728,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) pVal->Value >>= bVal; [pBtn setState: bVal ? NSOnState : NSOffState]; [pBtn sizeToFit]; - [pCurParent addSubview: pBtn]; + [pCurParent addSubview: [pBtn autorelease]]; // connect target [pBtn setTarget: pCtrlTarget]; @@ -572,12 +758,13 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSString* pText = CreateNSString( aText ); NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, { 300, 15 } }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; [pTextView setDrawsBackground: NO]; [pTextView setString: pText]; [pTextView sizeToFit]; // FIXME: this does nothing - [pCurParent addSubview: pTextView]; + [pCurParent addSubview: [pTextView autorelease]]; // move to nCurY aTextRect.origin.y = nCurY - aTextRect.size.height; @@ -634,7 +821,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // move it down, so it comes to the correct position aRadioRect.origin.y = nCurY - aRadioRect.size.height; [pMatrix setFrame: aRadioRect]; - [pCurParent addSubview: pMatrix]; + [pCurParent addSubview: [pMatrix autorelease]]; // update nCurY nCurY = aRadioRect.origin.y - 5; @@ -662,6 +849,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aTextSize.height += 3; NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; [pTextView setDrawsBackground: NO]; @@ -669,7 +857,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pTextView setVerticallyResizable: NO]; [pTextView setHorizontallyResizable: YES]; [pTextView sizeToFit]; // FIXME: this actually does nothing - [pCurParent addSubview: pTextView]; + [pCurParent addSubview: [pTextView autorelease]]; aTextRect = [pTextView frame]; @@ -699,7 +887,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pBtn setTag: pListenerProperties->addNameTag( aPropertyName )]; [pBtn sizeToFit]; - [pCurParent addSubview: pBtn]; + [pCurParent addSubview: [pBtn autorelease]]; // connect target and action [pBtn setTarget: pCtrlTarget]; @@ -743,12 +931,13 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aTextSize.height += 3; NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; + [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; [pTextView setEditable: NO]; [pTextView setSelectable: NO]; [pTextView setDrawsBackground: NO]; [pTextView setString: pText]; [pTextView sizeToFit]; // FIXME: this does nothing - [pCurParent addSubview: pTextView]; + [pCurParent addSubview: [pTextView autorelease]]; // move to nCurY aTextRect.origin.y = nCurY - aTextRect.size.height; @@ -770,7 +959,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pFieldView setSelectable: YES]; [pFieldView setDrawsBackground: YES]; [pFieldView sizeToFit]; // FIXME: this does nothing - [pCurParent addSubview: pFieldView]; + [pCurParent addSubview: [pFieldView autorelease]]; // add the field to observed controls for enabled state changes // also add a tag just for this purpose @@ -795,15 +984,17 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pStep setIncrement: 1]; [pStep setValueWraps: NO]; [pStep setTag: nTag]; - [pCurParent addSubview: pStep]; + [pCurParent addSubview: [pStep autorelease]]; pListenerProperties->addObservedControl( pStep ); [pStep setTarget: pCtrlTarget]; [pStep setAction: @selector(triggered:)]; // constrain the text field to decimal numbers NSNumberFormatter* pFormatter = [[NSNumberFormatter alloc] init]; + [pFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4]; [pFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; [pFormatter setAllowsFloats: NO]; + [pFormatter setMaximumFractionDigits: 0]; if( nMinValue != nMaxValue ) { [pFormatter setMinimum: [[NSNumber numberWithInt: nMinValue] autorelease]]; @@ -865,9 +1056,14 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) if( aTabCtrlSize.width < aMaxTabSize.width + 10 ) aTabCtrlSize.width = aMaxTabSize.width + 10; [pTabView setFrameSize: aTabCtrlSize]; + aViewFrame.size.width = aTabCtrlSize.width + aTabViewFrame.origin.x; + aViewFrame.size.height = aTabCtrlSize.height + aTabViewFrame.origin.y; + [pAccessoryView setFrameSize: aViewFrame.size]; + + pListenerProperties->setupPreview( pCtrlTarget ); // set the accessory view - [pOp setAccessoryView: pTabView]; + [pOp setAccessoryView: [pAccessoryView autorelease]]; // set the current selecte tab item if( pState->nLastPage >= 0 && pState->nLastPage < [pTabView numberOfTabViewItems] ) diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 0edbd5661335..a774717e8078 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -138,6 +138,7 @@ #define SV_PRINT_PROGRESS_CANCEL 1 #define SV_PRINT_PROGRESS_TEXT 2 +#define SV_PRINT_NATIVE_STRINGS 2050 #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index d629ba7c04d2..a653798332a2 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -395,3 +395,13 @@ ModelessDialog SV_DLG_PRINT_PROGRESS Center = TRUE; }; }; + +StringArray SV_PRINT_NATIVE_STRINGS +{ + ItemList [en-US] = + { + < "Preview"; >; + < "Page Number"; >; + < "Number of pages"; >; + }; +}; -- cgit From 6587abd0796af81128602a7e43927fb3eaead419 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 6 Jul 2009 10:54:21 +0000 Subject: rename PrinterListener, add: getValues, abortJob --- vcl/aqua/inc/aquaprintview.h | 7 +- vcl/aqua/inc/salprn.h | 4 +- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 116 ++++++++--------- vcl/aqua/source/gdi/aquaprintview.mm | 6 +- vcl/aqua/source/gdi/salprn.cxx | 34 ++--- vcl/inc/vcl/oldprintadaptor.hxx | 2 +- vcl/inc/vcl/print.hxx | 24 ++-- vcl/inc/vcl/prndlg.hxx | 6 +- vcl/inc/vcl/salprn.hxx | 4 +- vcl/source/app/salvtables.cxx | 2 +- vcl/source/gdi/oldprintadaptor.cxx | 2 +- vcl/source/gdi/print3.cxx | 175 ++++++++++++++------------ vcl/source/window/printdlg.cxx | 68 +++++----- 13 files changed, 236 insertions(+), 214 deletions(-) diff --git a/vcl/aqua/inc/aquaprintview.h b/vcl/aqua/inc/aquaprintview.h index a3984333f84e..55a85678cd50 100755 --- a/vcl/aqua/inc/aquaprintview.h +++ b/vcl/aqua/inc/aquaprintview.h @@ -38,7 +38,6 @@ #include "vcl/print.hxx" class AquaSalInfoPrinter; -namespace vcl { class PrinterListener; } struct PrintAccessoryViewState { @@ -51,10 +50,10 @@ struct PrintAccessoryViewState @interface AquaPrintView : NSView { - vcl::PrinterListener* mpListener; + vcl::PrinterController* mpController; AquaSalInfoPrinter* mpInfoPrinter; } --(id)initWithListener: (vcl::PrinterListener*)pListener withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter; +-(id)initWithController: (vcl::PrinterController*)pController withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter; -(MacOSBOOL)knowsPageRange: (NSRangePointer)range; -(NSRect)rectForPage: (int)page; -(NSPoint)locationOfPrintRect: (NSRect)aRect; @@ -64,7 +63,7 @@ struct PrintAccessoryViewState @interface AquaPrintAccessoryView : NSObject { } -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withState: (PrintAccessoryViewState*)pState; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withController: (vcl::PrinterController*)pController withState: (PrintAccessoryViewState*)pState; @end diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index a22503c22e78..e265f800906d 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -106,7 +106,7 @@ class AquaSalInfoPrinter : public SalInfoPrinter const String& rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterListener& i_rListener, + vcl::PrinterController& i_rController, bool bIsQuickJob ); BOOL EndJob(); BOOL AbortJob(); @@ -149,7 +149,7 @@ class AquaSalPrinter : public SalPrinter const String& rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterListener& i_rListener ); + vcl::PrinterController& i_rListener ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 30811a1e0219..645de97d7ac3 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -55,13 +55,13 @@ using namespace com::sun::star::uno; the preview insists on not being present. This is unfortunate. */ -class ListenerProperties; +class ControllerProperties; @interface ControlTarget : NSObject { - ListenerProperties* mpListener; + ControllerProperties* mpController; } --(id)initWithListenerMap: (ListenerProperties*)pListener; +-(id)initWithControllerMap: (ControllerProperties*)pController; -(void)triggered:(id)pSender; -(void)triggeredNumeric:(id)pSender; -(void)triggeredPreview:(id)pSender; @@ -69,9 +69,9 @@ class ListenerProperties; @end -class ListenerProperties +class ControllerProperties { - vcl::PrinterListener* mpListener; + vcl::PrinterController* mpController; std::map< int, rtl::OUString > maTagToPropertyName; std::map< int, sal_Int32 > maTagToValueInt; std::map< NSView*, NSView* > maViewPairMap; @@ -89,14 +89,14 @@ class ListenerProperties NSTextView* mpPagesLabel; public: - ListenerProperties( vcl::PrinterListener* i_pListener, - NSPrintOperation* i_pOp, - NSView* i_pAccessoryView, - NSTabView* i_pTabView, - PrintAccessoryViewState* i_pState ) - : mpListener( i_pListener ), + ControllerProperties( vcl::PrinterController* i_pController, + NSPrintOperation* i_pOp, + NSView* i_pAccessoryView, + NSTabView* i_pTabView, + PrintAccessoryViewState* i_pState ) + : mpController( i_pController ), mnNextTag( 0 ), - mnLastPageCount( i_pListener->getPageCount() ), + mnLastPageCount( i_pController->getPageCount() ), mpState( i_pState ), mpOp( i_pOp ), mpAccessoryView( i_pAccessoryView ), @@ -112,10 +112,10 @@ class ListenerProperties void updatePrintJob() { - // TODO: refresh page count etc from mpListener + // TODO: refresh page count etc from mpController // page range may have changed depending on options - sal_Int32 nPages = mpListener->getPageCount(); + sal_Int32 nPages = mpController->getPageCount(); #if OSL_DEBUG_LEVEL > 1 if( nPages != mnLastPageCount ) fprintf( stderr, "trouble: number of pages changed from %ld to %ld !\n", mnLastPageCount, nPages ); @@ -203,7 +203,7 @@ class ListenerProperties std::map< int, sal_Int32 >::const_iterator value_it = maTagToValueInt.find( i_nTag ); if( name_it != maTagToPropertyName.end() && value_it != maTagToValueInt.end() ) { - PropertyValue* pVal = mpListener->getValue( name_it->second ); + PropertyValue* pVal = mpController->getValue( name_it->second ); if( pVal ) { pVal->Value <<= value_it->second; @@ -217,7 +217,7 @@ class ListenerProperties std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); if( name_it != maTagToPropertyName.end() ) { - PropertyValue* pVal = mpListener->getValue( name_it->second ); + PropertyValue* pVal = mpController->getValue( name_it->second ); if( pVal ) { pVal->Value <<= i_nValue; @@ -231,7 +231,7 @@ class ListenerProperties std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); if( name_it != maTagToPropertyName.end() ) { - PropertyValue* pVal = mpListener->getValue( name_it->second ); + PropertyValue* pVal = mpController->getValue( name_it->second ); if( pVal ) { pVal->Value <<= i_bValue; @@ -245,7 +245,7 @@ class ListenerProperties std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( i_nTag ); if( name_it != maTagToPropertyName.end() ) { - PropertyValue* pVal = mpListener->getValue( name_it->second ); + PropertyValue* pVal = mpController->getValue( name_it->second ); if( pVal ) { pVal->Value <<= i_rValue; @@ -273,7 +273,7 @@ class ListenerProperties std::map< int, rtl::OUString >::const_iterator name_it = maTagToPropertyName.find( nTag ); if( name_it != maTagToPropertyName.end() ) { - MacOSBOOL bEnabled = mpListener->isUIOptionEnabled( name_it->second ) ? YES : NO; + MacOSBOOL bEnabled = mpController->isUIOptionEnabled( name_it->second ) ? YES : NO; if( pCtrl ) { [pCtrl setEnabled: bEnabled]; @@ -290,14 +290,14 @@ class ListenerProperties void updatePreviewImage( sal_Int32 i_nPage ) { - sal_Int32 nPages = mpListener->getFilteredPageCount(); + sal_Int32 nPages = mpController->getFilteredPageCount(); NSRect aViewFrame = [mpPreview frame]; Size aPixelSize( static_cast(aViewFrame.size.width), static_cast(aViewFrame.size.height) ); if( i_nPage >= 0 && nPages > i_nPage ) { GDIMetaFile aMtf; - Size aPageSize( mpListener->getFilteredPageFile( i_nPage, aMtf, false ) ); + Size aPageSize( mpController->getFilteredPageFile( i_nPage, aMtf, false ) ); VirtualDevice aDev; Size aLogicSize( aDev.PixelToLogic( aPixelSize, MapMode( MAP_100TH_MM ) ) ); double fScaleX = double(aLogicSize.Width())/double(aPageSize.Width()); @@ -355,7 +355,7 @@ class ListenerProperties [mpPreviewBox addSubview: [mpPreview autorelease]]; // add a label - sal_Int32 nPages = mpListener->getFilteredPageCount(); + sal_Int32 nPages = mpController->getFilteredPageCount(); rtl::OUStringBuffer aBuf( 16 ); aBuf.appendAscii( "/ " ); aBuf.append( rtl::OUString::valueOf( nPages ) ); @@ -445,11 +445,11 @@ static void filterAccelerator( rtl::OUString& io_rText ) } @implementation ControlTarget --(id)initWithListenerMap: (ListenerProperties*)pListener +-(id)initWithControllerMap: (ControllerProperties*)pController { if( (self = [super init]) ) { - mpListener = pListener; + mpController = pController; } return self; } @@ -462,14 +462,14 @@ static void filterAccelerator( rtl::OUString& io_rText ) if( pSelected ) { int nTag = [pSelected tag]; - mpListener->changePropertyWithIntValue( nTag ); + mpController->changePropertyWithIntValue( nTag ); } } else if( [pSender isMemberOfClass: [NSButton class]] ) { NSButton* pBtn = (NSButton*)pSender; int nTag = [pBtn tag]; - mpListener->changePropertyWithBoolValue( nTag, [pBtn state] == NSOnState ); + mpController->changePropertyWithBoolValue( nTag, [pBtn state] == NSOnState ); } else if( [pSender isMemberOfClass: [NSMatrix class]] ) { @@ -478,7 +478,7 @@ static void filterAccelerator( rtl::OUString& io_rText ) { NSButtonCell* pCell = (NSButtonCell*)pObj; int nTag = [pCell tag]; - mpListener->changePropertyWithIntValue( nTag ); + mpController->changePropertyWithIntValue( nTag ); } } else if( [pSender isMemberOfClass: [NSTextField class]] ) @@ -486,13 +486,13 @@ static void filterAccelerator( rtl::OUString& io_rText ) NSTextField* pField = (NSTextField*)pSender; int nTag = [pField tag]; rtl::OUString aValue = GetOUString( [pSender stringValue] ); - mpListener->changePropertyWithStringValue( nTag, aValue ); + mpController->changePropertyWithStringValue( nTag, aValue ); } else { DBG_ERROR( "unsupported class" ); } - mpListener->updateEnableState(); + mpController->updateEnableState(); } -(void)triggeredNumeric:(id)pSender; { @@ -502,11 +502,11 @@ static void filterAccelerator( rtl::OUString& io_rText ) int nTag = [pField tag]; sal_Int64 nValue = [pField intValue]; - NSView* pOther = mpListener->getPair( pField ); + NSView* pOther = mpController->getPair( pField ); if( pOther ) [(NSControl*)pOther setIntValue: nValue]; - mpListener->changePropertyWithIntValue( nTag, nValue ); + mpController->changePropertyWithIntValue( nTag, nValue ); } else if( [pSender isMemberOfClass: [NSStepper class]] ) { @@ -514,25 +514,25 @@ static void filterAccelerator( rtl::OUString& io_rText ) int nTag = [pStep tag]; sal_Int64 nValue = [pStep intValue]; - NSView* pOther = mpListener->getPair( pStep ); + NSView* pOther = mpController->getPair( pStep ); if( pOther ) [(NSControl*)pOther setIntValue: nValue]; - mpListener->changePropertyWithIntValue( nTag, nValue ); + mpController->changePropertyWithIntValue( nTag, nValue ); } else { DBG_ERROR( "unsupported class" ); } - mpListener->updateEnableState(); + mpController->updateEnableState(); } -(void)triggeredPreview:(id)pSender { - mpListener->changePreview( pSender ); + mpController->changePreview( pSender ); } -(void)dealloc { - delete mpListener; + delete mpController; [super dealloc]; } @end @@ -572,9 +572,9 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) @implementation AquaPrintAccessoryView -+(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withListener: (vcl::PrinterListener*)pListener withState: (PrintAccessoryViewState*)pState; ++(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withController: (vcl::PrinterController*)pController withState: (PrintAccessoryViewState*)pState; { - const Sequence< PropertyValue >& rOptions( pListener->getUIOptions() ); + const Sequence< PropertyValue >& rOptions( pController->getUIOptions() ); if( rOptions.getLength() == 0 ) return nil; @@ -590,8 +590,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) sal_Bool bIgnoreSubgroup = sal_False; - ListenerProperties* pListenerProperties = new ListenerProperties( pListener, pOp, pAccessoryView, pTabView, pState ); - ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithListenerMap: pListenerProperties]; + ControllerProperties* pControllerProperties = new ControllerProperties( pController, pOp, pAccessoryView, pTabView, pState ); + ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithControllerMap: pControllerProperties]; for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -723,7 +723,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pBtn setButtonType: NSSwitchButton]; [pBtn setTitle: pText]; sal_Bool bVal = sal_False; - PropertyValue* pVal = pListener->getValue( aPropertyName ); + PropertyValue* pVal = pController->getValue( aPropertyName ); if( pVal ) pVal->Value >>= bVal; [pBtn setState: bVal ? NSOnState : NSOffState]; @@ -733,8 +733,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // connect target [pBtn setTarget: pCtrlTarget]; [pBtn setAction: @selector(triggered:)]; - int nTag = pListenerProperties->addNameTag( aPropertyName ); - pListenerProperties->addObservedControl( pBtn ); + int nTag = pControllerProperties->addNameTag( aPropertyName ); + pControllerProperties->addObservedControl( pBtn ); [pBtn setTag: nTag]; aCheckRect = [pBtn frame]; @@ -793,7 +793,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) numberOfColumns: 1]; // get currently selected value sal_Int32 nSelectVal = 0; - PropertyValue* pVal = pListener->getValue( aPropertyName ); + PropertyValue* pVal = pController->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; // set individual titles @@ -807,8 +807,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // connect target and action [pCell setTarget: pCtrlTarget]; [pCell setAction: @selector(triggered:)]; - int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, m ); - pListenerProperties->addObservedControl( pCell ); + int nTag = pControllerProperties->addNameAndValueTag( aPropertyName, m ); + pControllerProperties->addObservedControl( pCell ); [pCell setTag: nTag]; [pTitle release]; // set current selection @@ -870,12 +870,12 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSString* pItemText = CreateNSString( aChoices[m] ); [pBtn addItemWithTitle: pItemText]; NSMenuItem* pItem = [pBtn itemWithTitle: pItemText]; - int nTag = pListenerProperties->addNameAndValueTag( aPropertyName, m ); + int nTag = pControllerProperties->addNameAndValueTag( aPropertyName, m ); [pItem setTag: nTag]; [pItemText release]; } - PropertyValue* pVal = pListener->getValue( aPropertyName ); + PropertyValue* pVal = pController->getValue( aPropertyName ); sal_Int32 aSelectVal = 0; if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aSelectVal; @@ -883,8 +883,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // add the button to observed controls for enabled state changes // also add a tag just for this purpose - pListenerProperties->addObservedControl( pBtn ); - [pBtn setTag: pListenerProperties->addNameTag( aPropertyName )]; + pControllerProperties->addObservedControl( pBtn ); + [pBtn setTag: pControllerProperties->addNameTag( aPropertyName )]; [pBtn sizeToFit]; [pCurParent addSubview: [pBtn autorelease]]; @@ -963,17 +963,17 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // add the field to observed controls for enabled state changes // also add a tag just for this purpose - pListenerProperties->addObservedControl( pFieldView ); - int nTag = pListenerProperties->addNameTag( aPropertyName ); + pControllerProperties->addObservedControl( pFieldView ); + int nTag = pControllerProperties->addNameTag( aPropertyName ); [pFieldView setTag: nTag]; - // pListenerProperties->addNamedView( pFieldView, aPropertyName ); + // pControllerProperties->addNamedView( pFieldView, aPropertyName ); // move to nCurY aFieldRect.origin.y = nCurY - aFieldRect.size.height; [pFieldView setFrame: aFieldRect]; // current value - PropertyValue* pVal = pListener->getValue( aPropertyName ); + PropertyValue* pVal = pController->getValue( aPropertyName ); if( aCtrlType.equalsAscii( "Range" ) ) { // add a stepper control @@ -985,7 +985,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pStep setValueWraps: NO]; [pStep setTag: nTag]; [pCurParent addSubview: [pStep autorelease]]; - pListenerProperties->addObservedControl( pStep ); + pControllerProperties->addObservedControl( pStep ); [pStep setTarget: pCtrlTarget]; [pStep setAction: @selector(triggered:)]; @@ -1011,7 +1011,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pFieldView setIntValue: nSelectVal]; [pStep setIntValue: nSelectVal]; - pListenerProperties->addViewPair( pFieldView, pStep ); + pControllerProperties->addViewPair( pFieldView, pStep ); // connect target and action [pFieldView setTarget: pCtrlTarget]; [pFieldView setAction: @selector(triggeredNumeric:)]; @@ -1047,7 +1047,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) DBG_ERROR( "Unsupported UI option" ); } } - pListenerProperties->updateEnableState(); + pControllerProperties->updateEnableState(); adjustViewAndChildren( pCurParent, aMaxTabSize ); // find the minimum needed tab size @@ -1060,7 +1060,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aViewFrame.size.height = aTabCtrlSize.height + aTabViewFrame.origin.y; [pAccessoryView setFrameSize: aViewFrame.size]; - pListenerProperties->setupPreview( pCtrlTarget ); + pControllerProperties->setupPreview( pCtrlTarget ); // set the accessory view [pOp setAccessoryView: [pAccessoryView autorelease]]; diff --git a/vcl/aqua/source/gdi/aquaprintview.mm b/vcl/aqua/source/gdi/aquaprintview.mm index a050d229f033..6519b4981770 100755 --- a/vcl/aqua/source/gdi/aquaprintview.mm +++ b/vcl/aqua/source/gdi/aquaprintview.mm @@ -36,12 +36,12 @@ #include "vcl/print.hxx" @implementation AquaPrintView --(id)initWithListener: (vcl::PrinterListener*)pListener withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter +-(id)initWithController: (vcl::PrinterController*)pController withInfoPrinter: (AquaSalInfoPrinter*)pInfoPrinter { NSRect aRect = { { 0, 0 }, [pInfoPrinter->getPrintInfo() paperSize] }; if( (self = [super initWithFrame: aRect]) != nil ) { - mpListener = pListener; + mpController = pController; mpInfoPrinter = pInfoPrinter; } return self; @@ -77,6 +77,6 @@ // page count is 1 based if( nPage - 1 < (mpInfoPrinter->getCurPageRangeStart() + mpInfoPrinter->getCurPageRangeCount() ) ) - mpListener->printFilteredPage( nPage-1 ); + mpController->printFilteredPage( nPage-1 ); } @end diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index e06e8c48fd8b..89a9d08cef13 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -484,10 +484,10 @@ void AquaSalInfoPrinter::GetPageInfo( const ImplJobSetup*, } } -static Size getPageSize( vcl::PrinterListener& i_rListener, sal_Int32 i_nPage ) +static Size getPageSize( vcl::PrinterController& i_rController, sal_Int32 i_nPage ) { Size aPageSize; - Sequence< PropertyValue > aPageParms( i_rListener.getPageParameters( i_nPage ) ); + Sequence< PropertyValue > aPageParms( i_rController.getPageParameters( i_nPage ) ); for( sal_Int32 nProperty = 0, nPropertyCount = aPageParms.getLength(); nProperty < nPropertyCount; ++nProperty ) { if( aPageParms[ nProperty ].Name.equalsAscii( "PageSize" ) ) @@ -506,7 +506,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, const String& i_rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterListener& i_rListener, + vcl::PrinterController& i_rController, bool bIsQuickJob ) { if( mbJob ) @@ -521,7 +521,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, aAccViewState.bNeedRestart = true; // reset IsLastPage - i_rListener.setLastPage( sal_False ); + i_rController.setLastPage( sal_False ); // update job data if( i_pSetupData ) @@ -529,20 +529,20 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, // do we want a progress panel ? sal_Bool bShowProgressPanel = sal_True; - beans::PropertyValue* pMonitor = i_rListener.getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); + beans::PropertyValue* pMonitor = i_rController.getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); if( pMonitor ) pMonitor->Value >>= bShowProgressPanel; // FIXME: jobStarted() should be done after the print dialog has ended (if there is one) // how do I know when that might be ? - i_rListener.jobStarted(); + i_rController.jobStarted(); do { if( aAccViewState.bNeedRestart ) { mnCurPageRangeStart = 0; mnCurPageRangeCount = 0; - nAllPages = i_rListener.getFilteredPageCount(); + nAllPages = i_rController.getFilteredPageCount(); } aAccViewState.bNeedRestart = false; @@ -551,13 +551,13 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( nAllPages > 0 ) { mnCurPageRangeCount = 1; - aCurSize = getPageSize( i_rListener, mnCurPageRangeStart ); + aCurSize = getPageSize( i_rController, mnCurPageRangeStart ); Size aNextSize( aCurSize ); // print pages up to a different size while( mnCurPageRangeCount + mnCurPageRangeStart < nAllPages ) { - aNextSize = getPageSize( i_rListener, mnCurPageRangeStart + mnCurPageRangeCount ); + aNextSize = getPageSize( i_rController, mnCurPageRangeStart + mnCurPageRangeCount ); if( aCurSize == aNextSize // same page size || (aCurSize.Width() == aNextSize.Height() && aCurSize.Height() == aNextSize.Width()) // same size, but different orientation @@ -578,7 +578,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, setPaperSize( aCurSize.Width(), aCurSize.Height(), ORIENTATION_PORTRAIT ); // create view - NSView* pPrintView = [[AquaPrintView alloc] initWithListener: &i_rListener withInfoPrinter: this]; + NSView* pPrintView = [[AquaPrintView alloc] initWithController: &i_rController withInfoPrinter: this]; NSMutableDictionary* pPrintDict = [mpPrintInfo dictionary]; @@ -591,7 +591,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, [pPath release]; } - [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rListener.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; + [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rController.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; @@ -612,7 +612,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, [pPrintOperation performSelector: @selector(setJobTitle:) withObject: [CreateNSString( i_rJobName ) autorelease]]; if( bShowPanel && mnCurPageRangeStart == 0 ) // only the first range of pages gets the accesory view - pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withListener: &i_rListener withState: &aAccViewState]; + pReleaseAfterUse = [AquaPrintAccessoryView setupPrinterPanel: pPrintOperation withController: &i_rController withState: &aAccViewState]; bSuccess = TRUE; mbJob = true; @@ -634,14 +634,14 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, // so we need to call XRenderadble::render one last time with IsLastPage = TRUE if( nAllPages > 0 ) { - i_rListener.setLastPage( sal_True ); + i_rController.setLastPage( sal_True ); GDIMetaFile aPageFile; if( mrContext ) SetupPrinterGraphics( mrContext ); - i_rListener.getFilteredPageFile( 0, aPageFile ); + i_rController.getFilteredPageFile( 0, aPageFile ); } - i_rListener.setJobState( bWasAborted + i_rController.setJobState( bWasAborted ? view::PrintableState_JOB_ABORTED : view::PrintableState_JOB_SPOOLED ); @@ -716,7 +716,7 @@ BOOL AquaSalPrinter::StartJob( const String* i_pFileName, const String& i_rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterListener& i_rListener ) + vcl::PrinterController& i_rController ) { bool bIsQuickJob = false; std::hash_map< rtl::OUString, rtl::OUString, rtl::OUStringHash >::const_iterator quick_it = @@ -728,7 +728,7 @@ BOOL AquaSalPrinter::StartJob( const String* i_pFileName, bIsQuickJob = true; } - return mpInfoPrinter->StartJob( i_pFileName, i_rJobName, i_rAppName, i_pSetupData, i_rListener, bIsQuickJob ); + return mpInfoPrinter->StartJob( i_pFileName, i_rJobName, i_rAppName, i_pSetupData, i_rController, bIsQuickJob ); } // ----------------------------------------------------------------------- diff --git a/vcl/inc/vcl/oldprintadaptor.hxx b/vcl/inc/vcl/oldprintadaptor.hxx index 9a0cb9a1d083..d8b26433af94 100644 --- a/vcl/inc/vcl/oldprintadaptor.hxx +++ b/vcl/inc/vcl/oldprintadaptor.hxx @@ -33,7 +33,7 @@ namespace vcl { struct ImplOldStyleAdaptorData; - class VCL_DLLPUBLIC OldStylePrintAdaptor : public PrinterListener + class VCL_DLLPUBLIC OldStylePrintAdaptor : public PrinterController { ImplOldStyleAdaptorData* mpData; public: diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 4cbd24dc02bd..339dee01d86d 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -56,7 +56,7 @@ class VirtualDevice; class Window; namespace vcl { - class PrinterListener; + class PrinterController; class PrintDialog; } @@ -264,7 +264,7 @@ private: SAL_DLLPRIVATE void ImplFindPaperFormatForUserSize( JobSetup& ); DECL_DLLPRIVATE_LINK( ImplDestroyPrinterAsync, void* ); - SAL_DLLPRIVATE bool StartJob( const rtl::OUString& rJobName, boost::shared_ptr& ); + SAL_DLLPRIVATE bool StartJob( const rtl::OUString& rJobName, boost::shared_ptr& ); static SAL_DLLPRIVATE ULONG ImplSalPrinterErrorCodeToVCL( ULONG nError ); @@ -386,26 +386,26 @@ public: starts a print job asynchronously (that is will return */ - static void PrintJob( const boost::shared_ptr& i_pListener, + static void PrintJob( const boost::shared_ptr& i_pController, const JobSetup& i_rInitSetup ); // implementation detail of PrintJob being asynchronous // not exported, not usable outside vcl - static void SAL_DLLPRIVATE ImplPrintJob( const boost::shared_ptr& i_pListener, + static void SAL_DLLPRIVATE ImplPrintJob( const boost::shared_ptr& i_pController, const JobSetup& i_rInitSetup ); }; namespace vcl { -class ImplPrinterListenerData; +class ImplPrinterControllerData; -class VCL_DLLPUBLIC PrinterListener +class VCL_DLLPUBLIC PrinterController { - ImplPrinterListenerData* mpImplData; + ImplPrinterControllerData* mpImplData; protected: - PrinterListener( const boost::shared_ptr& ); + PrinterController( const boost::shared_ptr& ); public: struct MultiPageSetup { @@ -432,8 +432,8 @@ public: } }; - PrinterListener(); - virtual ~PrinterListener(); + PrinterController(); + virtual ~PrinterController(); const boost::shared_ptr& getPrinter() const; /* for implementations: get current job properties as changed by e.g. print dialog @@ -449,6 +449,8 @@ public: */ com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& i_rPropertyName ); const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& i_rPropertyName ) const; + // get a sequence of properties + com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getValues( const com::sun::star::uno::Sequence< rtl::OUString >& ) const; /* set a property value - can also be used to add another UI property */ @@ -483,6 +485,8 @@ public: com::sun::star::view::PrintableState getJobState() const; + void abortJob(); + // implementation details, not usable outside vcl SAL_DLLPRIVATE int getFilteredPageCount(); SAL_DLLPRIVATE Size getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 67f38e45540f..e76d823b447a 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -112,7 +112,7 @@ namespace vcl void readFromSettings(); void storeToSettings(); - void initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& ); + void initFromMultiPageSetup( const vcl::PrinterController::MultiPageSetup& ); virtual void Resize(); }; @@ -156,7 +156,7 @@ namespace vcl FixedLine maButtonLine; - boost::shared_ptr< PrinterListener > maPListener; + boost::shared_ptr< PrinterController > maPController; rtl::OUString maPageStr; rtl::OUString maNoPageStr; @@ -206,7 +206,7 @@ namespace vcl DECL_LINK( UIOption_ModifyHdl, Edit* ); public: - PrintDialog( Window*, const boost::shared_ptr< PrinterListener >& ); + PrintDialog( Window*, const boost::shared_ptr< PrinterController >& ); virtual ~PrintDialog(); bool isPrintToFile(); diff --git a/vcl/inc/vcl/salprn.hxx b/vcl/inc/vcl/salprn.hxx index a53adfe3518e..e7fc44f0ab7d 100644 --- a/vcl/inc/vcl/salprn.hxx +++ b/vcl/inc/vcl/salprn.hxx @@ -41,7 +41,7 @@ class SalGraphics; class SalFrame; struct ImplJobSetup; -namespace vcl { class PrinterListener; } +namespace vcl { class PrinterController; } // ----------------------- // - SalPrinterQueueInfo - @@ -125,7 +125,7 @@ public: // public for Sal Implementation const String& rJobName, const String& rAppName, ImplJobSetup* pSetupData, - vcl::PrinterListener& rListener ); + vcl::PrinterController& rController ); virtual BOOL EndJob() = 0; virtual BOOL AbortJob() = 0; diff --git a/vcl/source/app/salvtables.cxx b/vcl/source/app/salvtables.cxx index 7f872d0a9b63..d8ead71c0a4b 100644 --- a/vcl/source/app/salvtables.cxx +++ b/vcl/source/app/salvtables.cxx @@ -91,7 +91,7 @@ SalPrinter::~SalPrinter() } BOOL SalPrinter::StartJob( const String*, const String&, const String&, - ImplJobSetup*, vcl::PrinterListener& ) + ImplJobSetup*, vcl::PrinterController& ) { return FALSE; } diff --git a/vcl/source/gdi/oldprintadaptor.cxx b/vcl/source/gdi/oldprintadaptor.cxx index e0250d2832ba..cffd11daaad6 100644 --- a/vcl/source/gdi/oldprintadaptor.cxx +++ b/vcl/source/gdi/oldprintadaptor.cxx @@ -55,7 +55,7 @@ using namespace com::sun::star::uno; using namespace com::sun::star::beans; OldStylePrintAdaptor::OldStylePrintAdaptor( const boost::shared_ptr< Printer >& i_pPrinter ) - : PrinterListener( i_pPrinter ) + : PrinterController( i_pPrinter ) , mpData( new ImplOldStyleAdaptorData() ) { } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index d0ff5814aa51..583ef206df7e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -130,7 +130,7 @@ public: } }; -class vcl::ImplPrinterListenerData +class vcl::ImplPrinterControllerData { public: struct ControlDependency @@ -154,27 +154,27 @@ public: sal_Bool mbLastPage; view::PrintableState meJobState; - vcl::PrinterListener::MultiPageSetup maMultiPage; + vcl::PrinterController::MultiPageSetup maMultiPage; vcl::PrintProgressDialog* mpProgress; ImplPageCache maPageCache; - ImplPrinterListenerData() : + ImplPrinterControllerData() : mbLastPage( sal_False ), meJobState( view::PrintableState_JOB_STARTED ), mpProgress( NULL ) {} - ~ImplPrinterListenerData() { delete mpProgress; } + ~ImplPrinterControllerData() { delete mpProgress; } }; -PrinterListener::PrinterListener() - : mpImplData( new ImplPrinterListenerData ) +PrinterController::PrinterController() + : mpImplData( new ImplPrinterControllerData ) { } -PrinterListener::PrinterListener( const boost::shared_ptr& i_pPrinter ) - : mpImplData( new ImplPrinterListenerData ) +PrinterController::PrinterController( const boost::shared_ptr& i_pPrinter ) + : mpImplData( new ImplPrinterControllerData ) { mpImplData->mpPrinter = i_pPrinter; } @@ -238,13 +238,13 @@ static rtl::OUString queryFile( Printer* pPrinter ) struct PrintJobAsync { - boost::shared_ptr mpListener; + boost::shared_ptr mpController; JobSetup maInitSetup; - PrintJobAsync( const boost::shared_ptr& i_pListener, + PrintJobAsync( const boost::shared_ptr& i_pController, const JobSetup& i_rInitSetup ) - : mpListener( i_pListener ), maInitSetup( i_rInitSetup ) + : mpController( i_pController ), maInitSetup( i_rInitSetup ) {} DECL_LINK( ExecJob, void* ); @@ -252,7 +252,7 @@ struct PrintJobAsync IMPL_LINK( PrintJobAsync, ExecJob, void*, EMPTYARG ) { - Printer::ImplPrintJob( mpListener, maInitSetup ); + Printer::ImplPrintJob( mpController, maInitSetup ); // clean up, do not access members after this delete this; @@ -260,41 +260,41 @@ IMPL_LINK( PrintJobAsync, ExecJob, void*, EMPTYARG ) return 0; } -void Printer::PrintJob( const boost::shared_ptr& i_pListener, +void Printer::PrintJob( const boost::shared_ptr& i_pController, const JobSetup& i_rInitSetup ) { sal_Bool bSynchronous = sal_False; - beans::PropertyValue* pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + beans::PropertyValue* pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); if( pVal ) pVal->Value >>= bSynchronous; if( bSynchronous ) - ImplPrintJob( i_pListener, i_rInitSetup ); + ImplPrintJob( i_pController, i_rInitSetup ); else { - PrintJobAsync* pAsync = new PrintJobAsync( i_pListener, i_rInitSetup ); + PrintJobAsync* pAsync = new PrintJobAsync( i_pController, i_rInitSetup ); Application::PostUserEvent( LINK( pAsync, PrintJobAsync, ExecJob ) ); } } -void Printer::ImplPrintJob( const boost::shared_ptr& i_pListener, +void Printer::ImplPrintJob( const boost::shared_ptr& i_pController, const JobSetup& i_rInitSetup ) { // setup printer - boost::shared_ptr pListener( i_pListener ); + boost::shared_ptr pController( i_pController ); // if no specific printer is already set, create one - if( ! pListener->getPrinter() ) + if( ! pController->getPrinter() ) { boost::shared_ptr pPrinter( new Printer( i_rInitSetup.GetPrinterName() ) ); - pListener->setPrinter( pPrinter ); + pController->setPrinter( pPrinter ); } // reset last page property - i_pListener->setLastPage( sal_False ); + i_pController->setLastPage( sal_False ); - beans::PropertyValue* pPagesVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pages" ) ) ); + beans::PropertyValue* pPagesVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pages" ) ) ); if( pPagesVal ) { rtl::OUString aPagesVal; @@ -304,13 +304,13 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene // "Pages" attribute from API is now equivalent to "PageRange" // AND "PrintContent" = 1 except calc where it is "PrintRange" = 1 // Argh ! That sure needs cleaning up - beans::PropertyValue* pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + beans::PropertyValue* pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); if( ! pVal ) - pVal = i_pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintContent" ) ) ); + pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintContent" ) ) ); if( pVal ) { pVal->Value = makeAny( sal_Int32( 1 ) ); - i_pListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PageRange" ) ), pPagesVal->Value ); + i_pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PageRange" ) ), pPagesVal->Value ); } } } @@ -319,25 +319,25 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene // in that case leave the work to that dialog const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); bool bIsQuick = rQuick.Len() && rQuick.EqualsIgnoreCaseAscii( "true" ); - if( ! pListener->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && ! bIsQuick ) + if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && ! bIsQuick ) { try { - PrintDialog aDlg( NULL, i_pListener ); + PrintDialog aDlg( NULL, i_pController ); if( ! aDlg.Execute() ) { GDIMetaFile aPageFile; - i_pListener->setLastPage( sal_True ); - if( i_pListener->getPageCount() > 0 ) - i_pListener->getFilteredPageFile( 0, aPageFile ); + i_pController->setLastPage( sal_True ); + if( i_pController->getPageCount() > 0 ) + i_pController->getFilteredPageFile( 0, aPageFile ); return; } if( aDlg.isPrintToFile() ) { - rtl::OUString aFile = queryFile( pListener->getPrinter().get() ); + rtl::OUString aFile = queryFile( pController->getPrinter().get() ); if( ! aFile.getLength() ) return; - pListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ), + pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ), makeAny( aFile ) ); } } @@ -346,19 +346,19 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pListene } } - pListener->pushPropertiesToPrinter(); + pController->pushPropertiesToPrinter(); rtl::OUString aJobName; - beans::PropertyValue* pJobNameVal = pListener->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "JobName" ) ) ); + beans::PropertyValue* pJobNameVal = pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "JobName" ) ) ); if( pJobNameVal ) pJobNameVal->Value >>= aJobName; - pListener->getPrinter()->StartJob( String( aJobName ), pListener ); + pController->getPrinter()->StartJob( String( aJobName ), pController ); - pListener->jobFinished( pListener->getJobState() ); + pController->jobFinished( pController->getJobState() ); } -bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptr& i_pListener ) +bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptr& i_pController ) { mnError = PRINTER_OK; @@ -403,7 +403,7 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrgetValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ) ); + beans::PropertyValue* pFileValue = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ) ); if( pFileValue ) { rtl::OUString aFile; @@ -429,12 +429,12 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrStartJob( pPrintFile, i_rJobName, Application::GetDisplayName(), maJobSetup.ImplGetConstData(), - *i_pListener ) ) + *i_pController ) ) { EndJob(); } @@ -456,8 +456,8 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrsetJobState( view::PrintableState_JOB_STARTED ); - i_pListener->jobStarted(); + i_pController->setJobState( view::PrintableState_JOB_STARTED ); + i_pController->jobStarted(); if( mpPrinter->StartJob( pPrintFile, i_rJobName, @@ -466,22 +466,22 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrcreateProgressDialog(); - int nPages = i_pListener->getFilteredPageCount(); + i_pController->createProgressDialog(); + int nPages = i_pController->getFilteredPageCount(); for( int nPage = 0; nPage < nPages; nPage++ ) { if( nPage == nPages-1 ) - i_pListener->setLastPage( sal_True ); - i_pListener->printFilteredPage( nPage ); + i_pController->setLastPage( sal_True ); + i_pController->printFilteredPage( nPage ); } EndJob(); - if( i_pListener->getJobState() == view::PrintableState_JOB_STARTED ) - i_pListener->setJobState( view::PrintableState_JOB_SPOOLED ); + if( i_pController->getJobState() == view::PrintableState_JOB_STARTED ) + i_pController->setJobState( view::PrintableState_JOB_SPOOLED ); } else { - i_pListener->setJobState( view::PrintableState_JOB_FAILED ); + i_pController->setJobState( view::PrintableState_JOB_FAILED ); mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); if ( !mnError ) @@ -499,27 +499,27 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrmeJobState; } -void PrinterListener::setJobState( view::PrintableState i_eState ) +void PrinterController::setJobState( view::PrintableState i_eState ) { mpImplData->meJobState = i_eState; } -const boost::shared_ptr& PrinterListener::getPrinter() const +const boost::shared_ptr& PrinterController::getPrinter() const { return mpImplData->mpPrinter; } -void PrinterListener::setPrinter( const boost::shared_ptr& i_rPrinter ) +void PrinterController::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; Size aPaperSize( i_rPrinter->PixelToLogic( i_rPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); @@ -547,7 +547,7 @@ static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& return aPageSize; } -Size PrinterListener::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) +Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { // update progress if necessary if( mpImplData->mpProgress ) @@ -635,7 +635,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD o_rMtf.AddAction( new MetaPopAction() ); } -Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) +Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { const MultiPageSetup& rMPS( mpImplData->maMultiPage ); int nSubPages = rMPS.nRows * rMPS.nColumns; @@ -713,7 +713,7 @@ Size PrinterListener::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_r return aPaperSize; } -int PrinterListener::getFilteredPageCount() +int PrinterController::getFilteredPageCount() { int nDiv = mpImplData->maMultiPage.nRows * mpImplData->maMultiPage.nColumns; if( nDiv < 1 ) @@ -721,7 +721,7 @@ int PrinterListener::getFilteredPageCount() return (getPageCount() * mpImplData->maMultiPage.nRepeat + (nDiv-1)) / nDiv; } -void PrinterListener::printFilteredPage( int i_nPage ) +void PrinterController::printFilteredPage( int i_nPage ) { if( mpImplData->meJobState != view::PrintableState_JOB_STARTED ) return; @@ -811,20 +811,25 @@ void PrinterListener::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->SetDrawMode( nRestoreDrawMode ); } -void PrinterListener::jobStarted() +void PrinterController::jobStarted() { } -void PrinterListener::jobFinished( view::PrintableState ) +void PrinterController::jobFinished( view::PrintableState ) { } -void PrinterListener::setLastPage( sal_Bool i_bLastPage ) +void PrinterController::abortJob() +{ + setJobState( view::PrintableState_JOB_ABORTED ); +} + +void PrinterController::setLastPage( sal_Bool i_bLastPage ) { mpImplData->mbLastPage = i_bLastPage; } -Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const +Sequence< PropertyValue > PrinterController::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const { std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; size_t nResultLen = size_t(i_rMergeList.getLength()) + mpImplData->maUIProperties.size() + 3; @@ -860,26 +865,40 @@ Sequence< PropertyValue > PrinterListener::getJobProperties( const Sequence< Pro return aResult; } -const Sequence< beans::PropertyValue >& PrinterListener::getUIOptions() const +const Sequence< beans::PropertyValue >& PrinterController::getUIOptions() const { return mpImplData->maUIOptions; } -com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl::OUString& i_rProperty ) +beans::PropertyValue* PrinterController::getValue( const rtl::OUString& i_rProperty ) { std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rProperty ); return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; } -const com::sun::star::beans::PropertyValue* PrinterListener::getValue( const rtl::OUString& i_rProperty ) const +const beans::PropertyValue* PrinterController::getValue( const rtl::OUString& i_rProperty ) const { std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rProperty ); return it != mpImplData->maPropertyToIndex.end() ? &mpImplData->maUIProperties[it->second] : NULL; } -void PrinterListener::setValue( const rtl::OUString& i_rName, const Any& i_rValue ) +Sequence< beans::PropertyValue > PrinterController::getValues( const Sequence< rtl::OUString >& i_rNames ) const +{ + Sequence< beans::PropertyValue > aRet( i_rNames.getLength() ); + sal_Int32 nFound = 0; + for( sal_Int32 i = 0; i < i_rNames.getLength(); i++ ) + { + const beans::PropertyValue* pVal = getValue( i_rNames[i] ); + if( pVal ) + aRet[ nFound++ ] = *pVal; + } + aRet.realloc( nFound ); + return aRet; +} + +void PrinterController::setValue( const rtl::OUString& i_rName, const Any& i_rValue ) { beans::PropertyValue aVal; aVal.Name = i_rName; @@ -888,7 +907,7 @@ void PrinterListener::setValue( const rtl::OUString& i_rName, const Any& i_rValu setValue( aVal ); } -void PrinterListener::setValue( const beans::PropertyValue& i_rValue ) +void PrinterController::setValue( const beans::PropertyValue& i_rValue ) { std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rValue.Name ); @@ -903,7 +922,7 @@ void PrinterListener::setValue( const beans::PropertyValue& i_rValue ) } } -void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rOptions ) +void PrinterController::setUIOptions( const Sequence< beans::PropertyValue >& i_rOptions ) { DBG_ASSERT( mpImplData->maUIOptions.getLength() == 0, "setUIOptions called twice !" ); @@ -916,7 +935,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO bool bIsEnabled = true; bool bHaveProperty = false; rtl::OUString aPropName; - vcl::ImplPrinterListenerData::ControlDependency aDep; + vcl::ImplPrinterControllerData::ControlDependency aDep; for( int n = 0; n < aOptProp.getLength(); n++ ) { const beans::PropertyValue& rEntry( aOptProp[ n ] ); @@ -947,7 +966,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO } if( bHaveProperty ) { - vcl::ImplPrinterListenerData::PropertyToIndexMap::const_iterator it = + vcl::ImplPrinterControllerData::PropertyToIndexMap::const_iterator it = mpImplData->maPropertyToIndex.find( aPropName ); // sanity check if( it != mpImplData->maPropertyToIndex.end() ) @@ -960,7 +979,7 @@ void PrinterListener::setUIOptions( const Sequence< beans::PropertyValue >& i_rO } } -void PrinterListener::enableUIOption( const rtl::OUString& i_rProperty, bool i_bEnable ) +void PrinterController::enableUIOption( const rtl::OUString& i_rProperty, bool i_bEnable ) { std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator it = mpImplData->maPropertyToIndex.find( i_rProperty ); @@ -977,7 +996,7 @@ void PrinterListener::enableUIOption( const rtl::OUString& i_rProperty, bool i_b } } -bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) const +bool PrinterController::isUIOptionEnabled( const rtl::OUString& i_rProperty ) const { bool bEnabled = false; std::hash_map< rtl::OUString, size_t, rtl::OUStringHash >::const_iterator prop_it = @@ -989,7 +1008,7 @@ bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) cons if( bEnabled ) { // check control dependencies - vcl::ImplPrinterListenerData::ControlDependencyMap::const_iterator it = + vcl::ImplPrinterControllerData::ControlDependencyMap::const_iterator it = mpImplData->maControlDependencies.find( i_rProperty ); if( it != mpImplData->maControlDependencies.end() ) { @@ -1031,12 +1050,12 @@ bool PrinterListener::isUIOptionEnabled( const rtl::OUString& i_rProperty ) cons return bEnabled; } -void PrinterListener::setOptionChangeHdl( const Link& i_rHdl ) +void PrinterController::setOptionChangeHdl( const Link& i_rHdl ) { mpImplData->maOptionChangeHdl = i_rHdl; } -void PrinterListener::createProgressDialog() +void PrinterController::createProgressDialog() { if( ! mpImplData->mpProgress ) { @@ -1053,17 +1072,17 @@ void PrinterListener::createProgressDialog() } } -void PrinterListener::setMultipage( const MultiPageSetup& i_rMPS ) +void PrinterController::setMultipage( const MultiPageSetup& i_rMPS ) { mpImplData->maMultiPage = i_rMPS; } -const PrinterListener::MultiPageSetup& PrinterListener::getMultipage() const +const PrinterController::MultiPageSetup& PrinterController::getMultipage() const { return mpImplData->maMultiPage; } -void PrinterListener::pushPropertiesToPrinter() +void PrinterController::pushPropertiesToPrinter() { sal_Int32 nCopyCount = 1; // set copycount and collate diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 138c75427d6d..5f8d08ec28a7 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -251,7 +251,7 @@ void PrintDialog::NUpTabPage::Resize() aPage->setManagedArea( Rectangle( Point(), GetOutputSizePixel() ) ); } -void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterListener::MultiPageSetup& i_rMPS ) +void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterController::MultiPageSetup& i_rMPS ) { maLeftMarginEdt.SetValue( maLeftMarginEdt.Normalize( i_rMPS.nLeftMargin ), FUNIT_100TH_MM ); maTopMarginEdt.SetValue( maTopMarginEdt.Normalize( i_rMPS.nTopMargin ), FUNIT_100TH_MM ); @@ -373,7 +373,7 @@ void PrintDialog::JobTabPage::storeToSettings() rtl::OUString::createFromAscii( maCollateBox.IsChecked() ? "true" : "false" ) ); } -PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rListener ) +PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rController ) : ModalDialog( i_pParent, VclResId( SV_DLG_PRINT ) ) , maOKButton( this, VclResId( SV_PRINT_OK ) ) , maCancelButton( this, VclResId( SV_PRINT_CANCEL ) ) @@ -386,7 +386,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) + if( maJobPage.maPrinters.GetEntryPos( maPController->getPrinter()->GetName() ) != LISTBOX_ENTRY_NOTFOUND ) { - maJobPage.maPrinters.SelectEntry( maPListener->getPrinter()->GetName() ); + maJobPage.maPrinters.SelectEntry( maPController->getPrinter()->GetName() ); } else { @@ -447,13 +447,13 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetPrinter( boost::shared_ptr( new Printer( aValue ) ) ); + maPController->setPrinter( boost::shared_ptr( new Printer( aValue ) ) ); } else { // fall back to default printer maJobPage.maPrinters.SelectEntry( Printer::GetDefaultPrinterName() ); - maPListener->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); + maPController->setPrinter( boost::shared_ptr( new Printer( Printer::GetDefaultPrinterName() ) ) ); } } // update the text fields for the printer @@ -463,9 +463,9 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPrinter()->PixelToLogic( - maPListener->getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); - if( maPListener->getPrinter()->GetOrientation() == ORIENTATION_LANDSCAPE ) + Size aNupSize( maPController->getPrinter()->PixelToLogic( + maPController->getPrinter()->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + if( maPController->getPrinter()->GetOrientation() == ORIENTATION_LANDSCAPE ) { maNupLandscapeSize = aNupSize; maNupPortraitSize = Size( aNupSize.Height(), aNupSize.Width() ); @@ -477,7 +477,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetMultipage() ); + maNUpPage.initFromMultiPageSetup( maPController->getMultipage() ); // setup click handler on the various buttons @@ -510,7 +510,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetOptionChangeHdl( LINK( this, PrintDialog, UIOptionsChanged ) ); + maPController->setOptionChangeHdl( LINK( this, PrintDialog, UIOptionsChanged ) ); // set min size pixel to current size SetMinOutputSizePixel( GetOutputSizePixel() ); @@ -639,7 +639,7 @@ void PrintDialog::setupOptionalUI() std::multimap< rtl::OUString, vcl::RowOrColumn* > aPropertyToDependencyRowMap; - const Sequence< PropertyValue >& rOptions( maPListener->getUIOptions() ); + const Sequence< PropertyValue >& rOptions( maPController->getUIOptions() ); for( int i = 0; i < rOptions.getLength(); i++ ) { Sequence< beans::PropertyValue > aOptProp; @@ -822,11 +822,11 @@ void PrintDialog::setupOptionalUI() pNewBox->Show(); sal_Bool bVal = sal_False; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); + PropertyValue* pVal = maPController->getValue( aPropertyName ); if( pVal ) pVal->Value >>= bVal; pNewBox->Check( bVal ); - pNewBox->Enable( maPListener->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); + pNewBox->Enable( maPController->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); pNewBox->SetToggleHdl( LINK( this, PrintDialog, UIOption_CheckHdl ) ); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); @@ -870,7 +870,7 @@ void PrintDialog::setupOptionalUI() } // iterate options sal_Int32 nSelectVal = 0; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); + PropertyValue* pVal = maPController->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) @@ -883,7 +883,7 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); pBtn->Check( m == nSelectVal ); - pBtn->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pBtn->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pBtn->SetToggleHdl( LINK( this, PrintDialog, UIOption_RadioHdl ) ); pBtn->Show(); maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pBtn ) ); @@ -934,11 +934,11 @@ void PrintDialog::setupOptionalUI() pList->InsertEntry( aChoices[m] ); } sal_Int32 nSelectVal = 0; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); + PropertyValue* pVal = maPController->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; pList->SelectEntryPos( static_cast(nSelectVal) ); - pList->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pList->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); pList->SetDropDownLineCount( static_cast(aChoices.getLength()) ); pList->Show(); @@ -966,12 +966,12 @@ void PrintDialog::setupOptionalUI() pField->SetMax( nMaxValue ); } sal_Int64 nCurVal = 0; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); + PropertyValue* pVal = maPController->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nCurVal; pField->SetValue( nCurVal ); - pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -992,11 +992,11 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pField ); rtl::OUString aCurVal; - PropertyValue* pVal = maPListener->getValue( aPropertyName ); + PropertyValue* pVal = maPController->getValue( aPropertyName ); if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aCurVal; pField->SetText( aCurVal ); - pField->Enable( maPListener->isUIOptionEnabled( aPropertyName ) ); + pField->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -1089,7 +1089,7 @@ void PrintDialog::checkControlDependencies() maJobPage.maCollateImage.SetImage( aImg ); // enable setup button only for printers that can be setup - bool bHaveSetup = maPListener->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ); + bool bHaveSetup = maPController->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ); maJobPage.maSetupButton.Enable( bHaveSetup ); if( bHaveSetup ) { @@ -1123,7 +1123,7 @@ void PrintDialog::checkOptionalControlDependencies() for( std::map< Window*, rtl::OUString >::iterator it = maControlToPropertyMap.begin(); it != maControlToPropertyMap.end(); ++it ) { - bool bShouldbeEnabled = maPListener->isUIOptionEnabled( it->second ); + bool bShouldbeEnabled = maPController->isUIOptionEnabled( it->second ); bool bIsEnabled = it->first->IsEnabled(); // Enable does not do a change check first, so can be less cheap than expected if( bShouldbeEnabled != bIsEnabled ) @@ -1176,7 +1176,7 @@ void PrintDialog::setPreviewText( sal_Int32 ) void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) { // page range may have changed depending on options - sal_Int32 nPages = maPListener->getFilteredPageCount(); + sal_Int32 nPages = maPController->getFilteredPageCount(); mnCachedPages = nPages; if( mnCurPage >= nPages ) @@ -1189,7 +1189,7 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) maPageEdit.SetMin( 1 ); maPageEdit.SetMax( nPages ); - boost::shared_ptr aPrt( maPListener->getPrinter() ); + boost::shared_ptr aPrt( maPController->getPrinter() ); if( i_bNewPage ) @@ -1197,7 +1197,7 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; if( nPages > 0 ) - maCurPageSize = maPListener->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); + maCurPageSize = maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); maPreviewWindow.setPreview( aMtf ); } @@ -1232,7 +1232,7 @@ void PrintDialog::updateNup() int nCols = int(maNUpPage.maNupColEdt.GetValue()); int nRepeat = int(maNUpPage.maNupRepEdt.GetValue()); - PrinterListener::MultiPageSetup aMPS; + PrinterController::MultiPageSetup aMPS; aMPS.nRows = nRows; aMPS.nColumns = nCols; aMPS.nRepeat = nRepeat; @@ -1248,7 +1248,7 @@ void PrintDialog::updateNup() aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); - maPListener->setMultipage( aMPS ); + maPController->setMultipage( aMPS ); preparePreview( true, true ); } @@ -1260,7 +1260,7 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) String aNewPrinter( pBox->GetSelectEntry() ); maJobPage.maPrinters.SelectEntry( aNewPrinter ); // set new printer - maPListener->setPrinter( boost::shared_ptr( new Printer( aNewPrinter ) ) ); + maPController->setPrinter( boost::shared_ptr( new Printer( aNewPrinter ) ) ); // update text fields updatePrinterText(); } @@ -1286,7 +1286,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) { if( pButton == &maJobPage.maSetupButton ) { - maPListener->getPrinter()->Setup( this ); + maPController->getPrinter()->Setup( this ); } checkControlDependencies(); if( pButton == &maNUpPage.maNupPortrait || pButton == &maNUpPage.maNupLandscape || pButton == &maNUpPage.maBorderCB ) @@ -1313,7 +1313,7 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) } else if( pEdit == &maJobPage.maCopyCountField ) { - maPListener->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), + maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), makeAny( sal_Int32(maJobPage.maCopyCountField.GetValue()) ) ); } return 0; @@ -1331,7 +1331,7 @@ PropertyValue* PrintDialog::getValueForWindow( Window* i_pWindow ) const std::map< Window*, rtl::OUString >::const_iterator it = maControlToPropertyMap.find( i_pWindow ); if( it != maControlToPropertyMap.end() ) { - pVal = maPListener->getValue( it->second ); + pVal = maPController->getValue( it->second ); DBG_ASSERT( pVal, "property value not found" ); } else -- cgit From de669ed51a29363beeb6b73e777004718b988861 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 6 Jul 2009 12:02:13 +0000 Subject: #i92516# rename PrinterListener --- padmin/source/padialog.cxx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/padmin/source/padialog.cxx b/padmin/source/padialog.cxx index 7c8ed6d39fe3..0417c784590a 100644 --- a/padmin/source/padialog.cxx +++ b/padmin/source/padialog.cxx @@ -361,13 +361,13 @@ static Color approachColor( const Color& rFrom, const Color& rTo ) return aColor; } -class SpaPrinterListener : public vcl::PrinterListener +class SpaPrinterController : public vcl::PrinterController { public: - SpaPrinterListener( const boost::shared_ptr& i_pPrinter ) - : vcl::PrinterListener( i_pPrinter ) + SpaPrinterController( const boost::shared_ptr& i_pPrinter ) + : vcl::PrinterController( i_pPrinter ) {} - virtual ~SpaPrinterListener() + virtual ~SpaPrinterController() {} virtual int getPageCount() const { return 1; } @@ -376,7 +376,7 @@ public: virtual void jobFinished(); }; -Sequence< PropertyValue > SpaPrinterListener::getPageParameters( int ) const +Sequence< PropertyValue > SpaPrinterController::getPageParameters( int ) const { Sequence< PropertyValue > aRet( 1 ); @@ -391,7 +391,7 @@ Sequence< PropertyValue > SpaPrinterListener::getPageParameters( int ) const return aRet; } -void SpaPrinterListener::printPage( int ) const +void SpaPrinterController::printPage( int ) const { const double DELTA = 5.0; @@ -574,7 +574,7 @@ void SpaPrinterListener::printPage( int ) const #endif } -void SpaPrinterListener::jobFinished() +void SpaPrinterController::jobFinished() { String aInfoString( PaResId( RID_PA_TXT_TESTPAGE_PRINTED ) ); InfoBox aInfoBox( NULL, aInfoString ); @@ -599,11 +599,11 @@ void PADialog::PrintTestPage() return; } - boost::shared_ptr pListener( new SpaPrinterListener( pPrinter ) ); + boost::shared_ptr pController( new SpaPrinterController( pPrinter ) ); JobSetup aJobSetup( pPrinter->GetJobSetup() ); aJobSetup.SetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ), String( RTL_CONSTASCII_USTRINGPARAM( "true" ) ) ); - Printer::PrintJob( pListener, aJobSetup ); + Printer::PrintJob( pController, aJobSetup ); } void PADialog::AddDevice() -- cgit From c8aed19d39abefd12d03b3c3fcc9a948344c4e94 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 7 Jul 2009 08:24:51 +0000 Subject: PrinterController API change --- padmin/source/padialog.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/padmin/source/padialog.cxx b/padmin/source/padialog.cxx index 0417c784590a..d1d36fade717 100644 --- a/padmin/source/padialog.cxx +++ b/padmin/source/padialog.cxx @@ -373,7 +373,7 @@ public: virtual int getPageCount() const { return 1; } virtual Sequence< PropertyValue > getPageParameters( int i_nPage ) const; virtual void printPage( int i_nPage ) const; - virtual void jobFinished(); + virtual void jobFinished( com::sun::star::view::PrintableState ); }; Sequence< PropertyValue > SpaPrinterController::getPageParameters( int ) const @@ -574,7 +574,7 @@ void SpaPrinterController::printPage( int ) const #endif } -void SpaPrinterController::jobFinished() +void SpaPrinterController::jobFinished( com::sun::star::view::PrintableState ) { String aInfoString( PaResId( RID_PA_TXT_TESTPAGE_PRINTED ) ); InfoBox aInfoBox( NULL, aInfoString ); -- cgit From e83bd2a5f6cab65ececd3a22722a41bbbeaf43b7 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 8 Jul 2009 16:27:08 +0000 Subject: #i95216# get a new enumerator that parsers a page range --- tools/inc/tools/multisel.hxx | 75 ++++++++++++++++ tools/source/memtools/multisel.cxx | 172 +++++++++++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+) diff --git a/tools/inc/tools/multisel.hxx b/tools/inc/tools/multisel.hxx index 46fd8947e21b..9e018d6b8479 100644 --- a/tools/inc/tools/multisel.hxx +++ b/tools/inc/tools/multisel.hxx @@ -35,6 +35,8 @@ #include #include +#include + //------------------------------------------------------------------ #ifdef _SV_MULTISEL_CXX @@ -112,4 +114,77 @@ public: const Range& GetRange( ULONG nRange ) const { return *(const Range*)aSels.GetObject(nRange); } }; +class TOOLS_DLLPUBLIC StringRangeEnumerator +{ + std::vector< sal_Int32 > maSequence; + sal_Int32 mnMin; + sal_Int32 mnMax; + sal_Int32 mnOffset; +public: + + typedef std::vector< sal_Int32 >::const_iterator Iterator; + + StringRangeEnumerator() {} + StringRangeEnumerator( const rtl::OUString& i_rInput, + sal_Int32 i_nMinNumber = -1, + sal_Int32 i_nMaxNumber = -1, + sal_Int32 i_nLogicalOffset = -1 ) : + mnMin( i_nMinNumber ), + mnMax( i_nMaxNumber ), + mnOffset( i_nLogicalOffset ) + { + getRangesFromString( i_rInput, maSequence, mnMin, mnMax, mnOffset ); + } + + size_t size() const { return maSequence.size(); } + Iterator begin() const { return maSequence.begin(); } + Iterator end() const { return maSequence.end(); } + + sal_Int32 getMin() const { return mnMin; } + void setMin( sal_Int32 i_nMinValue ) { mnMin = i_nMinValue; } + sal_Int32 getMax() const { return mnMax; } + void setMax( sal_Int32 i_nMaxValue ) { mnMax = i_nMaxValue; } + sal_Int32 getLogicalOffset() const { return mnOffset; } + void setLogicalOffset( sal_Int32 i_nOffset ) { mnOffset = i_nOffset; } + + void setRange( const rtl::OUString& i_rNewRange ) + { + maSequence.clear(); + getRangesFromString( i_rNewRange, maSequence, mnMin, mnMax, mnOffset ); + } + + + /** + i_rPageRange: the string to be changed into a sequence of numbers + valid format example "5-3,9,9,7-8" ; instead of ',' ';' or ' ' are allowed as well + o_rPageVector: the output sequence of numbers + i_nLogicalOffset: an offset to be applied to each number in the string before inserting it in the resulting sequence + example: a user enters page numbers from 1 to n (since that is logical) + of course usable page numbers in code would start from 0 and end at n-1 + so the logical offset would be -1 + i_nMinNumber: the minimum allowed number, a negative number means no minimum check + i_nMaxNumber: the maximum allowed number, a negative number means no maximum check + + @returns: true if the input string was valid, o_rPageVector will contain the resulting sequence + false if the input string was invalid, o_rPageVector will be unchanged + + behavior: + - only non-negative sequence numbers are allowed + - only non-negative values in the input string are allowed + - the string "-3" will be either + * an error if no minimum is given + * or result in the sequence i_nMinNumber to 3 + - the string "3-" will be either + * an error if no maximum is given + * or result in the seqeuence 3 to i_nMaxNumber + - an empty string as input is valid and will result in an empty result vector + */ + static bool getRangesFromString( const rtl::OUString& i_rPageRange, + std::vector< sal_Int32 >& o_rPageVector, + sal_Int32 i_nMinNumber = -1, + sal_Int32 i_nMaxNumber = -1, + sal_Int32 i_nLogicalOffset = -1 + ); +}; + #endif // _SV_MULTISEL_HXX diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index 6b32badc283e..a28b54c2347e 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -47,6 +47,8 @@ #define DBG(x) #endif +using namespace rtl; + //================================================================== #ifdef MI_DEBUG @@ -865,3 +867,173 @@ void MultiSelection::SetTotalRange( const Range& rTotRange ) bCurValid = FALSE; nCurIndex = 0; } + +// ----------------------------------------------------------------------- +// +// StringRangeEnumerator +// +// ----------------------------------------------------------------------- + +static bool lcl_getSingleValue( + const OUString &rText, + sal_Int32 &rVal, + sal_Int32 nLogicalOffset, + sal_Int32 nMinNumber, + sal_Int32 nMaxNumber + ) +{ + bool bRes = false; + const sal_Int32 nLen = rText.getLength(); + if (nLen > 0) + { + // verify that text consists of decimal number 0..9 only + bool bValidText = true; + const sal_Unicode *pText = rText.getStr(); + for (sal_Int32 i = 0; i < nLen && bValidText; ++i) + { + const sal_Unicode cChar = pText[i]; + if (cChar < '0' || cChar > '9') + bValidText = false; + } + + // get integer value if text is valid + if (bValidText) + { + sal_Int32 nTmpVal = rText.toInt32(); + nTmpVal += nLogicalOffset; + if( nTmpVal >= 0 && + (nMinNumber < 0 || nTmpVal >= nMinNumber) && + (nMaxNumber < 0 || nTmpVal <= nMaxNumber) + ) + { + bRes = true; + rVal = nTmpVal; + } + } + } + return bRes; +} + +static bool lcl_getSubRangeBounds( + const OUString &rSubRange, + sal_Int32 &rFirst, + sal_Int32 &rLast, + sal_Int32 nLogicalOffset, + sal_Int32 nMinNumber, + sal_Int32 nMaxNumber + ) +{ + bool bRes = false; + + // check for page range... + sal_Int32 nPos = rSubRange.indexOf( (sal_Unicode)'-' ); + if (nPos > 0) + { + // page range found... + nPos = 0; + const OUString aFirstPage( rSubRange.getToken( 0, '-', nPos ) ); + const OUString aLastPage( rSubRange.getToken( 0, '-', nPos ) ); + sal_Int32 nTmpFirst = -1; + sal_Int32 nTmpLast = -1; + if( aFirstPage.getLength() == 0 && nMinNumber >= 0 ) + nTmpFirst = nMinNumber; + else + lcl_getSingleValue( aFirstPage, nTmpFirst, nLogicalOffset, nMinNumber, nMaxNumber ); + if( aLastPage.getLength() == 0 && nMaxNumber >= 0 ) + nTmpLast = nMaxNumber; + else + lcl_getSingleValue( aLastPage, nTmpLast, nLogicalOffset, nMinNumber, nMaxNumber ); + if( nTmpFirst != -1 && nTmpLast != -1 ) + { + rFirst = nTmpFirst; + rLast = nTmpLast; + bRes = true; + } + } + else + { + // single page value... + sal_Int32 nVal = -1; + if (lcl_getSingleValue( rSubRange, nVal, nLogicalOffset, nMinNumber, nMaxNumber )) + { + rFirst = rLast = nVal; + bRes = true; + } + } + + return bRes; +} + +bool StringRangeEnumerator::getRangesFromString( const OUString& i_rPageRange, + std::vector< sal_Int32 >& o_rPageVector, + sal_Int32 i_nMinNumber, + sal_Int32 i_nMaxNumber, + sal_Int32 i_nLogicalOffset + ) +{ + bool bRes = false; + + // - strip leading and trailing whitespaces + // - unify token delimeters to ';' + // - remove duplicate delimiters + OUString aRange( i_rPageRange.trim() ); + aRange = aRange.replace( (sal_Unicode)' ', (sal_Unicode)';' ); + aRange = aRange.replace( (sal_Unicode)',', (sal_Unicode)';' ); + sal_Int32 nPos = -1; + rtl::OUString aDoubleSemi( RTL_CONSTASCII_USTRINGPARAM(";;") ); + rtl::OUString aSingleSemi( RTL_CONSTASCII_USTRINGPARAM(";;") ); + while ((nPos = aRange.indexOf( aDoubleSemi )) >= 0) + aRange = aRange.replaceAt( nPos, 2, aSingleSemi ); + + if (aRange.getLength() > 0) + { + std::vector< sal_Int32 > aTmpVector; + + // iterate over all sub ranges and add the respective pages to the + // vector while preserving the page order + bool bFailed = false; + nPos = 0; + do + { + const OUString aSubRange = aRange.getToken( 0, ';', nPos ); + sal_Int32 nFirst = -1, nLast = -1; + if (lcl_getSubRangeBounds( aSubRange, nFirst, nLast, i_nLogicalOffset, i_nMinNumber, i_nMaxNumber ) + && nFirst >= 0 && nLast >= 0) + { + // add pages of sub range to vector + if (nFirst == nLast) + aTmpVector.push_back( nFirst ); + else if (nFirst < nLast) + { + for (sal_Int32 i = nFirst; i <= nLast; ++i) + aTmpVector.push_back( i ); + } + else if (nFirst > nLast) + { + for (sal_Int32 i = nFirst; i >= nLast; --i) + aTmpVector.push_back( i ); + } + else + OSL_ENSURE( 0, "unexpected case" ); + } + else + bFailed = true; + } + while (!bFailed && 0 <= nPos && nPos < aRange.getLength()); + + if (!bFailed) + { + o_rPageVector = aTmpVector; + bRes = true; + } + } + else + { + // empty string ... + o_rPageVector.clear(); + bRes = true; + } + + return bRes; +} + -- cgit From 3f6401a45f6c8b112752900e959384080e5a4522 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 9 Jul 2009 14:01:10 +0000 Subject: add: set of possible values --- tools/inc/tools/multisel.hxx | 14 +++++++++----- tools/source/memtools/multisel.cxx | 23 +++++++++++++++++++---- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/tools/inc/tools/multisel.hxx b/tools/inc/tools/multisel.hxx index 9e018d6b8479..e30aff744897 100644 --- a/tools/inc/tools/multisel.hxx +++ b/tools/inc/tools/multisel.hxx @@ -36,6 +36,7 @@ #include #include +#include //------------------------------------------------------------------ @@ -128,12 +129,14 @@ public: StringRangeEnumerator( const rtl::OUString& i_rInput, sal_Int32 i_nMinNumber = -1, sal_Int32 i_nMaxNumber = -1, - sal_Int32 i_nLogicalOffset = -1 ) : + sal_Int32 i_nLogicalOffset = -1, + std::set< sal_Int32 >* i_pPossibleValues = NULL + ) : mnMin( i_nMinNumber ), mnMax( i_nMaxNumber ), mnOffset( i_nLogicalOffset ) { - getRangesFromString( i_rInput, maSequence, mnMin, mnMax, mnOffset ); + getRangesFromString( i_rInput, maSequence, mnMin, mnMax, mnOffset, i_pPossibleValues ); } size_t size() const { return maSequence.size(); } @@ -147,10 +150,10 @@ public: sal_Int32 getLogicalOffset() const { return mnOffset; } void setLogicalOffset( sal_Int32 i_nOffset ) { mnOffset = i_nOffset; } - void setRange( const rtl::OUString& i_rNewRange ) + void setRange( const rtl::OUString& i_rNewRange, std::set< sal_Int32 >* i_pPossibleValues = NULL ) { maSequence.clear(); - getRangesFromString( i_rNewRange, maSequence, mnMin, mnMax, mnOffset ); + getRangesFromString( i_rNewRange, maSequence, mnMin, mnMax, mnOffset, i_pPossibleValues ); } @@ -183,7 +186,8 @@ public: std::vector< sal_Int32 >& o_rPageVector, sal_Int32 i_nMinNumber = -1, sal_Int32 i_nMaxNumber = -1, - sal_Int32 i_nLogicalOffset = -1 + sal_Int32 i_nLogicalOffset = -1, + std::set< sal_Int32 >* i_pPossibleValues = NULL ); }; diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index a28b54c2347e..642a2398ae91 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -964,11 +964,17 @@ static bool lcl_getSubRangeBounds( return bRes; } +inline bool checkValue( std::set< sal_Int32 >* i_pPossibleValues, sal_Int32 nVal ) +{ + return i_pPossibleValues ? (i_pPossibleValues->find( nVal ) != i_pPossibleValues->end()) : true; +} + bool StringRangeEnumerator::getRangesFromString( const OUString& i_rPageRange, std::vector< sal_Int32 >& o_rPageVector, sal_Int32 i_nMinNumber, sal_Int32 i_nMaxNumber, - sal_Int32 i_nLogicalOffset + sal_Int32 i_nLogicalOffset, + std::set< sal_Int32 >* i_pPossibleValues ) { bool bRes = false; @@ -1002,16 +1008,25 @@ bool StringRangeEnumerator::getRangesFromString( const OUString& i_rPageRange, { // add pages of sub range to vector if (nFirst == nLast) - aTmpVector.push_back( nFirst ); + { + if( checkValue( i_pPossibleValues, nFirst ) ) + aTmpVector.push_back( nFirst ); + } else if (nFirst < nLast) { for (sal_Int32 i = nFirst; i <= nLast; ++i) - aTmpVector.push_back( i ); + { + if( checkValue( i_pPossibleValues, i ) ) + aTmpVector.push_back( i ); + } } else if (nFirst > nLast) { for (sal_Int32 i = nFirst; i >= nLast; --i) - aTmpVector.push_back( i ); + { + if( checkValue( i_pPossibleValues, i ) ) + aTmpVector.push_back( i ); + } } else OSL_ENSURE( 0, "unexpected case" ); -- cgit From a2459a0cb43b28458b1fef79db93067bb7f3bfc4 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 10 Jul 2009 13:52:54 +0000 Subject: #i92516# new parser for ranges --- tools/inc/tools/multisel.hxx | 74 +++++--- tools/source/memtools/multisel.cxx | 355 +++++++++++++++++++++++-------------- 2 files changed, 270 insertions(+), 159 deletions(-) diff --git a/tools/inc/tools/multisel.hxx b/tools/inc/tools/multisel.hxx index e30aff744897..e9b8b0f00177 100644 --- a/tools/inc/tools/multisel.hxx +++ b/tools/inc/tools/multisel.hxx @@ -117,31 +117,58 @@ public: class TOOLS_DLLPUBLIC StringRangeEnumerator { - std::vector< sal_Int32 > maSequence; - sal_Int32 mnMin; - sal_Int32 mnMax; - sal_Int32 mnOffset; + struct Range + { + sal_Int32 nFirst; + sal_Int32 nLast; + + Range() : nFirst( -1 ), nLast( -1 ) {} + Range( sal_Int32 i_nFirst, sal_Int32 i_nLast ) : nFirst( i_nFirst ), nLast( i_nLast ) {} + }; + std::vector< StringRangeEnumerator::Range > maSequence; + sal_Int32 mnCount; + sal_Int32 mnMin; + sal_Int32 mnMax; + sal_Int32 mnOffset; + + bool insertRange( sal_Int32 nFirst, sal_Int32 nLast, bool bSequence ); + bool checkValue( sal_Int32, const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; public: - - typedef std::vector< sal_Int32 >::const_iterator Iterator; - - StringRangeEnumerator() {} + class TOOLS_DLLPUBLIC Iterator + { + const StringRangeEnumerator* pEnumerator; + const std::set< sal_Int32 >* pPossibleValues; + sal_Int32 nRangeIndex; + sal_Int32 nCurrent; + + friend class StringRangeEnumerator; + Iterator( const StringRangeEnumerator* i_pEnum, + const std::set< sal_Int32 >* i_pPossibleValues, + sal_Int32 i_nRange, + sal_Int32 i_nCurrent ) + : pEnumerator( i_pEnum ), pPossibleValues( i_pPossibleValues ) + , nRangeIndex( i_nRange ), nCurrent( i_nCurrent ) {} + public: + Iterator() : pEnumerator( NULL ), pPossibleValues( NULL ), nRangeIndex( -1 ), nCurrent( -1 ) {} + Iterator& operator++(); + sal_Int32 operator*() const; + bool operator==(const Iterator&) const; + bool operator!=(const Iterator& i_rComp) const + { return ! (*this == i_rComp); } + }; + + friend class StringRangeEnumerator::Iterator; + + StringRangeEnumerator() : mnCount( 0 ), mnMin( -1 ), mnMax( -1 ), mnOffset( -1 ) {} StringRangeEnumerator( const rtl::OUString& i_rInput, sal_Int32 i_nMinNumber = -1, sal_Int32 i_nMaxNumber = -1, - sal_Int32 i_nLogicalOffset = -1, - std::set< sal_Int32 >* i_pPossibleValues = NULL - ) : - mnMin( i_nMinNumber ), - mnMax( i_nMaxNumber ), - mnOffset( i_nLogicalOffset ) - { - getRangesFromString( i_rInput, maSequence, mnMin, mnMax, mnOffset, i_pPossibleValues ); - } + sal_Int32 i_nLogicalOffset = -1 + ); - size_t size() const { return maSequence.size(); } - Iterator begin() const { return maSequence.begin(); } - Iterator end() const { return maSequence.end(); } + size_t size() const { return size_t(mnCount); } + Iterator begin( const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; + Iterator end( const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; sal_Int32 getMin() const { return mnMin; } void setMin( sal_Int32 i_nMinValue ) { mnMin = i_nMinValue; } @@ -150,11 +177,8 @@ public: sal_Int32 getLogicalOffset() const { return mnOffset; } void setLogicalOffset( sal_Int32 i_nOffset ) { mnOffset = i_nOffset; } - void setRange( const rtl::OUString& i_rNewRange, std::set< sal_Int32 >* i_pPossibleValues = NULL ) - { - maSequence.clear(); - getRangesFromString( i_rNewRange, maSequence, mnMin, mnMax, mnOffset, i_pPossibleValues ); - } + bool setRange( const rtl::OUString& i_rNewRange ); + bool hasValue( sal_Int32 nValue, const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; /** diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index 642a2398ae91..db83f3b47866 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -41,6 +41,8 @@ #include #include +#include "rtl/ustrbuf.hxx" + #ifdef MI_DEBUG #define DBG(x) x #else @@ -873,100 +875,240 @@ void MultiSelection::SetTotalRange( const Range& rTotRange ) // StringRangeEnumerator // // ----------------------------------------------------------------------- +StringRangeEnumerator::StringRangeEnumerator( const rtl::OUString& i_rInput, + sal_Int32 i_nMinNumber, + sal_Int32 i_nMaxNumber, + sal_Int32 i_nLogicalOffset + ) + : mnCount( 0 ) + , mnMin( i_nMinNumber ) + , mnMax( i_nMaxNumber ) + , mnOffset( i_nLogicalOffset ) +{ + setRange( i_rInput ); +} -static bool lcl_getSingleValue( - const OUString &rText, - sal_Int32 &rVal, - sal_Int32 nLogicalOffset, - sal_Int32 nMinNumber, - sal_Int32 nMaxNumber - ) +bool StringRangeEnumerator::checkValue( sal_Int32 i_nValue, const std::set< sal_Int32 >* i_pPossibleValues ) const { - bool bRes = false; - const sal_Int32 nLen = rText.getLength(); - if (nLen > 0) + if( mnMin >= 0 && i_nValue < mnMin ) + return false; + if( mnMax >= 0 && i_nValue > mnMax ) + return false; + if( i_nValue < 0 ) + return false; + if( i_pPossibleValues && i_pPossibleValues->find( i_nValue ) == i_pPossibleValues->end() ) + return false; + return true; +} + +bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, bool bSequence ) +{ + bool bSuccess = true; + if( bSequence ) { - // verify that text consists of decimal number 0..9 only - bool bValidText = true; - const sal_Unicode *pText = rText.getStr(); - for (sal_Int32 i = 0; i < nLen && bValidText; ++i) + if( i_nFirst == -1 ) + i_nFirst = mnMin; + if( i_nLast == -1 ) + i_nLast = mnMax; + if( checkValue( i_nFirst ) && checkValue( i_nLast ) ) { - const sal_Unicode cChar = pText[i]; - if (cChar < '0' || cChar > '9') - bValidText = false; + maSequence.push_back( Range( i_nFirst, i_nLast ) ); + mnCount += std::abs( i_nLast - i_nFirst - 1 ); } - - // get integer value if text is valid - if (bValidText) + else + bSuccess = false; + } + else + { + if( i_nFirst >= 0 ) + { + if( checkValue( i_nFirst ) ) + { + maSequence.push_back( Range( i_nFirst, i_nFirst ) ); + mnCount++; + } + else + bSuccess = false; + } + if( i_nLast >= 0 ) { - sal_Int32 nTmpVal = rText.toInt32(); - nTmpVal += nLogicalOffset; - if( nTmpVal >= 0 && - (nMinNumber < 0 || nTmpVal >= nMinNumber) && - (nMaxNumber < 0 || nTmpVal <= nMaxNumber) - ) + if( checkValue( i_nLast ) ) { - bRes = true; - rVal = nTmpVal; + maSequence.push_back( Range( i_nLast, i_nLast ) ); + mnCount++; } + else + bSuccess = false; } } - return bRes; + + return bSuccess; } -static bool lcl_getSubRangeBounds( - const OUString &rSubRange, - sal_Int32 &rFirst, - sal_Int32 &rLast, - sal_Int32 nLogicalOffset, - sal_Int32 nMinNumber, - sal_Int32 nMaxNumber - ) +bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) { - bool bRes = false; - - // check for page range... - sal_Int32 nPos = rSubRange.indexOf( (sal_Unicode)'-' ); - if (nPos > 0) + mnCount = 0; + maSequence.clear(); + + const sal_Unicode* pInput = i_rNewRange.getStr(); + rtl::OUStringBuffer aNumberBuf( 16 ); + sal_Int32 nLastNumber = -1, nNumber = -1; + bool bSequence = false; + bool bSuccess = true; + while( *pInput ) { - // page range found... - nPos = 0; - const OUString aFirstPage( rSubRange.getToken( 0, '-', nPos ) ); - const OUString aLastPage( rSubRange.getToken( 0, '-', nPos ) ); - sal_Int32 nTmpFirst = -1; - sal_Int32 nTmpLast = -1; - if( aFirstPage.getLength() == 0 && nMinNumber >= 0 ) - nTmpFirst = nMinNumber; + while( *pInput >= sal_Unicode('0') && *pInput <= sal_Unicode('9') ) + aNumberBuf.append( *pInput++ ); + if( aNumberBuf.getLength() ) + { + if( nNumber != -1 ) + { + if( bSequence ) + { + if( ! insertRange( nLastNumber, nNumber, true ) ) + { + bSuccess = false; + break; + } + nLastNumber = -1; + } + else + { + if( ! insertRange( nNumber, nNumber, false ) ) + { + bSuccess = false; + break; + } + } + } + nNumber = aNumberBuf.makeStringAndClear().toInt32(); + nNumber += mnOffset; + } + bool bInsertRange = false; + if( *pInput == sal_Unicode('-') ) + { + nLastNumber = nNumber; + nNumber = -1; + bSequence = true; + } + else if( *pInput == ' ' ) + { + } + else if( *pInput == sal_Unicode(',') || *pInput == sal_Unicode(';') ) + bInsertRange = true; else - lcl_getSingleValue( aFirstPage, nTmpFirst, nLogicalOffset, nMinNumber, nMaxNumber ); - if( aLastPage.getLength() == 0 && nMaxNumber >= 0 ) - nTmpLast = nMaxNumber; + { + bSuccess = false; + break; // parse error + } + + if( bInsertRange ) + { + if( ! insertRange( nLastNumber, nNumber, bSequence ) ) + { + bSuccess = false; + break; + } + nNumber = nLastNumber = -1; + bSequence = false; + } + if( *pInput ) + pInput++; + } + // insert last entries + insertRange( nLastNumber, nNumber, bSequence ); + + return bSuccess; +} + +bool StringRangeEnumerator::hasValue( sal_Int32 i_nValue, const std::set< sal_Int32 >* i_pPossibleValues ) const +{ + if( i_pPossibleValues && i_pPossibleValues->find( i_nValue ) == i_pPossibleValues->end() ) + return false; + size_t n = maSequence.size(); + for( size_t i= 0; i < n; ++i ) + { + const StringRangeEnumerator::Range rRange( maSequence[i] ); + if( rRange.nFirst < rRange.nLast ) + { + if( i_nValue >= rRange.nFirst && i_nValue <= rRange.nLast ) + return true; + } else - lcl_getSingleValue( aLastPage, nTmpLast, nLogicalOffset, nMinNumber, nMaxNumber ); - if( nTmpFirst != -1 && nTmpLast != -1 ) { - rFirst = nTmpFirst; - rLast = nTmpLast; - bRes = true; + if( i_nValue >= rRange.nLast && i_nValue <= rRange.nFirst ) + return true; } } - else + return false; +} + +StringRangeEnumerator::Iterator& StringRangeEnumerator::Iterator::operator++() +{ + if( nRangeIndex >= 0 && nCurrent >= 0 && pEnumerator ) { - // single page value... - sal_Int32 nVal = -1; - if (lcl_getSingleValue( rSubRange, nVal, nLogicalOffset, nMinNumber, nMaxNumber )) + const StringRangeEnumerator::Range& rRange( pEnumerator->maSequence[nRangeIndex] ); + bool bRangeChange = false; + if( rRange.nLast < rRange.nFirst ) + { + // backward range + if( nCurrent > rRange.nLast ) + nCurrent--; + else + bRangeChange = true; + } + else + { + // forward range + if( nCurrent < rRange.nLast ) + nCurrent++; + else + bRangeChange = true; + } + if( bRangeChange ) + { + nRangeIndex++; + if( size_t(nRangeIndex) == pEnumerator->maSequence.size() ) + { + // reached the end + nRangeIndex = nCurrent = -1; + } + else + nCurrent = pEnumerator->maSequence[nRangeIndex].nFirst; + } + if( nRangeIndex != -1 && nCurrent != -1 ) { - rFirst = rLast = nVal; - bRes = true; + if( ! pEnumerator->checkValue( nCurrent, pPossibleValues ) ) + return ++(*this); } } + return *this; +} - return bRes; +sal_Int32 StringRangeEnumerator::Iterator::operator*() const +{ + return nCurrent; +} + +bool StringRangeEnumerator::Iterator::operator==( const Iterator& i_rCompare ) const +{ + return i_rCompare.pEnumerator == pEnumerator && i_rCompare.nRangeIndex == nRangeIndex && i_rCompare.nCurrent == nCurrent; } -inline bool checkValue( std::set< sal_Int32 >* i_pPossibleValues, sal_Int32 nVal ) +StringRangeEnumerator::Iterator StringRangeEnumerator::begin( const std::set< sal_Int32 >* i_pPossibleValues ) const { - return i_pPossibleValues ? (i_pPossibleValues->find( nVal ) != i_pPossibleValues->end()) : true; + StringRangeEnumerator::Iterator it( this, + i_pPossibleValues, + maSequence.empty() ? -1 : 0, + maSequence.empty() ? -1 : maSequence[0].nFirst ); + if( ! checkValue(*it, i_pPossibleValues ) ) + ++it; + return it; +} + +StringRangeEnumerator::Iterator StringRangeEnumerator::end( const std::set< sal_Int32 >* i_pPossibleValues ) const +{ + return StringRangeEnumerator::Iterator( this, i_pPossibleValues, -1, -1 ); } bool StringRangeEnumerator::getRangesFromString( const OUString& i_rPageRange, @@ -977,76 +1119,21 @@ bool StringRangeEnumerator::getRangesFromString( const OUString& i_rPageRange, std::set< sal_Int32 >* i_pPossibleValues ) { - bool bRes = false; - - // - strip leading and trailing whitespaces - // - unify token delimeters to ';' - // - remove duplicate delimiters - OUString aRange( i_rPageRange.trim() ); - aRange = aRange.replace( (sal_Unicode)' ', (sal_Unicode)';' ); - aRange = aRange.replace( (sal_Unicode)',', (sal_Unicode)';' ); - sal_Int32 nPos = -1; - rtl::OUString aDoubleSemi( RTL_CONSTASCII_USTRINGPARAM(";;") ); - rtl::OUString aSingleSemi( RTL_CONSTASCII_USTRINGPARAM(";;") ); - while ((nPos = aRange.indexOf( aDoubleSemi )) >= 0) - aRange = aRange.replaceAt( nPos, 2, aSingleSemi ); - - if (aRange.getLength() > 0) - { - std::vector< sal_Int32 > aTmpVector; + StringRangeEnumerator aEnum; + aEnum.setMin( i_nMinNumber ); + aEnum.setMax( i_nMaxNumber ); + aEnum.setLogicalOffset( i_nLogicalOffset ); - // iterate over all sub ranges and add the respective pages to the - // vector while preserving the page order - bool bFailed = false; - nPos = 0; - do - { - const OUString aSubRange = aRange.getToken( 0, ';', nPos ); - sal_Int32 nFirst = -1, nLast = -1; - if (lcl_getSubRangeBounds( aSubRange, nFirst, nLast, i_nLogicalOffset, i_nMinNumber, i_nMaxNumber ) - && nFirst >= 0 && nLast >= 0) - { - // add pages of sub range to vector - if (nFirst == nLast) - { - if( checkValue( i_pPossibleValues, nFirst ) ) - aTmpVector.push_back( nFirst ); - } - else if (nFirst < nLast) - { - for (sal_Int32 i = nFirst; i <= nLast; ++i) - { - if( checkValue( i_pPossibleValues, i ) ) - aTmpVector.push_back( i ); - } - } - else if (nFirst > nLast) - { - for (sal_Int32 i = nFirst; i >= nLast; --i) - { - if( checkValue( i_pPossibleValues, i ) ) - aTmpVector.push_back( i ); - } - } - else - OSL_ENSURE( 0, "unexpected case" ); - } - else - bFailed = true; - } - while (!bFailed && 0 <= nPos && nPos < aRange.getLength()); - - if (!bFailed) - { - o_rPageVector = aTmpVector; - bRes = true; - } - } - else + bool bRes = aEnum.setRange( i_rPageRange ); + if( bRes ) { - // empty string ... o_rPageVector.clear(); - bRes = true; + o_rPageVector.reserve( aEnum.size() ); + for( StringRangeEnumerator::Iterator it = aEnum.begin( i_pPossibleValues ); + it != aEnum.end( i_pPossibleValues ); ++it ) + { + o_rPageVector.push_back( *it ); + } } return bRes; -- cgit From d6ad6af9da5d94ecad27aceedf9cb719858e5cfd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 10 Jul 2009 14:33:03 +0000 Subject: #i92516# fix count --- tools/source/memtools/multisel.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index db83f3b47866..b6f483312fa5 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -913,7 +913,9 @@ bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, if( checkValue( i_nFirst ) && checkValue( i_nLast ) ) { maSequence.push_back( Range( i_nFirst, i_nLast ) ); - mnCount += std::abs( i_nLast - i_nFirst - 1 ); + sal_Int32 nNumber = i_nLast - i_nFirst; + nNumber = nNumber < 0 ? -nNumber : nNumber; + mnCount += nNumber + 1; } else bSuccess = false; -- cgit From 92cb6e5eac5e9108ddfe37f70189a96f61c27c39 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 13 Jul 2009 14:32:36 +0000 Subject: fix number at end, change behaviour for empty string --- tools/inc/tools/multisel.hxx | 3 ++- tools/source/memtools/multisel.cxx | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/tools/inc/tools/multisel.hxx b/tools/inc/tools/multisel.hxx index e9b8b0f00177..bd2f7023bf8d 100644 --- a/tools/inc/tools/multisel.hxx +++ b/tools/inc/tools/multisel.hxx @@ -204,7 +204,8 @@ public: - the string "3-" will be either * an error if no maximum is given * or result in the seqeuence 3 to i_nMaxNumber - - an empty string as input is valid and will result in an empty result vector + - an empty string as input is valid and will result in the range [min,max] if given + or an empty vector, if not */ static bool getRangesFromString( const rtl::OUString& i_rPageRange, std::vector< sal_Int32 >& o_rPageVector, diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index b6f483312fa5..4f5ccbbabeae 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -952,6 +952,16 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) mnCount = 0; maSequence.clear(); + // we love special cases + if( i_rNewRange.getLength() == 0 ) + { + if( mnMin >= 0 && mnMax >= 0 ) + { + insertRange( mnMin, mnMax, mnMin != mnMax ); + } + return true; + } + const sal_Unicode* pInput = i_rNewRange.getStr(); rtl::OUStringBuffer aNumberBuf( 16 ); sal_Int32 nLastNumber = -1, nNumber = -1; @@ -998,8 +1008,9 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) } else if( *pInput == sal_Unicode(',') || *pInput == sal_Unicode(';') ) bInsertRange = true; - else + else if( *pInput ) { + bSuccess = false; break; // parse error } -- cgit From cd572c7f63e41e68dc74a2ec6166f686911c0fa8 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 14 Jul 2009 13:26:46 +0000 Subject: #i92516# make dialog maximizable, fix a paint issue --- vcl/source/src/print.src | 1 + vcl/source/window/printdlg.cxx | 2 ++ 2 files changed, 3 insertions(+) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index a653798332a2..8a589c4b18ed 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -36,6 +36,7 @@ ModalDialog SV_DLG_PRINT Closeable = TRUE; Sizeable = TRUE; Moveable = TRUE; + Maxable = TRUE; SVLook = TRUE; Size = MAP_APPFONT( 350, 215 ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 5f8d08ec28a7..20b3b737f509 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1508,6 +1508,8 @@ void PrintDialog::Resize() // and do the preview; however the metafile does not need to be gotten anew preparePreview( false ); + // do an invalidate for the benefit of the grouping elements + Invalidate(); } // ----------------------------------------------------------------------------- -- cgit From 2564edcb1c9779e345c5a418d8db251d8ba20f9b Mon Sep 17 00:00:00 2001 From: Frank Schönheit Date: Tue, 14 Jul 2009 16:00:02 +0000 Subject: merging selected changes from tags/DEV300_m52 --- toolkit/inc/toolkit/helper/vclunohelper.hxx | 4 ++++ toolkit/source/helper/vclunohelper.cxx | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/toolkit/inc/toolkit/helper/vclunohelper.hxx b/toolkit/inc/toolkit/helper/vclunohelper.hxx index 68583f99b447..1c5d89a3cc64 100644 --- a/toolkit/inc/toolkit/helper/vclunohelper.hxx +++ b/toolkit/inc/toolkit/helper/vclunohelper.hxx @@ -135,11 +135,15 @@ public: static MapUnit /* MapModeUnit */ ConvertToMapModeUnit(sal_Int16 /* com.sun.star.util.MeasureUnit.* */ _nMeasureUnit) throw (::com::sun::star::lang::IllegalArgumentException); static sal_Int16 /* com.sun.star.util.MeasureUnit.* */ ConvertToMeasurementUnit(MapUnit /* MapModeUnit */ _nMapModeUnit) throw (::com::sun::star::lang::IllegalArgumentException); + static ::Size /* VCLSize */ ConvertToVCLSize(::com::sun::star::awt::Size const& _aSize); static ::com::sun::star::awt::Size ConvertToAWTSize(::Size /* VCLSize */ const& _aSize); + static ::Point /* VCLPoint */ ConvertToVCLPoint(::com::sun::star::awt::Point const& _aPoint); static ::com::sun::star::awt::Point ConvertToAWTPoint(::Point /* VCLPoint */ const& _aPoint); + static ::Rectangle ConvertToVCLRect( ::com::sun::star::awt::Rectangle const & _rRect ); + static ::com::sun::star::awt::Rectangle ConvertToAWTRect( ::Rectangle const & _rRect ); }; diff --git a/toolkit/source/helper/vclunohelper.cxx b/toolkit/source/helper/vclunohelper.cxx index d76b56a6a37d..029e520baca6 100644 --- a/toolkit/source/helper/vclunohelper.cxx +++ b/toolkit/source/helper/vclunohelper.cxx @@ -736,4 +736,12 @@ com::sun::star::awt::Point VCLUnoHelper::ConvertToAWTPoint(::Point /* VCLPoint * return aAWTPoint; } +::Rectangle VCLUnoHelper::ConvertToVCLRect( ::com::sun::star::awt::Rectangle const & _rRect ) +{ + return ::Rectangle( _rRect.X, _rRect.Y, _rRect.X + _rRect.Width - 1, _rRect.Y + _rRect.Height - 1 ); +} +::com::sun::star::awt::Rectangle VCLUnoHelper::ConvertToAWTRect( ::Rectangle const & _rRect ) +{ + return ::com::sun::star::awt::Rectangle( _rRect.Left(), _rRect.Top(), _rRect.GetWidth(), _rRect.GetHeight() ); +} -- cgit From c2a9d1f422dee43b2dac04bed45fc9a201c62893 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 16 Jul 2009 08:50:32 +0000 Subject: #i92516# support wheel for preview forward/backward --- vcl/inc/vcl/prndlg.hxx | 5 +++++ vcl/source/window/printdlg.cxx | 51 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index e76d823b447a..b689ee66e058 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -73,6 +73,7 @@ namespace vcl virtual ~PrintPreviewWindow(); virtual void Paint( const Rectangle& rRect ); + virtual void Command( const CommandEvent& ); void setPreview( const GDIMetaFile& ); void setScale( double fScaleX, double fScaleY ); @@ -194,6 +195,7 @@ namespace vcl virtual void Resize(); virtual void Paint( const Rectangle& ); + virtual void Command( const CommandEvent& ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); @@ -212,6 +214,9 @@ namespace vcl bool isPrintToFile(); int getCopyCount(); bool isCollate(); + + void previewForward(); + void previewBackward(); }; class PrintProgressDialog : public ModelessDialog diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 20b3b737f509..20dfa502f61e 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -97,6 +97,26 @@ void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) Pop(); } +void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) +{ + if( rEvt.GetCommand() == COMMAND_WHEEL ) + { + const CommandWheelData* pWheelData = rEvt.GetWheelData(); + PrintDialog* pDlg = dynamic_cast(GetParent()); + if( pDlg ) + { + if( pWheelData->GetDelta() > 0 ) + pDlg->previewForward(); + else if( pWheelData->GetDelta() < 0 ) + pDlg->previewBackward(); + /* + else + huh ? + */ + } + } +} + void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview ) { maMtf = i_rNewPreview; @@ -1276,11 +1296,11 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) } else if( pButton == &maForwardBtn ) { - maPageEdit.Up(); + previewForward(); } else if( pButton == &maBackwardBtn ) { - maPageEdit.Down(); + previewBackward(); } else { @@ -1456,6 +1476,22 @@ void PrintDialog::Paint( const Rectangle& i_rRect ) #endif } +void PrintDialog::Command( const CommandEvent& rEvt ) +{ + if( rEvt.GetCommand() == COMMAND_WHEEL ) + { + const CommandWheelData* pWheelData = rEvt.GetWheelData(); + if( pWheelData->GetDelta() > 0 ) + previewForward(); + else if( pWheelData->GetDelta() < 0 ) + previewBackward(); + /* + else + huh ? + */ + } +} + void PrintDialog::Resize() { Size aPixDiff( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); @@ -1512,6 +1548,16 @@ void PrintDialog::Resize() Invalidate(); } +void PrintDialog::previewForward() +{ + maPageEdit.Up(); +} + +void PrintDialog::previewBackward() +{ + maPageEdit.Down(); +} + // ----------------------------------------------------------------------------- // // PrintProgressDialog @@ -1635,3 +1681,4 @@ void PrintProgressDialog::Paint( const Rectangle& ) aDecoView.DrawFrame( aFrameRect ); } } + -- cgit From 6f059173a5959880e366be1c9d43345a0e7aa031 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 16 Jul 2009 11:37:53 +0000 Subject: #i92516# collation support --- vcl/inc/vcl/jobdata.hxx | 2 ++ vcl/source/gdi/print.cxx | 3 ++- vcl/source/gdi/print3.cxx | 15 ++++++++++----- vcl/source/window/printdlg.cxx | 9 ++++++++- vcl/unx/headless/svpprn.cxx | 25 ++++++++++++++++++++++--- vcl/unx/headless/svpprn.hxx | 1 + vcl/unx/inc/salprn.h | 1 + vcl/unx/source/gdi/salprnpsp.cxx | 25 ++++++++++++++++++++++--- vcl/unx/source/printer/jobdata.cxx | 22 ++++++++++++++++++++++ 9 files changed, 90 insertions(+), 13 deletions(-) diff --git a/vcl/inc/vcl/jobdata.hxx b/vcl/inc/vcl/jobdata.hxx index 4451c566b5bf..d328f41f5b5b 100644 --- a/vcl/inc/vcl/jobdata.hxx +++ b/vcl/inc/vcl/jobdata.hxx @@ -74,6 +74,8 @@ struct JobData JobData( const JobData& rData ) { *this = rData; } + void setCollate( bool bCollate ); + // creates a new buffer using new // it is up to the user to delete it again bool getStreamBuffer( void*& pData, int& bytes ); diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index a3e33f236166..f03080a8a699 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -1288,9 +1288,10 @@ XubString Printer::GetPaperBinName( USHORT nPaperBin ) const // ----------------------------------------------------------------------- -BOOL Printer::SetCopyCount( USHORT nCopy, BOOL /*bCollate*/ ) +BOOL Printer::SetCopyCount( USHORT nCopy, BOOL bCollate ) { mnCopyCount = nCopy; + mbCollateCopy = bCollate; return TRUE; } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 583ef206df7e..a868be758c41 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -468,11 +468,16 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrcreateProgressDialog(); int nPages = i_pController->getFilteredPageCount(); - for( int nPage = 0; nPage < nPages; nPage++ ) + int nRepeatCount = bUserCopy ? mnCopyCount : 1; + for( int nIteration = 0; nIteration < nRepeatCount; nIteration++ ) { - if( nPage == nPages-1 ) - i_pController->setLastPage( sal_True ); - i_pController->printFilteredPage( nPage ); + for( int nPage = 0; nPage < nPages; nPage++ ) + { + if( nPage == nPages-1 && nIteration == nRepeatCount-1 ) + i_pController->setLastPage( sal_True ); + i_pController->printFilteredPage( nPage ); + } + // FIXME: duplex ? } EndJob(); @@ -1090,7 +1095,7 @@ void PrinterController::pushPropertiesToPrinter() if( pVal ) pVal->Value >>= nCopyCount; sal_Bool bCollate = sal_False; - pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ) ); + pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); if( pVal ) pVal->Value >>= bCollate; mpImplData->mpPrinter->SetCopyCount( static_cast(nCopyCount), bCollate ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 20dfa502f61e..8b3560b1f119 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -507,7 +507,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), + makeAny( sal_Bool(isCollate()) ) ); + } else { if( pButton == &maJobPage.maSetupButton ) @@ -1335,6 +1340,8 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), makeAny( sal_Int32(maJobPage.maCopyCountField.GetValue()) ) ); + maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), + makeAny( sal_Bool(isCollate()) ) ); } return 0; } diff --git a/vcl/unx/headless/svpprn.cxx b/vcl/unx/headless/svpprn.cxx index ca95acab6e78..9610cdd001c6 100644 --- a/vcl/unx/headless/svpprn.cxx +++ b/vcl/unx/headless/svpprn.cxx @@ -790,7 +790,18 @@ ULONG PspSalInfoPrinter::GetCapabilities( const ImplJobSetup* pJobSetup, USHORT case PRINTER_CAPABILITIES_COPIES: return 0xffff; case PRINTER_CAPABILITIES_COLLATECOPIES: - return 0; + { + // see if the PPD contains a value to set Collate to True + JobData aData; + JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, aData ); + + const PPDKey* pKey = aData.m_pParser ? aData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ) : NULL; + const PPDValue* pVal = pKey ? pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "True" ) ) ) : NULL; + + // PPDs don't mention the number of possible collated copies. + // so let's guess as many as we want ? + return pVal ? 0xffff : 0; + } case PRINTER_CAPABILITIES_SETORIENTATION: return 1; case PRINTER_CAPABILITIES_SETDUPLEX: @@ -844,6 +855,7 @@ PspSalPrinter::PspSalPrinter( SalInfoPrinter* pInfoPrinter ) m_bSwallowFaxNo( false ), m_pGraphics( NULL ), m_nCopies( 1 ), + m_bCollate( false ), m_pInfoPrinter( pInfoPrinter ) { } @@ -869,7 +881,7 @@ BOOL PspSalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL /*bCollate*/, + ULONG nCopies, BOOL bCollate, ImplJobSetup* pJobSetup ) { vcl_sal::PrinterUpdate::jobStarted(); @@ -878,13 +890,17 @@ BOOL PspSalPrinter::StartJob( m_bPdf = false; m_aFileName = pFileName ? *pFileName : String(); m_aTmpFile = String(); - m_nCopies = nCopies; + m_nCopies = nCopies; + m_bCollate = bCollate; JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, m_aJobData ); if( m_nCopies > 1 ) + { // in case user did not do anything (m_nCopies=1) // take the default from jobsetup m_aJobData.m_nCopies = m_nCopies; + m_aJobData.setCollate( bCollate ); + } // check wether this printer is configured as fax int nMode = 0; @@ -984,9 +1000,12 @@ SalGraphics* PspSalPrinter::StartPage( ImplJobSetup* pJobSetup, BOOL ) m_pGraphics = new PspGraphics( &m_aJobData, &m_aPrinterGfx, m_bFax ? &m_aFaxNr : NULL, m_bSwallowFaxNo, m_pInfoPrinter ); m_pGraphics->SetLayout( 0 ); if( m_nCopies > 1 ) + { // in case user did not do anything (m_nCopies=1) // take the default from jobsetup m_aJobData.m_nCopies = m_nCopies; + m_aJobData.setCollate( m_nCopies > 1 && m_bCollate ); + } m_aPrintJob.StartPage( m_aJobData ); m_aPrinterGfx.Init( m_aPrintJob ); diff --git a/vcl/unx/headless/svpprn.hxx b/vcl/unx/headless/svpprn.hxx index dd1c0cb1d88e..154273f6da88 100644 --- a/vcl/unx/headless/svpprn.hxx +++ b/vcl/unx/headless/svpprn.hxx @@ -79,6 +79,7 @@ public: psp::JobData m_aJobData; psp::PrinterGfx m_aPrinterGfx; ULONG m_nCopies; + bool m_bCollate; SalInfoPrinter* m_pInfoPrinter; PspSalPrinter( SalInfoPrinter* ); diff --git a/vcl/unx/inc/salprn.h b/vcl/unx/inc/salprn.h index 7d46d24ce94c..b1c92300ac49 100644 --- a/vcl/unx/inc/salprn.h +++ b/vcl/unx/inc/salprn.h @@ -79,6 +79,7 @@ public: psp::JobData m_aJobData; psp::PrinterGfx m_aPrinterGfx; ULONG m_nCopies; + bool m_bCollate; SalInfoPrinter* m_pInfoPrinter; PspSalPrinter( SalInfoPrinter* ); diff --git a/vcl/unx/source/gdi/salprnpsp.cxx b/vcl/unx/source/gdi/salprnpsp.cxx index 0891f0f9fb05..0b05e5e8fa14 100644 --- a/vcl/unx/source/gdi/salprnpsp.cxx +++ b/vcl/unx/source/gdi/salprnpsp.cxx @@ -892,7 +892,18 @@ ULONG PspSalInfoPrinter::GetCapabilities( const ImplJobSetup* pJobSetup, USHORT case PRINTER_CAPABILITIES_COPIES: return 0xffff; case PRINTER_CAPABILITIES_COLLATECOPIES: - return 0; + { + // see if the PPD contains a value to set Collate to True + JobData aData; + JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, aData ); + + const PPDKey* pKey = aData.m_pParser ? aData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ) : NULL; + const PPDValue* pVal = pKey ? pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "True" ) ) ) : NULL; + + // PPDs don't mention the number of possible collated copies. + // so let's guess as many as we want ? + return pVal ? 0xffff : 0; + } case PRINTER_CAPABILITIES_SETORIENTATION: return 1; case PRINTER_CAPABILITIES_SETDUPLEX: @@ -926,6 +937,7 @@ ULONG PspSalInfoPrinter::GetCapabilities( const ImplJobSetup* pJobSetup, USHORT m_bSwallowFaxNo( false ), m_pGraphics( NULL ), m_nCopies( 1 ), + m_bCollate( false ), m_pInfoPrinter( pInfoPrinter ) { } @@ -951,7 +963,7 @@ BOOL PspSalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL /*bCollate*/, + ULONG nCopies, BOOL bCollate, ImplJobSetup* pJobSetup ) { vcl_sal::PrinterUpdate::jobStarted(); @@ -960,13 +972,17 @@ BOOL PspSalPrinter::StartJob( m_bPdf = false; m_aFileName = pFileName ? *pFileName : String(); m_aTmpFile = String(); - m_nCopies = nCopies; + m_nCopies = nCopies; + m_bCollate = bCollate; JobData::constructFromStreamBuffer( pJobSetup->mpDriverData, pJobSetup->mnDriverDataLen, m_aJobData ); if( m_nCopies > 1 ) + { // in case user did not do anything (m_nCopies=1) // take the default from jobsetup m_aJobData.m_nCopies = m_nCopies; + m_aJobData.setCollate( bCollate ); + } // check wether this printer is configured as fax int nMode = 0; @@ -1076,9 +1092,12 @@ SalGraphics* PspSalPrinter::StartPage( ImplJobSetup* pJobSetup, BOOL ) m_pGraphics = new PspGraphics( &m_aJobData, &m_aPrinterGfx, m_bFax ? &m_aFaxNr : NULL, m_bSwallowFaxNo, m_pInfoPrinter ); m_pGraphics->SetLayout( 0 ); if( m_nCopies > 1 ) + { // in case user did not do anything (m_nCopies=1) // take the default from jobsetup m_aJobData.m_nCopies = m_nCopies; + m_aJobData.setCollate( m_nCopies > 1 && m_bCollate ); + } m_aPrintJob.StartPage( m_aJobData ); m_aPrinterGfx.Init( m_aPrintJob ); diff --git a/vcl/unx/source/printer/jobdata.cxx b/vcl/unx/source/printer/jobdata.cxx index 51e171d578d9..0410b349c93b 100644 --- a/vcl/unx/source/printer/jobdata.cxx +++ b/vcl/unx/source/printer/jobdata.cxx @@ -64,6 +64,28 @@ JobData& JobData::operator=(const JobData& rRight) return *this; } +void JobData::setCollate( bool bCollate ) +{ + const PPDParser* pParser = m_aContext.getParser(); + if( pParser ) + { + const PPDKey* pKey = pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); + if( pKey ) + { + const PPDValue* pVal = NULL; + if( bCollate ) + pVal = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "True" ) ) ); + else + { + pVal = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "False" ) ) ); + if( ! pVal ) + pVal = pKey->getValue( String( RTL_CONSTASCII_USTRINGPARAM( "None" ) ) ); + } + m_aContext.setValue( pKey, pVal ); + } + } +} + bool JobData::getStreamBuffer( void*& pData, int& bytes ) { // consistency checks -- cgit From d1c3c9440be742fe67ff2f0e7497e32b41ae4b8a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 16 Jul 2009 12:41:37 +0000 Subject: #i101973# add configuration setting for administrator to switch off collation UI --- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/window/printdlg.cxx | 43 +++++++++++++++++++++++++++--------------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index b689ee66e058..1208c8890b1d 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -136,6 +136,8 @@ namespace vcl Image maNoCollateImg; Image maNoCollateHCImg; + long mnCollateUIMode; + JobTabPage( Window*, const ResId& ); virtual ~JobTabPage(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 8b3560b1f119..acb87756758f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -291,17 +291,17 @@ void PrintDialog::NUpTabPage::readFromSettings() SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ) ); sal_Int32 nVal = aValue.toInt32(); maNupRowsEdt.SetValue( sal_Int64( nVal > 1 ? nVal : 1) ); - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ) ); nVal = aValue.toInt32(); maNupColEdt.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ) ); if( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ) maNupPortrait.Check(); @@ -314,13 +314,13 @@ void PrintDialog::NUpTabPage::storeToSettings() { #if 0 SettingsConfigItem* pItem = SettingsConfigItem::get(); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ), maNupRowsEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ), maNupColEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_NUpPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ), rtl::OUString::createFromAscii( maNupPortrait.IsChecked() ? "true" : "false" ) ); #endif @@ -340,6 +340,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maCollateHCImg( VclResId( SV_PRINT_COLLATE_HC_IMG ) ) , maNoCollateImg( VclResId( SV_PRINT_NOCOLLATE_IMG ) ) , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) + , mnCollateUIMode( 0 ) { FreeResource(); maPrinters.SMHID2( "JobPage", "PrinterList" ); @@ -361,34 +362,46 @@ void PrintDialog::JobTabPage::readFromSettings() SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); #if 0 // do not actually make copy count persistent // the assumption is that this would lead to a lot of unwanted copies - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ) ); sal_Int32 nVal = aValue.toInt32(); maCopyCountField.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); #endif - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); - maCollateBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CollateBox" ) ) ); + if( aValue.equalsIgnoreAsciiCaseAscii( "alwaysoff" ) ) + { + mnCollateUIMode = 1; + maCollateBox.Check( FALSE ); + maCollateBox.Enable( FALSE ); + } + else + { + mnCollateUIMode = 0; + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); + maCollateBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); + } } void PrintDialog::JobTabPage::storeToSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ), rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), maCopyCountField.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog_JobPage" ) ), + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), rtl::OUString::createFromAscii( maCollateBox.IsChecked() ? "true" : "false" ) ); } @@ -1096,7 +1109,7 @@ void PrintDialog::setupOptionalUI() void PrintDialog::checkControlDependencies() { if( maJobPage.maCopyCountField.GetValue() > 1 ) - maJobPage.maCollateBox.Enable( TRUE ); + maJobPage.maCollateBox.Enable( maJobPage.mnCollateUIMode == 0 ); else maJobPage.maCollateBox.Enable( FALSE ); -- cgit From e1ede83e9d1d354bbf454fb76ae95084f681c1e6 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 17 Jul 2009 00:30:17 +0000 Subject: add exceptions for stl --- tools/source/memtools/makefile.mk | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/source/memtools/makefile.mk b/tools/source/memtools/makefile.mk index 037dadbf4a46..51d831ec0fed 100644 --- a/tools/source/memtools/makefile.mk +++ b/tools/source/memtools/makefile.mk @@ -47,6 +47,8 @@ SLOFILES= $(SLO)$/contnr.obj \ $(SLO)$/mempool.obj \ $(SLO)$/multisel.obj +EXCEPTIONSFILES= $(SLO)$/multisel.obj $(OBJ)$/multisel.obj + OBJFILES= $(OBJ)$/contnr.obj \ $(OBJ)$/table.obj \ $(OBJ)$/unqidx.obj \ -- cgit -- cgit From f3f952731fa35c7618d9c929ccb0773ad841fbf2 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 22 Jul 2009 17:16:34 +0000 Subject: #i92516# adapt to new UI spec --- vcl/inc/vcl/arrange.hxx | 6 +- vcl/inc/vcl/fixed.hxx | 1 + vcl/inc/vcl/print.hxx | 2 +- vcl/inc/vcl/prndlg.hxx | 51 ++++++--- vcl/inc/vcl/svids.hrc | 13 ++- vcl/source/control/fixed.cxx | 8 ++ vcl/source/control/lstbox.cxx | 1 + vcl/source/gdi/print3.cxx | 8 +- vcl/source/src/print.src | 86 ++++++++++----- vcl/source/window/printdlg.cxx | 238 +++++++++++++++++++++++++++++------------ 10 files changed, 295 insertions(+), 119 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index f350b9ae110d..2a9d83b7b769 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -200,16 +200,18 @@ namespace vcl class Spacer : public WindowArranger { WindowArranger::Element m_aElement; + Size m_aSize; public: - Spacer( WindowArranger* i_pParent = NULL, sal_Int32 i_nPrio = 20 ) + Spacer( WindowArranger* i_pParent = NULL, sal_Int32 i_nPrio = 20, const Size& i_rSize = Size( 0, 0 ) ) : WindowArranger( i_pParent ) , m_aElement( NULL, boost::shared_ptr(), i_nPrio ) + , m_aSize( i_rSize ) {} virtual ~Spacer() {} virtual Size getOptimalSize( WindowSizeType ) const - { return Size( 0, 0 ); } + { return m_aSize; } virtual void resize() {} virtual void setParentWindow( Window* ) {} virtual size_t countElements() const { return 1; } diff --git a/vcl/inc/vcl/fixed.hxx b/vcl/inc/vcl/fixed.hxx index ba576f280b83..39135826e38e 100644 --- a/vcl/inc/vcl/fixed.hxx +++ b/vcl/inc/vcl/fixed.hxx @@ -174,6 +174,7 @@ public: virtual void StateChanged( StateChangedType nType ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); virtual void UserDraw( const UserDrawEvent& rUDEvt ); + virtual Size GetOptimalSize(WindowSizeType eType) const; void SetImage( const Image& rImage ); const Image& GetImage() const { return maImage; } diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 339dee01d86d..1dc9a9958ad5 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -571,7 +571,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // create a subgroup (e.g. a FixedLine); following controls will be grouped in it until the next // subgroup or group begins // setting bJobPage = true will make the subgroup appear on the first page of the print dialog - static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, bool i_bJobPage = false, bool i_bInternalOnly = false ); + static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, const rtl::OUString& i_rGroupHint = rtl::OUString(), bool i_bInternalOnly = false ); // create a bool option (usually a checkbox) static com::sun::star::uno::Any getBoolControlOpt( const rtl::OUString& i_rTitle, diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 1208c8890b1d..5577592bc775 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -53,16 +53,6 @@ namespace vcl { class PrintDialog : public ModalDialog { - class PrinterListBox : public ListBox - { - public: - PrinterListBox( Window* i_pParent, const ResId& i_rId ) - : ListBox( i_pParent, i_rId ) - {} - virtual ~PrinterListBox() {} - virtual void RequestHelp( const HelpEvent& i_rHEvt ); - }; - class PrintPreviewWindow : public Window { GDIMetaFile maMtf; @@ -121,11 +111,19 @@ namespace vcl class JobTabPage : public TabPage { public: - PrinterListBox maPrinters; + FixedLine maPrinterFL; + ListBox maPrinters; + FixedText maStatusLabel; + FixedText maStatusTxt; + FixedText maLocationLabel; + FixedText maLocationTxt; + FixedText maCommentLabel; + FixedText maCommentTxt; + PushButton maSetupButton; - CheckBox maToFileBox; FixedLine maCopies; + FixedLine maCopySpacer; FixedText maCopyCount; NumericField maCopyCountField; CheckBox maCollateBox; @@ -138,11 +136,33 @@ namespace vcl long mnCollateUIMode; + vcl::RowOrColumn maLayout; + boost::shared_ptr mxPrintRange; + JobTabPage( Window*, const ResId& ); virtual ~JobTabPage(); void readFromSettings(); void storeToSettings(); + + virtual void Resize(); + + void setupLayout(); + }; + + class OutputOptPage : public TabPage + { + public: + FixedLine maOptionsLine; + CheckBox maToFileBox; + CheckBox maCollateSingleJobsBox; + CheckBox maReverseOrderBox; + + OutputOptPage( Window*, const ResId& ); + virtual ~OutputOptPage(); + + void readFromSettings(); + void storeToSettings(); }; OKButton maOKButton; @@ -156,6 +176,7 @@ namespace vcl TabControl maTabCtrl; NUpTabPage maNUpPage; JobTabPage maJobPage; + OutputOptPage maOptionsPage; FixedLine maButtonLine; @@ -176,10 +197,8 @@ namespace vcl Size maNupPortraitSize; Size maNupLandscapeSize; - rtl::OUString maCommentText; - rtl::OUString maStatusText; - rtl::OUString maLocationText; - rtl::OUString maTypeText; + rtl::OUString maPrintToFileText; + rtl::OUString maPrintText; vcl::RowOrColumn maPreviewCtrlRow; Rectangle maPreviewBackground; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index a774717e8078..b00f1742fced 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -114,8 +114,8 @@ #define SV_PRINT_PRT_NUP_PAGEREPEAT_EDT 23 #define SV_PRINT_TAB_JOB 2 -#define SV_PRINT_PRINTERS 1 -#define SV_PRINT_PRT_TOFILE 2 +#define SV_PRINT_PRINTERS_FL 1 +#define SV_PRINT_PRINTERS 2 #define SV_PRINT_PRT_SETUP 3 #define SV_PRINT_RANGE 4 #define SV_PRINT_ALL 5 @@ -133,6 +133,15 @@ #define SV_PRINT_COLLATE_HC_IMG 17 #define SV_PRINT_NOCOLLATE_HC_IMG 18 #define SV_PRINT_NOPAGES 19 +#define SV_PRINT_STATUS_TXT 20 +#define SV_PRINT_LOCATION_TXT 21 +#define SV_PRINT_COMMENT_TXT 22 + +#define SV_PRINT_TAB_OPT 3 +#define SV_PRINT_OPT_PRINT_FL 1 +#define SV_PRINT_OPT_TOFILE 2 +#define SV_PRINT_OPT_SINGLEJOBS 3 +#define SV_PRINT_OPT_REVERSE 4 #define SV_DLG_PRINT_PROGRESS 2049 #define SV_PRINT_PROGRESS_CANCEL 1 diff --git a/vcl/source/control/fixed.cxx b/vcl/source/control/fixed.cxx index 530e928532e1..0bf440e9c349 100644 --- a/vcl/source/control/fixed.cxx +++ b/vcl/source/control/fixed.cxx @@ -1094,6 +1094,14 @@ void FixedImage::Paint( const Rectangle& ) // ----------------------------------------------------------------------- +Size FixedImage::GetOptimalSize( WindowSizeType ) const +{ + const Image* pImage = GetSettings().GetStyleSettings().GetHighContrastMode() ? &maImageHC : &maImage; + return pImage->GetSizePixel(); +} + +// ----------------------------------------------------------------------- + void FixedImage::UserDraw( const UserDrawEvent& ) { } diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 05ddd5ce3bd2..37c289851898 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -108,6 +108,7 @@ void ListBox::ImplInitListBoxData() mnDDHeight = 0; mbDDAutoSize = TRUE; mnSaveValue = LISTBOX_ENTRY_NOTFOUND; + mnLineCount = 0; } // ----------------------------------------------------------------------- diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index a868be758c41..db77313db446 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1266,14 +1266,14 @@ Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle, con } Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, - bool i_bJobPage, bool i_bInternalOnly ) + const rtl::OUString& i_rGroupHint, bool i_bInternalOnly ) { PropertyValue aAddProps[2]; sal_Int32 nUsed = 0; - if( i_bJobPage ) + if( i_rGroupHint.getLength() ) { - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PutOnJobPage" ) ); - aAddProps[nUsed++].Value <<= sal_True; + aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GroupingHint" ) ); + aAddProps[nUsed++].Value <<= i_rGroupHint; } if( i_bInternalOnly ) { diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 8a589c4b18ed..3a3afd8c568a 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -101,23 +101,6 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "No pages"; }; - String SV_PRINT_PRT_TYPE - { - Text [en-US] = "Type: %s"; - }; - String SV_PRINT_PRT_STATUS - { - Text [en-US] = "Status: %s"; - }; - String SV_PRINT_PRT_LOCATION - { - Text [en-US] = "Location: %s"; - }; - String SV_PRINT_PRT_COMMENT - { - Text [en-US] = "Comment: %s"; - }; - TabPage SV_PRINT_TAB_NUP { Text [en-US] = "N-Up"; @@ -296,14 +279,38 @@ ModalDialog SV_DLG_PRINT TabPage SV_PRINT_TAB_JOB { - Text [en-US] = "Job Setup"; + Text [en-US] = "General"; Hide = TRUE; + FixedLine SV_PRINT_PRINTERS_FL + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 10 ); + Text [ en-US ] = "Prin~ter"; + }; ListBox SV_PRINT_PRINTERS { Pos = MAP_APPFONT( 5, 5 ); - Size = MAP_APPFONT( 100, 200 ); - DropDown = TRUE; + Size = MAP_APPFONT( 100, 80 ); + Border = TRUE; + }; + FixedText SV_PRINT_STATUS_TXT + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 10 ); + Text [en-US] = "Status:"; + }; + FixedText SV_PRINT_LOCATION_TXT + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 10 ); + Text [en-US] = "Location"; + }; + FixedText SV_PRINT_COMMENT_TXT + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 100, 10 ); + Text [en-US] = "Comment:"; }; PushButton SV_PRINT_PRT_SETUP { @@ -311,17 +318,11 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 50, 15 ); Text [en-US] = "Properties..."; }; - CheckBox SV_PRINT_PRT_TOFILE - { - Pos = MAP_APPFONT( 10, 20 ); - Size = MAP_APPFONT( 200, 12 ); - Text [en-US] = "Print to file"; - }; FixedLine SV_PRINT_COPIES { Pos = MAP_APPFONT( 5, 35 ); Size = MAP_APPFONT( 150, 10 ); - Text [en-US] = "Copies"; + Text [en-US] = "Print Range and Copies"; }; FixedText SV_PRINT_COPYCOUNT { @@ -371,6 +372,37 @@ ModalDialog SV_DLG_PRINT ImageBitmap = Bitmap { File = "ncollate_h.png" ; }; }; }; + + TabPage SV_PRINT_TAB_OPT + { + Text [en-US] = "Options"; + Hide = TRUE; + + FixedLine SV_PRINT_PRT_NUP + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 150, 10 ); + Text [en-US] = "Options"; + }; + CheckBox SV_PRINT_OPT_TOFILE + { + Pos = MAP_APPFONT( 10, 20 ); + Size = MAP_APPFONT( 200, 12 ); + Text [en-US] = "Print to ~file"; + }; + CheckBox SV_PRINT_OPT_SINGLEJOBS + { + Pos = MAP_APPFONT( 10, 35 ); + Size = MAP_APPFONT( 200, 12 ); + Text [en-US] = "~Create single print jobs for collated output"; + }; + CheckBox SV_PRINT_OPT_REVERSE + { + Pos = MAP_APPFONT( 10, 50 ); + Size = MAP_APPFONT( 200, 12 ); + Text [en-US] = "Print in ~reverse page order"; + }; + }; }; ModelessDialog SV_DLG_PRINT_PROGRESS diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index acb87756758f..a52f1a954315 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -60,14 +60,6 @@ using namespace com::sun::star::beans; #define SMHID2( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ":" b ) ) ) ) #define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ) ) ) -void PrintDialog::PrinterListBox::RequestHelp( const HelpEvent& i_rHEvt ) -{ - if( i_rHEvt.GetMode() & HELPMODE_QUICK ) - Help::ShowBalloon( this, i_rHEvt.GetMousePosPixel(), GetHelpText() ); - else - ListBox::RequestHelp( i_rHEvt ); -} - PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ), mfScaleX( 1 ), @@ -328,10 +320,17 @@ void PrintDialog::NUpTabPage::storeToSettings() PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) - , maPrinters( this, VclResId( SV_PRINT_PRINTERS) ) + , maPrinterFL( this, VclResId( SV_PRINT_PRINTERS_FL ) ) + , maPrinters( this, VclResId( SV_PRINT_PRINTERS ) ) + , maStatusLabel( this, VclResId( SV_PRINT_STATUS_TXT ) ) + , maStatusTxt( this, 0 ) + , maLocationLabel( this, VclResId( SV_PRINT_LOCATION_TXT ) ) + , maLocationTxt( this, 0 ) + , maCommentLabel( this, VclResId( SV_PRINT_COMMENT_TXT ) ) + , maCommentTxt( this, 0 ) , maSetupButton( this, VclResId( SV_PRINT_PRT_SETUP ) ) - , maToFileBox( this, VclResId( SV_PRINT_PRT_TOFILE ) ) , maCopies( this, VclResId( SV_PRINT_COPIES ) ) + , maCopySpacer( this, WB_VERT ) , maCopyCount( this, VclResId( SV_PRINT_COPYCOUNT ) ) , maCopyCountField( this, VclResId( SV_PRINT_COPYCOUNT_FIELD ) ) , maCollateBox( this, VclResId( SV_PRINT_COLLATE ) ) @@ -343,29 +342,96 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , mnCollateUIMode( 0 ) { FreeResource(); + maPrinterFL.SMHID2( "JobPage", "Printer" ); maPrinters.SMHID2( "JobPage", "PrinterList" ); + maStatusLabel.SMHID2( "JobPage", "StatusLabel" ); + maStatusTxt.SMHID2( "JobPage", "StatusText" ); + maLocationLabel.SMHID2( "JobPage", "LocationLabel" ); + maLocationTxt.SMHID2( "JobPage", "LocationText" ); + maCommentLabel.SMHID2( "JobPage", "CommentLabel" ); + maCommentTxt.SMHID2( "JobPage", "CommentText" ); maSetupButton.SMHID2( "JobPage", "Setup" ); - maToFileBox.SMHID2( "JobPage", "ToFile" ); maCopies.SMHID2( "JobPage", "CopiesLine" ); + maCopySpacer.SMHID2( "JobPage", "CopySpacer" ); maCopyCount.SMHID2( "JobPage", "CopiesText" ); maCopyCountField.SMHID2( "JobPage", "Copies" ); maCollateBox.SMHID2( "JobPage", "Collate" ); maCollateImage.SMHID2( "JobPage", "CollateImage" ); + + maCopySpacer.Show(); + maStatusTxt.Show(); + maCommentTxt.Show(); + maLocationTxt.Show(); + + setupLayout(); } PrintDialog::JobTabPage::~JobTabPage() { } +void PrintDialog::JobTabPage::setupLayout() +{ + // HACK: this is not a dropdown box, but the dropdown line count + // sets the results of GetOptimalSize in a normal ListBox + maPrinters.SetDropDownLineCount( 4 ); + + Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); + + maLayout.setParentWindow( this ); + maLayout.setOuterBorder( aBorder.Width() ); + + // add printer fixed line + maLayout.addWindow( &maPrinterFL ); + // add print LB + maLayout.addWindow( &maPrinters ); + + // create a row for stati and properties button + boost::shared_ptr< vcl::RowOrColumn > xStateRow( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xStateRow ); + boost::shared_ptr< vcl::RowOrColumn > xLabelCol( new vcl::RowOrColumn( xStateRow.get(), true, aBorder.Height() ) ); + xStateRow->addChild( xLabelCol ); + xLabelCol->addWindow( &maStatusLabel ); + xLabelCol->addWindow( &maLocationLabel ); + xLabelCol->addWindow( &maCommentLabel ); + + boost::shared_ptr< vcl::RowOrColumn > xStatusCol( new vcl::RowOrColumn( xStateRow.get(), true, aBorder.Height() ) ); + xStateRow->addChild( xStatusCol ); + xStatusCol->addWindow( &maStatusTxt ); + xStatusCol->addWindow( &maLocationTxt ); + xStatusCol->addWindow( &maCommentTxt ); + + xStateRow->addWindow( &maSetupButton ); + + // add print range and copies columns + maLayout.addWindow( &maCopies ); + boost::shared_ptr< vcl::RowOrColumn > xRangeRow( new vcl::RowOrColumn( &maLayout, false, aBorder.Width() ) ); + maLayout.addChild( xRangeRow ); + + // create print range and add to range row + mxPrintRange.reset( new vcl::RowOrColumn( xRangeRow.get() ) ); + xRangeRow->addChild( mxPrintRange ); + xRangeRow->addWindow( &maCopySpacer ); + + boost::shared_ptr< vcl::RowOrColumn > xCopyCollateCol( new vcl::RowOrColumn( xRangeRow.get() ) ); + xRangeRow->addChild( xCopyCollateCol ); + + // add copies row to copy/collate column + boost::shared_ptr< vcl::RowOrColumn > xCopiesRow( new vcl::RowOrColumn( xCopyCollateCol.get(), false, 0 ) ); + xCopyCollateCol->addChild( xCopiesRow ); + xCopiesRow->addWindow( &maCopyCount ); + xCopiesRow->addWindow( &maCopyCountField ); + boost::shared_ptr< vcl::RowOrColumn > xCollateRow( new vcl::RowOrColumn( xCopyCollateCol.get(), false, 0 ) ); + xCopyCollateCol->addChild( xCollateRow ); + xCollateRow->addWindow( &maCollateBox ); + xCollateRow->addWindow( &maCollateImage ); +} + void PrintDialog::JobTabPage::readFromSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); - maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); - #if 0 // do not actually make copy count persistent // the assumption is that this would lead to a lot of unwanted copies @@ -395,9 +461,6 @@ void PrintDialog::JobTabPage::readFromSettings() void PrintDialog::JobTabPage::storeToSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ), - rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CopyCount" ) ), maCopyCountField.GetText() ); @@ -406,6 +469,47 @@ void PrintDialog::JobTabPage::storeToSettings() rtl::OUString::createFromAscii( maCollateBox.IsChecked() ? "true" : "false" ) ); } +void PrintDialog::JobTabPage::Resize() +{ + maLayout.setManagedArea( Rectangle( Point( 0, 0 ), GetSizePixel() ) ); +} + +PrintDialog::OutputOptPage::OutputOptPage( Window* i_pParent, const ResId& i_rResId ) + : TabPage( i_pParent, i_rResId ) + , maOptionsLine( this, VclResId( SV_PRINT_OPT_PRINT_FL ) ) + , maToFileBox( this, VclResId( SV_PRINT_OPT_TOFILE ) ) + , maCollateSingleJobsBox( this, VclResId( SV_PRINT_OPT_SINGLEJOBS ) ) + , maReverseOrderBox( this, VclResId( SV_PRINT_OPT_REVERSE ) ) +{ + maOptionsLine.SMHID2( "OptPage", "Options" ); + maToFileBox.SMHID2( "OptPage", "ToFile" ); + maCollateSingleJobsBox.SMHID2( "OptPage", "SingleJobs" ); + maReverseOrderBox.SMHID2( "OptPage", "Reverse" ); +} + +PrintDialog::OutputOptPage::~OutputOptPage() +{ +} + +void PrintDialog::OutputOptPage::readFromSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + rtl::OUString aValue; + + aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); + maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); +} + +void PrintDialog::OutputOptPage::storeToSettings() +{ + SettingsConfigItem* pItem = SettingsConfigItem::get(); + pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), + rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ), + rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); +} + + PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rController ) : ModalDialog( i_pParent, VclResId( SV_DLG_PRINT ) ) , maOKButton( this, VclResId( SV_PRINT_OK ) ) @@ -418,15 +522,12 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr aDynamicColumns; vcl::RowOrColumn* pCurColumn = 0; - aPrintRangeRow.setParentWindow( &maJobPage ); - aPrintRangeRow.setOuterBorder( nBorderWidth ); - Window* pCurParent = 0, *pDynamicPageParent = 0; USHORT nOptPageId = 9, nCurSubGroup = 0; bool bOnJobPage = false; @@ -687,7 +790,7 @@ void PrintDialog::setupOptionalUI() Sequence< rtl::OUString > aHelpTexts; sal_Int64 nMinValue = 0, nMaxValue = 0; sal_Int32 nCurHelpText = 0; - sal_Bool bOnJobPageValue = sal_False; + rtl::OUString aGroupingHint; rtl::OUString aDependsOnName; sal_Int32 nDependsOnValue = 0; sal_Bool bUseDependencyRow = sal_False; @@ -719,9 +822,9 @@ void PrintDialog::setupOptionalUI() rEntry.Value >>= bValue; bEnabled = bValue; } - else if( rEntry.Name.equalsAscii( "PutOnJobPage" ) ) + else if( rEntry.Name.equalsAscii( "GroupingHint" ) ) { - rEntry.Value >>= bOnJobPageValue; + rEntry.Value >>= aGroupingHint; } else if( rEntry.Name.equalsAscii( "DependsOnName" ) ) { @@ -758,7 +861,7 @@ void PrintDialog::setupOptionalUI() } if( aCtrlType.equalsAscii( "Group" ) || - ( ! pCurParent && ! (bOnJobPage || bOnJobPageValue) ) ) + ( ! pCurParent && ! (bOnJobPage || aGroupingHint.getLength() ) ) ) { // add new tab page TabPage* pNewGroup = new TabPage( &maTabCtrl ); @@ -781,13 +884,13 @@ void PrintDialog::setupOptionalUI() pCurColumn->setParentWindow( pNewGroup ); pCurColumn->setOuterBorder( nBorderWidth ); } - else if( aCtrlType.equalsAscii( "Subgroup" ) && (pCurParent || bOnJobPageValue) ) + else if( aCtrlType.equalsAscii( "Subgroup" ) && (pCurParent || aGroupingHint.getLength() ) ) { // change to job page or back if necessary - if( (bOnJobPage && ! bOnJobPageValue) || - (! bOnJobPage && bOnJobPageValue) ) + if( (bOnJobPage && ! aGroupingHint.getLength() ) || + (! bOnJobPage && aGroupingHint.getLength() ) ) { - bOnJobPage = bOnJobPageValue; + bOnJobPage = (aGroupingHint.getLength() != 0); if( bOnJobPage ) { pDynamicPageParent = pCurParent; // save current parent @@ -801,27 +904,31 @@ void PrintDialog::setupOptionalUI() if( bOnJobPage ) { - // create a new column in the PrintRange row - vcl::RowOrColumn* pNewColumn = new vcl::RowOrColumn( &aPrintRangeRow, true, nBorderWidth ); - aPrintRangeRow.addChild( pNewColumn ); - pCurColumn = pNewColumn; + if( aGroupingHint.equalsAscii( "PrintRange" ) ) + pCurColumn = maJobPage.mxPrintRange.get(); + else + pCurColumn = &maJobPage.maLayout; } else pCurColumn = aDynamicColumns.back(); // create group FixedLine - FixedLine* pNewSub = new FixedLine( pCurParent ); - maControls.push_front( pNewSub ); - pNewSub->SetText( aText ); - pNewSub->Show(); - - // set help id - setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); - // set help text - setHelpText( pNewSub, aHelpTexts, 0 ); + if( ! aGroupingHint.equalsAscii( "PrintRange" ) || + ! pCurColumn->countElements() == 0 + ) + { + FixedLine* pNewSub = new FixedLine( pCurParent ); + maControls.push_front( pNewSub ); + pNewSub->SetText( aText ); + pNewSub->Show(); - // add group to current column - pCurColumn->addWindow( pNewSub ); + // set help id + setSmartId( pNewSub, "FixedLine", sal_Int32( nCurSubGroup++ ) ); + // set help text + setHelpText( pNewSub, aHelpTexts, 0 ); + // add group to current column + pCurColumn->addWindow( pNewSub ); + } } else { @@ -1055,11 +1162,7 @@ void PrintDialog::setupOptionalUI() } // calculate job page - long nJobPageCurY = maJobPage.maCollateImage.GetPosPixel().Y(); - nJobPageCurY += maJobPage.maCollateImage.GetSizePixel().Height(); - - Size aMaxSize = aPrintRangeRow.getOptimalSize( WINDOWSIZE_PREFERRED ); - aMaxSize.Height() += nJobPageCurY; + Size aMaxSize = maJobPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ); Size aMaxPageSize; for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); @@ -1095,8 +1198,6 @@ void PrintDialog::setupOptionalUI() // and finally arrange controls aTabSize = maTabCtrl.GetTabPageSizePixel(); - aPrintRangeRow.setManagedArea( Rectangle( Point( 0, nJobPageCurY ), - Size( aTabSize.Width(), aTabSize.Height() - nJobPageCurY ) ) ); for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); it != aDynamicColumns.end(); ++it ) { @@ -1184,14 +1285,16 @@ void PrintDialog::updatePrinterText() const QueueInfo* pInfo = Printer::GetQueueInfo( maJobPage.maPrinters.GetSelectEntry(), true ); if( pInfo ) { - rtl::OUStringBuffer aBuf( 256 ); - aBuf.append( searchAndReplace( maTypeText, "%s", 2, pInfo->GetDriver() ) ); - aBuf.append( sal_Unicode( '\n' ) ); - aBuf.append( searchAndReplace( maLocationText, "%s", 2, pInfo->GetLocation() ) ); - aBuf.append( sal_Unicode( '\n' ) ); - aBuf.append( searchAndReplace( maCommentText, "%s", 2, pInfo->GetComment() ) ); - aBuf.append( sal_Unicode( '\n' ) ); - maJobPage.maPrinters.SetHelpText( aBuf.makeStringAndClear() ); + maJobPage.maLocationTxt.SetText( pInfo->GetLocation() ); + maJobPage.maCommentTxt.SetText( pInfo->GetComment() ); + // FIXME: status text + maJobPage.maStatusTxt.SetText( String() ); + } + else + { + maJobPage.maLocationTxt.SetText( String() ); + maJobPage.maCommentTxt.SetText( String() ); + maJobPage.maStatusTxt.SetText( String() ); } } @@ -1319,6 +1422,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) { maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), makeAny( sal_Bool(isCollate()) ) ); + checkControlDependencies(); } else { -- cgit From d3e83bb08919ad8f87a03069f0e12e9ccf6c8806 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 23 Jul 2009 17:22:34 +0000 Subject: #i92516# adapt new UX spec --- vcl/inc/vcl/prndlg.hxx | 6 ++++ vcl/source/control/lstbox.cxx | 15 +++++++++ vcl/source/gdi/print3.cxx | 2 +- vcl/source/src/print.src | 2 +- vcl/source/window/arrange.cxx | 2 +- vcl/source/window/printdlg.cxx | 73 +++++++++++++++++++++++++++++++++--------- 6 files changed, 81 insertions(+), 19 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 5577592bc775..2569000dd9f0 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -158,11 +158,17 @@ namespace vcl CheckBox maCollateSingleJobsBox; CheckBox maReverseOrderBox; + vcl::RowOrColumn maLayout; + OutputOptPage( Window*, const ResId& ); virtual ~OutputOptPage(); void readFromSettings(); void storeToSettings(); + + virtual void Resize(); + + void setupLayout(); }; OKButton maOKButton; diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 37c289851898..476c5d8f4b7f 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -1286,6 +1286,21 @@ Size ListBox::CalcMinimumSize() const } aSz = CalcWindowSize( aSz ); + + if ( IsDropDownBox() ) // check minimum height of dropdown box + { + ImplControlValue aControlValue; + Rectangle aRect( Point( 0, 0 ), aSz ); + Region aContent, aBound; + if( const_cast(this)->GetNativeControlRegion( + CTRL_LISTBOX, PART_ENTIRE_CONTROL, aRect, 0, aControlValue, rtl::OUString(), aBound, aContent) ) + { + Rectangle aBoundRect( aBound.GetBoundRect() ); + if( aBoundRect.GetHeight() > aSz.Height() ) + aSz.Height() = aBoundRect.GetHeight(); + } + } + return aSz; } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index db77313db446..53326cb3efbd 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1032,7 +1032,7 @@ bool PrinterController::isUIOptionEnabled( const rtl::OUString& i_rProperty ) co sal_Bool bDepVal = sal_False; if( pVal->Value >>= nDepVal ) { - bEnabled = (nDepVal == it->second.mnDependsOnEntry); + bEnabled = (nDepVal == it->second.mnDependsOnEntry) || (it->second.mnDependsOnEntry == -1); } else if( pVal->Value >>= bDepVal ) { diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 3a3afd8c568a..1e09b7c9fcc1 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -103,7 +103,7 @@ ModalDialog SV_DLG_PRINT TabPage SV_PRINT_TAB_NUP { - Text [en-US] = "N-Up"; + Text [en-US] = "Page Layout"; Hide = TRUE; FixedLine SV_PRINT_PRT_NUP diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 917b04fcc855..665c83e5f2d5 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -353,7 +353,7 @@ void Indenter::resize() aPt.X() += m_nOuterBorder + m_nIndent; aPt.Y() += m_nOuterBorder; Size aSz( m_aManagedArea.GetSize() ); - aSz.Width() -= 2*m_nOuterBorder - m_nIndent; + aSz.Width() -= 2*m_nOuterBorder + m_nIndent; aSz.Height() -= 2*m_nOuterBorder; if( m_aElement.m_pElement ) m_aElement.m_pElement->SetPosSizePixel( aPt, aSz ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index a52f1a954315..09d2532fa812 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -485,12 +485,31 @@ PrintDialog::OutputOptPage::OutputOptPage( Window* i_pParent, const ResId& i_rRe maToFileBox.SMHID2( "OptPage", "ToFile" ); maCollateSingleJobsBox.SMHID2( "OptPage", "SingleJobs" ); maReverseOrderBox.SMHID2( "OptPage", "Reverse" ); + + setupLayout(); } PrintDialog::OutputOptPage::~OutputOptPage() { } +void PrintDialog::OutputOptPage::setupLayout() +{ + Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); + + maLayout.setParentWindow( this ); + maLayout.setOuterBorder( aBorder.Width() ); + + maLayout.addWindow( &maOptionsLine ); + boost::shared_ptr xIndent( new vcl::Indenter( &maLayout, aBorder.Width() ) ); + maLayout.addChild( xIndent ); + boost::shared_ptr xCol( new vcl::RowOrColumn( xIndent.get(), aBorder.Height() ) ); + xIndent->setChild( xCol ); + xCol->addWindow( &maToFileBox ); + xCol->addWindow( &maCollateSingleJobsBox ); + xCol->addWindow( &maReverseOrderBox ); +} + void PrintDialog::OutputOptPage::readFromSettings() { SettingsConfigItem* pItem = SettingsConfigItem::get(); @@ -509,6 +528,11 @@ void PrintDialog::OutputOptPage::storeToSettings() rtl::OUString::createFromAscii( maToFileBox.IsChecked() ? "true" : "false" ) ); } +void PrintDialog::OutputOptPage::Resize() +{ + maLayout.setManagedArea( Rectangle( Point( 0, 0 ), GetSizePixel() ) ); +} + PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_rController ) : ModalDialog( i_pParent, VclResId( SV_DLG_PRINT ) ) @@ -542,11 +566,9 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr& i_r void PrintDialog::setupOptionalUI() { - const long nBorderWidth = maJobPage.maCopies.GetPosPixel().X(); + Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); std::vector aDynamicColumns; vcl::RowOrColumn* pCurColumn = 0; Window* pCurParent = 0, *pDynamicPageParent = 0; USHORT nOptPageId = 9, nCurSubGroup = 0; - bool bOnJobPage = false; + bool bOnStaticPage = false; std::multimap< rtl::OUString, vcl::RowOrColumn* > aPropertyToDependencyRowMap; @@ -861,12 +885,12 @@ void PrintDialog::setupOptionalUI() } if( aCtrlType.equalsAscii( "Group" ) || - ( ! pCurParent && ! (bOnJobPage || aGroupingHint.getLength() ) ) ) + ( ! pCurParent && ! (bOnStaticPage || aGroupingHint.getLength() ) ) ) { // add new tab page TabPage* pNewGroup = new TabPage( &maTabCtrl ); maControls.push_front( pNewGroup ); - pCurParent = pNewGroup; + pDynamicPageParent = pCurParent = pNewGroup; pNewGroup->SetText( aText ); maTabCtrl.InsertPage( ++nOptPageId, aText ); maTabCtrl.SetTabPage( nOptPageId, pNewGroup ); @@ -879,22 +903,21 @@ void PrintDialog::setupOptionalUI() // reset subgroup counter nCurSubGroup = 0; - aDynamicColumns.push_back( new vcl::RowOrColumn( NULL, true, nBorderWidth ) ); + aDynamicColumns.push_back( new vcl::RowOrColumn( NULL, true, aBorder.Width() ) ); pCurColumn = aDynamicColumns.back(); pCurColumn->setParentWindow( pNewGroup ); - pCurColumn->setOuterBorder( nBorderWidth ); + pCurColumn->setOuterBorder( aBorder.Width() ); } else if( aCtrlType.equalsAscii( "Subgroup" ) && (pCurParent || aGroupingHint.getLength() ) ) { // change to job page or back if necessary - if( (bOnJobPage && ! aGroupingHint.getLength() ) || - (! bOnJobPage && aGroupingHint.getLength() ) ) + if( (bOnStaticPage && ! aGroupingHint.getLength() ) || + (! bOnStaticPage && aGroupingHint.getLength() ) ) { - bOnJobPage = (aGroupingHint.getLength() != 0); - if( bOnJobPage ) + bOnStaticPage = (aGroupingHint.getLength() != 0); + if( bOnStaticPage ) { pDynamicPageParent = pCurParent; // save current parent - pCurParent = &maJobPage; // set job page as current parent } else { @@ -902,12 +925,23 @@ void PrintDialog::setupOptionalUI() } } - if( bOnJobPage ) + if( bOnStaticPage ) { if( aGroupingHint.equalsAscii( "PrintRange" ) ) + { pCurColumn = maJobPage.mxPrintRange.get(); + pCurParent = &maJobPage; // set job page as current parent + } + else if( aGroupingHint.equalsAscii( "OptionsPage" ) ) + { + pCurColumn = &maOptionsPage.maLayout; + pCurParent = &maOptionsPage; // set options page as current parent + } else + { pCurColumn = &maJobPage.maLayout; + pCurParent = &maJobPage; // set job page as current parent + } } else pCurColumn = aDynamicColumns.back(); @@ -929,6 +963,13 @@ void PrintDialog::setupOptionalUI() // add group to current column pCurColumn->addWindow( pNewSub ); } + + // add an indent to the current column + vcl::Indenter* pIndent = new vcl::Indenter( pCurColumn, aBorder.Width() ); + pCurColumn->addChild( pIndent ); + // and create a column inside the indent + pCurColumn = new vcl::RowOrColumn( pIndent ); + pIndent->setChild( pCurColumn ); } else { -- cgit From 6d16b13150863dc7506506863e73e28d5ff569ad Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 24 Jul 2009 13:15:45 +0000 Subject: #i92516# adapt new print UI spec --- vcl/inc/vcl/arrange.hxx | 103 ++++++++++++++------- vcl/inc/vcl/prndlg.hxx | 15 ++-- vcl/inc/vcl/svids.hrc | 1 + vcl/inc/vcl/tabctrl.hxx | 3 + vcl/source/control/tabctrl.cxx | 23 +++++ vcl/source/src/print.src | 6 +- vcl/source/window/arrange.cxx | 144 +++++++++++++++++------------- vcl/source/window/printdlg.cxx | 198 ++++++++++++++++++++++++----------------- 8 files changed, 311 insertions(+), 182 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 2a9d83b7b769..febbe69491a2 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -53,12 +53,13 @@ namespace vcl class WindowArranger { - protected: + protected: struct Element { Window* m_pElement; boost::shared_ptr m_pChild; sal_Int32 m_nExpandPriority; + Size m_aMinSize; Element() : m_pElement( NULL ) @@ -78,6 +79,7 @@ namespace vcl void deleteChild() { m_pChild.reset(); } sal_Int32 getExpandPriority() const; + Size getOptimalSize( WindowSizeType ) const; }; Window* m_pParentWindow; @@ -85,7 +87,12 @@ namespace vcl Rectangle m_aManagedArea; long m_nOuterBorder; - public: + virtual Element* getElement( size_t i_nIndex ) = NULL; + const Element* getConstElement( size_t i_nIndex ) const + { return const_cast(this)->getElement( i_nIndex ); } + + + public: WindowArranger( WindowArranger* i_pParent = NULL ) : m_pParentWindow( i_pParent ? i_pParent->m_pParentWindow : NULL ) , m_pParentArranger( i_pParent ) @@ -106,9 +113,39 @@ namespace vcl virtual void setParent( WindowArranger* ); virtual size_t countElements() const = 0; - virtual boost::shared_ptr getChild( size_t i_nIndex ) const = 0; - virtual Window* getWindow( size_t i_nIndex ) const = 0; - virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const = 0; + boost::shared_ptr getChild( size_t i_nIndex ) const + { + const Element* pEle = getConstElement( i_nIndex ); + return pEle ? pEle->m_pChild : boost::shared_ptr(); + } + Window* getWindow( size_t i_nIndex ) const + { + const Element* pEle = getConstElement( i_nIndex ); + return pEle ? pEle->m_pElement : NULL; + } + + sal_Int32 getExpandPriority( size_t i_nIndex ) const + { + const Element* pEle = getConstElement( i_nIndex ); + return pEle ? pEle->getExpandPriority() : 0; + } + + Size getMinimumSize( size_t i_nIndex ) const + { + const Element* pEle = getConstElement( i_nIndex ); + return pEle ? pEle->m_aMinSize : Size(); + } + + bool setMinimumSize( size_t i_nIndex, const Size& i_rMinSize ) + { + Element* pEle = getElement( i_nIndex ); + if( pEle ) + { + pEle->m_aMinSize = i_rMinSize; + resize(); + } + return pEle != NULL; + } void setManagedArea( const Rectangle& i_rArea ) { @@ -132,7 +169,12 @@ namespace vcl std::vector< WindowArranger::Element > m_aElements; void distributeRowWidth( std::vector< Size >& io_rSizes, long i_nUsedWidth, long i_nExtraWidth ); - public: + void distributeColumnHeight( std::vector< Size >& io_rSizes, long i_nUsedHeight, long i_nExtraHeight ); + protected: + virtual Element* getElement( size_t i_nIndex ) + { return i_nIndex < m_aElements.size() ? &m_aElements[ i_nIndex ] : 0; } + + public: RowOrColumn( WindowArranger* i_pParent = NULL, bool bColumn = true, long i_nBorderWidth = 5 ) : WindowArranger( i_pParent ) @@ -146,19 +188,16 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return m_aElements.size(); } - virtual boost::shared_ptr getChild( size_t i_nIndex ) const; - virtual Window* getWindow( size_t i_nIndex ) const; - virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const; // add a managed window at the given index // an index smaller than zero means add the window at the end - void addWindow( Window*, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ); + size_t addWindow( Window*, sal_Int32 i_nExpandPrio = 0, size_t i_nIndex = ~0 ); void remove( Window* ); - void addChild( boost::shared_ptr const &, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ); + size_t addChild( boost::shared_ptr const &, sal_Int32 i_nExpandPrio = 0, size_t i_nIndex = ~0 ); // convenience: use for addChild( new WindowArranger( ... ) ) constructs - void addChild( WindowArranger* i_pNewChild, sal_Int32 i_nExpandPrio = 0, sal_Int32 i_nIndex = -1 ) - { addChild( boost::shared_ptr( i_pNewChild ), i_nExpandPrio, i_nIndex ); } + size_t addChild( WindowArranger* i_pNewChild, sal_Int32 i_nExpandPrio = 0, size_t i_nIndex = ~0 ) + { return addChild( boost::shared_ptr( i_pNewChild ), i_nExpandPrio, i_nIndex ); } void remove( boost::shared_ptr const & ); }; @@ -167,7 +206,11 @@ namespace vcl long m_nIndent; WindowArranger::Element m_aElement; - public: + protected: + virtual Element* getElement( size_t i_nIndex ) + { return i_nIndex == 0 ? &m_aElement : NULL; } + + public: Indenter( WindowArranger* i_pParent = NULL, long i_nIndent = 15 ) : WindowArranger( i_pParent ) , m_nIndent( i_nIndent ) @@ -179,10 +222,6 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } - virtual boost::shared_ptr getChild( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pChild : boost::shared_ptr(); } - virtual Window* getWindow( size_t i_nIndex ) const { return (i_nIndex == 0) ? m_aElement.m_pElement : NULL; } - virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const - { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } void setIndent( long i_nIndent ) { @@ -201,7 +240,12 @@ namespace vcl { WindowArranger::Element m_aElement; Size m_aSize; - public: + + protected: + virtual Element* getElement( size_t i_nIndex ) + { return i_nIndex == 0 ? &m_aElement : NULL; } + + public: Spacer( WindowArranger* i_pParent = NULL, sal_Int32 i_nPrio = 20, const Size& i_rSize = Size( 0, 0 ) ) : WindowArranger( i_pParent ) , m_aElement( NULL, boost::shared_ptr(), i_nPrio ) @@ -215,10 +259,6 @@ namespace vcl virtual void resize() {} virtual void setParentWindow( Window* ) {} virtual size_t countElements() const { return 1; } - virtual boost::shared_ptr getChild( size_t ) const { return boost::shared_ptr(); } - virtual Window* getWindow( size_t ) const { return NULL; } - virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const - { return (i_nIndex == 0) ? m_aElement.getExpandPriority() : 0; } }; class MatrixArranger : public WindowArranger @@ -256,7 +296,11 @@ namespace vcl { return static_cast< sal_uInt64 >(i_nX) | (static_cast< sal_uInt64>(i_nY) << 32 ); } Size getOptimalSize( WindowSizeType, std::vector& o_rColumnWidths, std::vector& o_rRowHeights ) const; - public: + protected: + virtual Element* getElement( size_t i_nIndex ) + { return i_nIndex < m_aElements.size() ? &m_aElements[ i_nIndex ] : 0; } + + public: MatrixArranger( WindowArranger* i_pParent = NULL, long i_nBorderX = 5, long i_nBorderY = 5 ) @@ -271,18 +315,15 @@ namespace vcl virtual void resize(); virtual void setParentWindow( Window* ); virtual size_t countElements() const { return m_aElements.size(); } - virtual boost::shared_ptr getChild( size_t i_nIndex ) const; - virtual Window* getWindow( size_t i_nIndex ) const; - virtual sal_Int32 getExpandPriority( size_t i_nIndex ) const; // add a managed window at the given matrix position - void addWindow( Window*, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); + size_t addWindow( Window*, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); void remove( Window* ); - void addChild( boost::shared_ptr const &, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); + size_t addChild( boost::shared_ptr const &, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ); // convenience: use for addChild( new WindowArranger( ... ) ) constructs - void addChild( WindowArranger* i_pNewChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ) - { addChild( boost::shared_ptr( i_pNewChild ), i_nX, i_nY, i_nExpandPrio ); } + size_t addChild( WindowArranger* i_pNewChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio = 0 ) + { return addChild( boost::shared_ptr( i_pNewChild ), i_nX, i_nY, i_nExpandPrio ); } void remove( boost::shared_ptr const & ); }; diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 2569000dd9f0..03ecdfc79979 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -45,6 +45,7 @@ #include "vcl/tabctrl.hxx" #include "vcl/tabpage.hxx" #include "vcl/arrange.hxx" +#include "vcl/virdev.hxx" #include #include @@ -56,17 +57,17 @@ namespace vcl class PrintPreviewWindow : public Window { GDIMetaFile maMtf; - double mfScaleX; - double mfScaleY; + Size maOrigSize; + VirtualDevice maPageVDev; public: PrintPreviewWindow( Window* pParent, const ResId& ); virtual ~PrintPreviewWindow(); virtual void Paint( const Rectangle& rRect ); virtual void Command( const CommandEvent& ); + virtual void Resize(); - void setPreview( const GDIMetaFile& ); - void setScale( double fScaleX, double fScaleY ); + void setPreview( const GDIMetaFile&, const Size& ); }; class NUpTabPage : public TabPage @@ -192,7 +193,6 @@ namespace vcl rtl::OUString maNoPageStr; sal_Int32 mnCurPage; sal_Int32 mnCachedPages; - Rectangle maPreviewSpace; Size maCurPageSize; std::list< Window* > maControls; @@ -206,8 +206,7 @@ namespace vcl rtl::OUString maPrintToFileText; rtl::OUString maPrintText; - vcl::RowOrColumn maPreviewCtrlRow; - Rectangle maPreviewBackground; + vcl::RowOrColumn maLayout; void updateNup(); void preparePreview( bool i_bPrintChanged = true, bool i_bMayUseCache = false ); @@ -221,7 +220,6 @@ namespace vcl com::sun::star::beans::PropertyValue* getValueForWindow( Window* ) const; virtual void Resize(); - virtual void Paint( const Rectangle& ); virtual void Command( const CommandEvent& ); DECL_LINK( SelectHdl, ListBox* ); @@ -234,6 +232,7 @@ namespace vcl DECL_LINK( UIOption_SelectHdl, ListBox* ); DECL_LINK( UIOption_ModifyHdl, Edit* ); + void setupLayout(); public: PrintDialog( Window*, const boost::shared_ptr< PrinterController >& ); virtual ~PrintDialog(); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index b00f1742fced..681017107a1b 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -87,6 +87,7 @@ #define SV_PRINT_PRT_STATUS 10 #define SV_PRINT_PRT_LOCATION 11 #define SV_PRINT_PRT_COMMENT 12 +#define SV_PRINT_TOFILE_TXT 13 #define SV_PRINT_TAB_NUP 1 #define SV_PRINT_PRT_NUP 1 diff --git a/vcl/inc/vcl/tabctrl.hxx b/vcl/inc/vcl/tabctrl.hxx index 25aa9d1ae581..f5e0b64b58ee 100644 --- a/vcl/inc/vcl/tabctrl.hxx +++ b/vcl/inc/vcl/tabctrl.hxx @@ -127,6 +127,9 @@ public: virtual void ActivatePage(); virtual long DeactivatePage(); + virtual Size GetOptimalSize(WindowSizeType eType) const; + void SetMinimumSizePixel( const Size& ); + void SetTabPageSizePixel( const Size& rSize ); Size GetTabPageSizePixel() const; diff --git a/vcl/source/control/tabctrl.cxx b/vcl/source/control/tabctrl.cxx index 9ff3e4f5a728..b13be2f43b3d 100644 --- a/vcl/source/control/tabctrl.cxx +++ b/vcl/source/control/tabctrl.cxx @@ -89,6 +89,7 @@ struct ImplTabCtrlData Point maItemsOffset; // offset of the tabitems std::vector< ImplTabItem > maItemList; ListBox* mpListBox; + Size maMinSize; }; // ----------------------------------------------------------------------- @@ -2303,3 +2304,25 @@ Point TabControl::GetItemsOffset() const } // ----------------------------------------------------------------------- + +Size TabControl::GetOptimalSize(WindowSizeType eType) const +{ + switch (eType) { + case WINDOWSIZE_MINIMUM: + return mpTabCtrlData ? mpTabCtrlData->maMinSize : Size(); + default: + return Control::GetOptimalSize( eType ); + } +} + +// ----------------------------------------------------------------------- + +void TabControl::SetMinimumSizePixel( const Size& i_rSize ) +{ + if( mpTabCtrlData ) + mpTabCtrlData->maMinSize = i_rSize; +} + +// ----------------------------------------------------------------------- + + diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 1e09b7c9fcc1..eb7ae8966d82 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -89,7 +89,6 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 140, 5 ); Size = MAP_APPFONT( 205, 175 ); -// DropDown = TRUE; }; FixedLine SV_PRINT_BUTTONLINE { @@ -101,6 +100,11 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "No pages"; }; + String SV_PRINT_TOFILE_TXT + { + Text [en-US] = "Print to file..."; + }; + TabPage SV_PRINT_TAB_NUP { Text [en-US] = "Page Layout"; diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 665c83e5f2d5..4f03706b4264 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -69,6 +69,21 @@ sal_Int32 WindowArranger::Element::getExpandPriority() const return nPrio; } +Size WindowArranger::Element::getOptimalSize( WindowSizeType i_eType ) const +{ + Size aResult; + if( m_pElement ) + aResult = m_pElement->GetOptimalSize( i_eType ); + else if( m_pChild ) + aResult = m_pChild->getOptimalSize( i_eType ); + if( aResult.Width() < m_aMinSize.Width() ) + aResult.Width() = m_aMinSize.Width(); + if( aResult.Height() < m_aMinSize.Height() ) + aResult.Height() = m_aMinSize.Height(); + + return aResult; +} + // ---------------------------------------- // vcl::RowOrColumn //----------------------------------------- @@ -82,21 +97,6 @@ RowOrColumn::~RowOrColumn() } } -boost::shared_ptr RowOrColumn::getChild( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : boost::shared_ptr(); -} - -Window* RowOrColumn::getWindow( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL; -} - -sal_Int32 RowOrColumn::getExpandPriority( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].getExpandPriority() : 0; -} - Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const { Size aRet( 0, 0 ); @@ -112,11 +112,7 @@ Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const it != m_aElements.end(); ++it ) { // get the size of type of the managed element - Size aElementSize( it->m_pElement - ? it->m_pElement->GetOptimalSize( i_eType ) - : it->m_pChild - ? it->m_pChild->getOptimalSize( i_eType ) - : Size() ); + Size aElementSize( it->getOptimalSize( i_eType ) ); if( m_bColumn ) { // add the distance between elements @@ -181,6 +177,43 @@ void RowOrColumn::distributeRowWidth( std::vector& io_rSizes, long /*i_nUs } } +void RowOrColumn::distributeColumnHeight( std::vector& io_rSizes, long /*i_nUsedHeight*/, long i_nExtraHeight ) +{ + if( ! io_rSizes.empty() && io_rSizes.size() == m_aElements.size() ) + { + // find all elements with the highest expand priority + size_t nElements = m_aElements.size(); + std::vector< size_t > aIndices; + sal_Int32 nHighPrio = 3; + for( size_t i = 0; i < nElements; i++ ) + { + sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); + if( nCurPrio > nHighPrio ) + { + aIndices.clear(); + nHighPrio = nCurPrio; + } + if( nCurPrio == nHighPrio ) + aIndices.push_back( i ); + } + + // distribute extra space evenly among elements + nElements = aIndices.size(); + if( nElements > 0 ) // sanity check + { + long nDelta = i_nExtraHeight / nElements; + for( size_t i = 0; i < nElements; i++ ) + { + io_rSizes[ aIndices[i] ].Height() += nDelta; + i_nExtraHeight -= nDelta; + } + // add the last pixels to the last row element + if( i_nExtraHeight > 0 && nElements > 0 ) + io_rSizes[aIndices.back()].Height() += i_nExtraHeight; + } + } +} + void RowOrColumn::resize() { // check if we can get optimal size, else fallback to minimal size @@ -203,11 +236,7 @@ void RowOrColumn::resize() long nUsedWidth = 2*m_nOuterBorder - (nElements ? m_nBorderWidth : 0); for( size_t i = 0; i < nElements; i++ ) { - aElementSizes[i] = m_aElements[i].m_pElement - ? m_aElements[i].m_pElement->GetOptimalSize( eType ) - : m_aElements[i].m_pChild - ? m_aElements[i].m_pChild->getOptimalSize( eType ) - : Size(); + aElementSizes[i] = m_aElements[i].getOptimalSize( eType ); if( m_bColumn ) { aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder; @@ -220,9 +249,11 @@ void RowOrColumn::resize() } } - long nExtraWidth = m_aManagedArea.GetWidth() - nUsedWidth; + long nExtraWidth = (m_bColumn ? m_aManagedArea.GetHeight() : m_aManagedArea.GetWidth()) - nUsedWidth; if( nExtraWidth > 0 ) - if( ! m_bColumn ) + if( m_bColumn ) + distributeColumnHeight( aElementSizes, nUsedWidth, nExtraWidth ); + else distributeRowWidth( aElementSizes, nUsedWidth, nExtraWidth ); // get starting position @@ -268,10 +299,14 @@ void RowOrColumn::setParentWindow( Window* i_pNewParent ) } } -void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio, sal_Int32 i_nIndex ) +size_t RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio, size_t i_nIndex ) { - if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) + size_t nIndex = i_nIndex; + if( i_nIndex >= m_aElements.size() ) + { + nIndex = m_aElements.size(); m_aElements.push_back( WindowArranger::Element( i_pWindow, boost::shared_ptr(), i_nExpandPrio ) ); + } else { std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); @@ -279,12 +314,17 @@ void RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio, sal_Int ++it; m_aElements.insert( it, WindowArranger::Element( i_pWindow, boost::shared_ptr(), i_nExpandPrio ) ); } + return nIndex; } -void RowOrColumn::addChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nExpandPrio, sal_Int32 i_nIndex ) +size_t RowOrColumn::addChild( boost::shared_ptr const & i_pChild, sal_Int32 i_nExpandPrio, size_t i_nIndex ) { - if( i_nIndex < 0 || size_t(i_nIndex) >= m_aElements.size() ) + size_t nIndex = i_nIndex; + if( i_nIndex >= m_aElements.size() ) + { + nIndex = m_aElements.size(); m_aElements.push_back( WindowArranger::Element( NULL, i_pChild, i_nExpandPrio ) ); + } else { std::vector< WindowArranger::Element >::iterator it = m_aElements.begin(); @@ -292,6 +332,7 @@ void RowOrColumn::addChild( boost::shared_ptr const & i_pChild, ++it; m_aElements.insert( it, WindowArranger::Element( NULL, i_pChild, i_nExpandPrio ) ); } + return nIndex; } void RowOrColumn::remove( Window* i_pWindow ) @@ -337,11 +378,7 @@ Indenter::~Indenter() Size Indenter::getOptimalSize( WindowSizeType i_eType ) const { - Size aSize( m_aElement.m_pElement - ? m_aElement.m_pElement->GetOptimalSize( i_eType ) - : m_aElement.m_pChild - ? m_aElement.m_pChild->getOptimalSize( i_eType ) - : Size() ); + Size aSize( m_aElement.getOptimalSize( i_eType ) ); aSize.Width() += 2*m_nOuterBorder + m_nIndent; aSize.Height() += 2*m_nOuterBorder; return aSize; @@ -419,11 +456,7 @@ Size MatrixArranger::getOptimalSize( WindowSizeType i_eType, std::vector& for( std::vector< MatrixElement >::const_iterator it = m_aElements.begin(); it != m_aElements.end(); ++it ) { - Size aSize; - if( it->m_pElement ) - aSize = it->m_pElement->GetOptimalSize( i_eType ); - else if( it->m_pChild ) - aSize = it->m_pChild->getOptimalSize( i_eType ); + Size aSize( it->getOptimalSize( i_eType ) ); if( aSize.Width() > o_rColumnWidths[ it->m_nX ] ) o_rColumnWidths[ it->m_nX ] = aSize.Width(); if( aSize.Height() > o_rRowHeights[ it->m_nY ] ) @@ -513,28 +546,14 @@ void MatrixArranger::setParentWindow( Window* i_pNewParent ) } } -boost::shared_ptr MatrixArranger::getChild( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pChild : boost::shared_ptr(); -} - -Window* MatrixArranger::getWindow( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].m_pElement : NULL; -} - -sal_Int32 MatrixArranger::getExpandPriority( size_t i_nIndex ) const -{ - return i_nIndex < m_aElements.size() ? m_aElements[i_nIndex].getExpandPriority() : 0; -} - -void MatrixArranger::addWindow( Window* i_pWindow, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) +size_t MatrixArranger::addWindow( Window* i_pWindow, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) { sal_uInt64 nMapValue = getMap( i_nX, i_nY ); std::map< sal_uInt64, size_t >::const_iterator it = m_aMatrixMap.find( nMapValue ); + size_t nIndex = 0; if( it == m_aMatrixMap.end() ) { - m_aMatrixMap[ nMapValue ] = m_aElements.size(); + m_aMatrixMap[ nMapValue ] = nIndex = m_aElements.size(); m_aElements.push_back( MatrixElement( i_pWindow, i_nX, i_nY, boost::shared_ptr(), i_nExpandPrio ) ); } else @@ -545,7 +564,9 @@ void MatrixArranger::addWindow( Window* i_pWindow, sal_uInt32 i_nX, sal_uInt32 i rEle.m_nExpandPriority = i_nExpandPrio; rEle.m_nX = i_nX; rEle.m_nY = i_nY; + nIndex = it->second; } + return nIndex; } void MatrixArranger::remove( Window* i_pWindow ) @@ -565,13 +586,14 @@ void MatrixArranger::remove( Window* i_pWindow ) } } -void MatrixArranger::addChild( boost::shared_ptr const &i_pChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) +size_t MatrixArranger::addChild( boost::shared_ptr const &i_pChild, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) { sal_uInt64 nMapValue = getMap( i_nX, i_nY ); std::map< sal_uInt64, size_t >::const_iterator it = m_aMatrixMap.find( nMapValue ); + size_t nIndex = 0; if( it == m_aMatrixMap.end() ) { - m_aMatrixMap[ nMapValue ] = m_aElements.size(); + m_aMatrixMap[ nMapValue ] = nIndex = m_aElements.size(); m_aElements.push_back( MatrixElement( NULL, i_nX, i_nY, i_pChild, i_nExpandPrio ) ); } else @@ -582,7 +604,9 @@ void MatrixArranger::addChild( boost::shared_ptr const &i_pChild rEle.m_nExpandPriority = i_nExpandPrio; rEle.m_nX = i_nX; rEle.m_nY = i_nY; + nIndex = it->second; } + return nIndex; } void MatrixArranger::remove( boost::shared_ptr const &i_pChild ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 09d2532fa812..cd9e8712abaf 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -61,32 +61,66 @@ using namespace com::sun::star::beans; #define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ) ) ) PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) - : Window( i_pParent, i_rId ), - mfScaleX( 1 ), - mfScaleY( 1 ) + : Window( i_pParent, i_rId ) + , maOrigSize( 10, 10 ) + , maPageVDev( *this ) { + SetPaintTransparent( TRUE ); + SetBackground(); + maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); } PrintDialog::PrintPreviewWindow::~PrintPreviewWindow() { } -void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) +void PrintDialog::PrintPreviewWindow::Resize() { - Window::Paint( i_rRect ); + Size aNewSize( GetSizePixel() ); + Size aScaledSize; + double fScale = 1.0; + if( maOrigSize.Width() > maOrigSize.Height() ) + { + aScaledSize = Size( aNewSize.Width(), aNewSize.Width() * maOrigSize.Height() / maOrigSize.Width() ); + if( aScaledSize.Height() > aNewSize.Height() ) + fScale = double(aNewSize.Height())/double(aScaledSize.Height()); + } + else + { + aScaledSize = Size( aNewSize.Height() * maOrigSize.Width() / maOrigSize.Height(), aNewSize.Height() ); + if( aScaledSize.Width() > aNewSize.Width() ) + fScale = double(aNewSize.Width())/double(aScaledSize.Width()); + } + aScaledSize.Width() = long(aScaledSize.Width()*fScale); + aScaledSize.Height() = long(aScaledSize.Height()*fScale); + maPageVDev.SetOutputSizePixel( aScaledSize, FALSE ); +} +void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) +{ GDIMetaFile aMtf( maMtf ); - SetFillColor( Color( COL_WHITE ) ); - SetLineColor(); - DrawRect( Rectangle( Point( 0, 0 ), GetSizePixel() )); - Push(); - SetMapMode( MAP_100TH_MM ); + Size aPreviewSize = maPageVDev.GetOutputSizePixel(); + Size aSize( GetSizePixel() ); + Point aOffset( (aSize.Width() - aPreviewSize.Width()) / 2, + (aSize.Height() - aPreviewSize.Height()) / 2 ); + + const Size aLogicSize( maPageVDev.PixelToLogic( aPreviewSize, MapMode( MAP_100TH_MM ) ) ); + double fScale = double(aLogicSize.Width())/double(maOrigSize.Width()); + + + maPageVDev.Erase(); + maPageVDev.Push(); + maPageVDev.SetMapMode( MAP_100TH_MM ); aMtf.WindStart(); - aMtf.Scale( mfScaleX, mfScaleY ); + aMtf.Scale( fScale, fScale ); aMtf.WindStart(); - aMtf.Play( this, Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ); - Pop(); + aMtf.Play( &maPageVDev, Point( 0, 0 ), aLogicSize ); + maPageVDev.Pop(); + + SetMapMode( MAP_PIXEL ); + maPageVDev.SetMapMode( MAP_PIXEL ); + DrawOutDev( aOffset, aPreviewSize, Point( 0, 0 ), aPreviewSize, maPageVDev ); } void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) @@ -109,16 +143,10 @@ void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) } } -void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview ) +void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview, const Size& i_rOrigSize ) { maMtf = i_rNewPreview; - Invalidate(); -} - -void PrintDialog::PrintPreviewWindow::setScale( double fScaleX, double fScaleY ) -{ - mfScaleX = fScaleX; - mfScaleY = fScaleY; + maOrigSize = i_rOrigSize; Invalidate(); } @@ -481,6 +509,7 @@ PrintDialog::OutputOptPage::OutputOptPage( Window* i_pParent, const ResId& i_rRe , maCollateSingleJobsBox( this, VclResId( SV_PRINT_OPT_SINGLEJOBS ) ) , maReverseOrderBox( this, VclResId( SV_PRINT_OPT_REVERSE ) ) { + FreeResource(); maOptionsLine.SMHID2( "OptPage", "Options" ); maToFileBox.SMHID2( "OptPage", "ToFile" ); maCollateSingleJobsBox.SMHID2( "OptPage", "SingleJobs" ); @@ -552,19 +581,16 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr xPreviewAndTab( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xPreviewAndTab, 5 ); + + // setup column for preview and sub controls + boost::shared_ptr< vcl::RowOrColumn > xPreview( new vcl::RowOrColumn( xPreviewAndTab.get() ) ); + xPreviewAndTab->addChild( xPreview, 5 ); + xPreview->addWindow( &maPreviewWindow, 5 ); + // get a row for the preview controls + boost::shared_ptr< vcl::RowOrColumn > xPreviewCtrls( new vcl::RowOrColumn( xPreview.get(), false ) ); + xPreview->addChild( xPreviewCtrls ); + xPreviewCtrls->addWindow( &maPageEdit ); + xPreviewCtrls->addWindow( &maNumPagesText ); + boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); + xPreviewCtrls->addChild( xSpacer ); + xPreviewCtrls->addWindow( &maBackwardBtn ); + xPreviewCtrls->addWindow( &maForwardBtn ); + + // continue with the tab ctrl + xPreviewAndTab->addWindow( &maTabCtrl ); + + // add the button line + maLayout.addWindow( &maButtonLine ); + + // add the row for the buttons + boost::shared_ptr< vcl::RowOrColumn > xButtons( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xButtons ); + + // insert a spacer, buttons are right aligned + xSpacer.reset( new vcl::Spacer( xButtons.get(), 2 ) ); + xButtons->addChild( xSpacer ); + Size aMinSize( maCancelButton.GetSizePixel() ); + xButtons->setMinimumSize( xButtons->addWindow( &maOKButton ), aMinSize ); + xButtons->setMinimumSize( xButtons->addWindow( &maCancelButton ), aMinSize ); +} + void PrintDialog::readFromSettings() { maJobPage.readFromSettings(); @@ -723,6 +794,7 @@ void PrintDialog::readFromSettings() break; } } + maOKButton.SetText( maOptionsPage.maToFileBox.IsChecked() ? maPrintToFileText : maPrintText ); } void PrintDialog::storeToSettings() @@ -1222,6 +1294,7 @@ void PrintDialog::setupOptionalUI() // resize dialog if necessary Size aTabSize = maTabCtrl.GetTabPageSizePixel(); + maTabCtrl.SetMinimumSizePixel( maTabCtrl.GetSizePixel() ); if( aMaxSize.Height() > aTabSize.Height() || aMaxSize.Width() > aTabSize.Width() ) { Size aCurSize( GetSizePixel() ); @@ -1233,6 +1306,7 @@ void PrintDialog::setupOptionalUI() // and the tab ctrl needs more space, too aTabSize.Width() = aMaxSize.Width(); maTabCtrl.SetSizePixel( aTabSize ); + maTabCtrl.SetMinimumSizePixel( maTabCtrl.GetSizePixel() ); } SetSizePixel( aCurSize ); } @@ -1375,32 +1449,11 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) GDIMetaFile aMtf; if( nPages > 0 ) maCurPageSize = maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); + else + maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); - maPreviewWindow.setPreview( aMtf ); - } - // catch corner case of strange page size - if( maCurPageSize.Width() == 0 || maCurPageSize.Height() == 0 ) - maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); - - Size aPreviewSize; - Point aPreviewPos = maPreviewSpace.TopLeft(); - const long nW = maPreviewSpace.GetSize().Width(); - const long nH = maPreviewSpace.GetSize().Height(); - if( maCurPageSize.Width() > maCurPageSize.Height() ) - { - aPreviewSize = Size( nW, nW * maCurPageSize.Height() / maCurPageSize.Width() ); - aPreviewPos.Y() += (maPreviewSpace.GetHeight() - aPreviewSize.Height())/2; - } - else - { - aPreviewSize = Size( nH * maCurPageSize.Width() / maCurPageSize.Height(), nH ); - aPreviewPos.X() += (maPreviewSpace.GetWidth() - aPreviewSize.Width())/2; + maPreviewWindow.setPreview( aMtf, maCurPageSize ); } - - maPreviewWindow.SetPosSizePixel( aPreviewPos, aPreviewSize ); - const Size aLogicSize( maPreviewWindow.PixelToLogic( maPreviewWindow.GetSizePixel(), MapMode( MAP_100TH_MM ) ) ); - maPreviewWindow.setScale( double(aLogicSize.Width())/double(maCurPageSize.Width()), - double(aLogicSize.Height())/double(maCurPageSize.Height()) ); } void PrintDialog::updateNup() @@ -1459,6 +1512,11 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) { previewBackward(); } + else if( pButton == &maOptionsPage.maToFileBox ) + { + maOKButton.SetText( maOptionsPage.maToFileBox.IsChecked() ? maPrintToFileText : maPrintText ); + maLayout.resize(); + } else if( pButton == &maJobPage.maCollateBox ) { maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), @@ -1613,34 +1671,6 @@ IMPL_LINK( PrintDialog, UIOption_ModifyHdl, Edit*, i_pBox ) return 0; } -void PrintDialog::Paint( const Rectangle& i_rRect ) -{ - ModalDialog::Paint( i_rRect ); - - #if 0 - // sadly Tab panes are not a reliable choice for a grouping background - // since they depend on the tab items above in some themes - if( IsNativeControlSupported( CTRL_TAB_PANE, PART_ENTIRE_CONTROL) ) - { - Rectangle aPrevBg( maPreviewBackground ); - #ifdef QUARTZ - // FIXME: this interacts with vcl/aqua/source/gdi/salnativewidgets.cxx where - // some magic offsets are added to the area - aPrevBg.Top() += 10; - #endif - const ImplControlValue aControlValue( BUTTONVALUE_DONTKNOW, rtl::OUString(), 0 ); - - ControlState nState = CTRL_STATE_ENABLED; - Region aCtrlRegion( aPrevBg ); - DrawNativeControl( CTRL_TAB_PANE, PART_ENTIRE_CONTROL, aCtrlRegion, nState, - aControlValue, rtl::OUString() ); - } - #else - DecorationView aVw( this ); - aVw.DrawFrame( maPreviewBackground, FRAME_DRAW_IN ); - #endif -} - void PrintDialog::Command( const CommandEvent& rEvt ) { if( rEvt.GetCommand() == COMMAND_WHEEL ) @@ -1659,6 +1689,7 @@ void PrintDialog::Command( const CommandEvent& rEvt ) void PrintDialog::Resize() { + #if 0 Size aPixDiff( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); Size aWindowSize( GetOutputSizePixel() ); @@ -1705,6 +1736,9 @@ void PrintDialog::Resize() maPreviewBackground.Top() = aPixDiff.Height() - 2; maPreviewBackground.Right() = aPixDiff.Width() + nPreviewLength + 2; maPreviewBackground.Bottom() = maPreviewCtrlRow.getManagedArea().Bottom() + aPixDiff.Height(); + #else + maLayout.setManagedArea( Rectangle( Point( 0, 0 ), GetSizePixel() ) ); + #endif // and do the preview; however the metafile does not need to be gotten anew preparePreview( false ); -- cgit From 90854d1828ab03e7dbfca7214cd3aec140d8a9f3 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 25 Jul 2009 01:56:38 +0000 Subject: solve some rebase problems --- vcl/aqua/inc/salprn.h | 2 +- vcl/aqua/source/gdi/salprn.cxx | 19 +++++++++---------- vcl/inc/vcl/arrange.hxx | 2 +- vcl/source/window/printdlg.cxx | 2 +- 4 files changed, 12 insertions(+), 13 deletions(-) diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index e265f800906d..a572641dd59e 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -120,7 +120,7 @@ class AquaSalInfoPrinter : public SalInfoPrinter sal_Int32 getCurPageRangeCount() const { return mnCurPageRangeCount; } // match width/height against known paper formats, possibly switching orientation - const vcl::PaperInfo* matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const; + const PaperInfo* matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const; void setPaperSize( long i_nWidth, long i_nHeight, Orientation i_eSetOrientation ); private: diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 601adb3aa9b5..7a5b0c7ba483 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -128,6 +128,7 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const long nDPIX = 720, nDPIY = 720; NSSize aPaperSize = [mpPrintInfo paperSize]; + NSRect aImageRect = [mpPrintInfo imageablePageBounds]; if( mePageOrientation == ORIENTATION_PORTRAIT ) { // move mirrored CTM back into paper @@ -303,11 +304,11 @@ void AquaSalInfoPrinter::setPaperSize( long i_nWidth, long i_nHeight, Orientatio { Orientation ePaperOrientation = ORIENTATION_PORTRAIT; - const vcl::PaperInfo* pPaper = matchPaper( (i_nWidth+50)/100, (i_nHeight+50)/100, ePaperOrientation ); + const PaperInfo* pPaper = matchPaper( (i_nWidth+50)/100, (i_nHeight+50)/100, ePaperOrientation ); if( pPaper ) { - NSString* pPaperName = [CreateNSString( pPaper->m_aPaperName ) autorelease]; + NSString* pPaperName = [CreateNSString( rtl::OStringToOUString(PaperInfo::toPSName(pPaper->getPaper()), RTL_TEXTENCODING_ASCII_US) ) autorelease]; [mpPrintInfo setPaperName: pPaperName]; } else if( i_nWidth > 0 && i_nHeight > 0 ) @@ -809,10 +810,8 @@ void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) NSSize aPaperSize = [mpPrinter pageSizeForPaper: pPaper]; if( aPaperSize.width > 0 && aPaperSize.height > 0 ) { - vcl::PaperInfo aInfo; - aInfo.m_aPaperName = GetOUString( pPaper ); - aInfo.m_nPaperWidth = (PtTo10Mu( aPaperSize.width ) + 50 ) / 100; - aInfo.m_nPaperHeight = (PtTo10Mu( aPaperSize.height ) + 50 ) / 100; + PaperInfo aInfo( (PtTo10Mu( aPaperSize.width ) + 50 ) / 100, + (PtTo10Mu( aPaperSize.height ) + 50 ) / 100 ); m_aPaperFormats.push_back( aInfo ); } } @@ -821,19 +820,19 @@ void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) } } -const vcl::PaperInfo* AquaSalInfoPrinter::matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const +const PaperInfo* AquaSalInfoPrinter::matchPaper( long i_nWidth, long i_nHeight, Orientation& o_rOrientation ) const { if( ! m_bPapersInit ) const_cast(this)->InitPaperFormats( NULL ); - const vcl::PaperInfo* pMatch = NULL; + const PaperInfo* pMatch = NULL; o_rOrientation = ORIENTATION_PORTRAIT; for( int n = 0; n < 2 ; n++ ) { for( size_t i = 0; i < m_aPaperFormats.size(); i++ ) { - if( abs( m_aPaperFormats[i].m_nPaperWidth - i_nWidth ) < 2 && - abs( m_aPaperFormats[i].m_nPaperHeight - i_nHeight ) < 2 ) + if( abs( m_aPaperFormats[i].getWidth() - i_nWidth ) < 2 && + abs( m_aPaperFormats[i].getHeight() - i_nHeight ) < 2 ) { pMatch = &m_aPaperFormats[i]; return pMatch; diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index febbe69491a2..54727d24755b 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -87,7 +87,7 @@ namespace vcl Rectangle m_aManagedArea; long m_nOuterBorder; - virtual Element* getElement( size_t i_nIndex ) = NULL; + virtual Element* getElement( size_t i_nIndex ) = 0; const Element* getConstElement( size_t i_nIndex ) const { return const_cast(this)->getElement( i_nIndex ); } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index cd9e8712abaf..3022151e4425 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -96,7 +96,7 @@ void PrintDialog::PrintPreviewWindow::Resize() maPageVDev.SetOutputSizePixel( aScaledSize, FALSE ); } -void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& i_rRect ) +void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& ) { GDIMetaFile aMtf( maMtf ); -- cgit From efe311f79e12853753d50ffaf73630dfc88c1c09 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 27 Jul 2009 17:10:15 +0000 Subject: #i92518# adapting new UX spec --- vcl/inc/vcl/prndlg.hxx | 48 +++--- vcl/inc/vcl/svids.hrc | 44 +++-- vcl/source/src/print.src | 184 +++++++++----------- vcl/source/window/printdlg.cxx | 371 +++++++++++++++++++++-------------------- 4 files changed, 314 insertions(+), 333 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 03ecdfc79979..6a8974ccb966 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -74,30 +74,30 @@ namespace vcl { public: FixedLine maNupLine; - FixedText maNupRowsTxt; - NumericField maNupRowsEdt; - FixedText maNupColTxt; + FixedText maNupPagesTxt; + ListBox maNupPagesBox; + + // controls for "Custom" page mode + FixedText maNupNumPagesTxt; NumericField maNupColEdt; - FixedText maNupRepTxt; - NumericField maNupRepEdt; + FixedText maNupTimesTxt; + NumericField maNupRowsEdt; + FixedText maPageMarginTxt; + MetricField maPageMarginEdt; + FixedText maSheetMarginTxt; + MetricField maSheetMarginEdt; + FixedText maNupOrientationTxt; + ListBox maNupOrientationBox; + + // page order ("left to right, then down") + FixedText maNupOrderTxt; + ListBox maNupOrderBox; + // border around each page CheckBox maBorderCB; - RadioButton maNupPortrait; - RadioButton maNupLandscape; - - FixedLine maMargins; - FixedText maLeftMarginTxt; - MetricField maLeftMarginEdt; - FixedText maRightMarginTxt; - MetricField maRightMarginEdt; - FixedText maTopMarginTxt; - MetricField maTopMarginEdt; - FixedText maBottomMarginTxt; - MetricField maBottomMarginEdt; - - FixedText maHSpaceTxt; - MetricField maHSpaceEdt; - FixedText maVSpaceTxt; - MetricField maVSpaceEdt; + + vcl::RowOrColumn maLayout; + + void setupLayout(); NUpTabPage( Window*, const ResId& ); virtual ~NUpTabPage(); @@ -203,11 +203,15 @@ namespace vcl Size maNupPortraitSize; Size maNupLandscapeSize; + // internal, used for automatic Nup-Portrait/landscape + Size maFirstPageSize; + rtl::OUString maPrintToFileText; rtl::OUString maPrintText; vcl::RowOrColumn maLayout; + Size getJobPageSize(); void updateNup(); void preparePreview( bool i_bPrintChanged = true, bool i_bMayUseCache = false ); void setPreviewText( sal_Int32 ); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 681017107a1b..ed7f16cfb17c 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -90,29 +90,27 @@ #define SV_PRINT_TOFILE_TXT 13 #define SV_PRINT_TAB_NUP 1 -#define SV_PRINT_PRT_NUP 1 -#define SV_PRINT_PRT_NUP_ROWS_TXT 2 -#define SV_PRINT_PRT_NUP_ROWS_EDT 3 -#define SV_PRINT_PRT_NUP_COLUMNS_TXT 4 -#define SV_PRINT_PRT_NUP_COLUMNS_EDT 5 -#define SV_PRINT_PRT_NUP_PORTRAIT 6 -#define SV_PRINT_PRT_NUP_LANDSCAPE 7 -#define SV_PRINT_PRT_NUP_MARGINS_FL 8 -#define SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT 9 -#define SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT 10 -#define SV_PRINT_PRT_NUP_MARGINS_TOP_TXT 11 -#define SV_PRINT_PRT_NUP_MARGINS_TOP_EDT 12 -#define SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT 13 -#define SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT 14 -#define SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT 15 -#define SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT 16 -#define SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT 17 -#define SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT 18 -#define SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT 19 -#define SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT 20 -#define SV_PRINT_PRT_NUP_BORDER_CB 21 -#define SV_PRINT_PRT_NUP_PAGEREPEAT_TXT 22 -#define SV_PRINT_PRT_NUP_PAGEREPEAT_EDT 23 +#define SV_PRINT_PRT_NUP_LAYOUT_FL 1 +#define SV_PRINT_PRT_NUP_PAGES_TXT 2 +#define SV_PRINT_PRT_NUP_PAGES_BOX 2 +#define SV_PRINT_PRT_NUP_NUM_PAGES_TXT 3 +#define SV_PRINT_PRT_NUP_COLS_EDT 4 +#define SV_PRINT_PRT_NUP_TIMES_TXT 5 +#define SV_PRINT_PRT_NUP_ROWS_EDT 6 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT 7 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT 8 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT 9 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT 10 +#define SV_PRINT_PRT_NUP_ORIENTATION_TXT 12 +#define SV_PRINT_PRT_NUP_ORIENTATION_BOX 13 +#define SV_PRINT_PRT_NUP_ORDER_TXT 14 +#define SV_PRINT_PRT_NUP_ORDER_BOX 15 +#define SV_PRINT_PRT_NUP_BORDER_CB 16 + +#define SV_PRINT_PRT_NUP_ORIENTATION_AUTOMATIC 0 +#define SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT 1 +#define SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE 2 + #define SV_PRINT_TAB_JOB 2 #define SV_PRINT_PRINTERS_FL 1 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index eb7ae8966d82..600a690ef23d 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -110,19 +110,43 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "Page Layout"; Hide = TRUE; - FixedLine SV_PRINT_PRT_NUP + FixedLine SV_PRINT_PRT_NUP_LAYOUT_FL { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 150, 10 ); - Text [en-US] = "N-Up printing"; + Text [en-US] = "Layout"; }; - FixedText SV_PRINT_PRT_NUP_ROWS_TXT + FixedText SV_PRINT_PRT_NUP_PAGES_TXT { Pos = MAP_APPFONT( 10, 20 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Rows"; + Text [en-US] = "Pages per ~sheet"; }; - NumericField SV_PRINT_PRT_NUP_ROWS_EDT + ListBox SV_PRINT_PRT_NUP_PAGES_BOX + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 80 ); + Border = TRUE; + DropDown = TRUE; + CurPos = 0; + StringList [en-US] = + { + < "1"; 1; >; + < "2"; 2; >; + < "4"; 4; >; + < "6"; 6; >; + < "9"; 9; >; + < "16"; 16; >; + < "Custom"; 0xffff; >; + }; + }; + FixedText SV_PRINT_PRT_NUP_NUM_PAGES_TXT + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "P~ages"; + }; + NumericField SV_PRINT_PRT_NUP_COLS_EDT { Pos = MAP_APPFONT( 55, 20 ); Size = MAP_APPFONT( 40, 12 ); @@ -132,13 +156,13 @@ ModalDialog SV_DLG_PRINT Maximum = 32; Value = 1; }; - FixedText SV_PRINT_PRT_NUP_COLUMNS_TXT + FixedText SV_PRINT_PRT_NUP_TIMES_TXT { Pos = MAP_APPFONT( 10, 35 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "C~olumns"; + Text [en-US] = "~by"; }; - NumericField SV_PRINT_PRT_NUP_COLUMNS_EDT + NumericField SV_PRINT_PRT_NUP_ROWS_EDT { Pos = MAP_APPFONT( 55, 35 ); Size = MAP_APPFONT( 40, 12 ); @@ -148,53 +172,13 @@ ModalDialog SV_DLG_PRINT Maximum = 32; Value = 1; }; - FixedText SV_PRINT_PRT_NUP_PAGEREPEAT_TXT - { - Pos = MAP_APPFONT( 10, 50 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Repeat"; - }; - NumericField SV_PRINT_PRT_NUP_PAGEREPEAT_EDT - { - Pos = MAP_APPFONT( 55, 50 ); - Size = MAP_APPFONT( 40, 12 ); - Border = TRUE; - Spin = TRUE; - Minimum = 1; - Maximum = 32; - Value = 1; - }; - CheckBox SV_PRINT_PRT_NUP_BORDER_CB - { - Pos = MAP_APPFONT( 10, 65 ); - Size = MAP_APPFONT( 150, 12 ); - Text [en-US] = "~Draw a Border around each page"; - }; - RadioButton SV_PRINT_PRT_NUP_PORTRAIT - { - Pos = MAP_APPFONT( 110, 20 ); - Size = MAP_APPFONT( 90, 10 ); - Text [en-US] = "Po~rtrait"; - }; - RadioButton SV_PRINT_PRT_NUP_LANDSCAPE - { - Pos = MAP_APPFONT( 110, 30 ); - Size = MAP_APPFONT( 90, 10 ); - Text [en-US] = "~Landscape"; - }; - FixedLine SV_PRINT_PRT_NUP_MARGINS_FL - { - Pos = MAP_APPFONT( 5, 80 ); - Size = MAP_APPFONT( 150, 10 ); - Text [en-US] = "Margins"; - }; - FixedText SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT + FixedText SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT { Pos = MAP_APPFONT( 10, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Left"; + Text [en-US] = "~Margin between pages"; }; - MetricField SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT + MetricField SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT { Pos = MAP_APPFONT( 55, 95 ); Size = MAP_APPFONT( 40, 12 ); @@ -203,13 +187,13 @@ ModalDialog SV_DLG_PRINT Value = 0; Unit = FUNIT_MM; }; - FixedText SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT + FixedText SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT { Pos = MAP_APPFONT( 110, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Right"; + Text [en-US] = "Ma~rgin to sheet border"; }; - MetricField SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT + MetricField SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT { Pos = MAP_APPFONT( 155, 95 ); Size = MAP_APPFONT( 40, 12 ); @@ -218,66 +202,50 @@ ModalDialog SV_DLG_PRINT Value = 0; Unit = FUNIT_MM; }; - FixedText SV_PRINT_PRT_NUP_MARGINS_TOP_TXT - { - Pos = MAP_APPFONT( 10, 110 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Top"; - }; - MetricField SV_PRINT_PRT_NUP_MARGINS_TOP_EDT - { - Pos = MAP_APPFONT( 55, 110 ); - Size = MAP_APPFONT( 40, 12 ); - Spin = TRUE; - Border = TRUE; - Value = 0; - Unit = FUNIT_MM; - }; - FixedText SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT + FixedText SV_PRINT_PRT_NUP_ORIENTATION_TXT { - Pos = MAP_APPFONT( 110, 110 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Bottom"; + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "~Orientation"; }; - MetricField SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT + ListBox SV_PRINT_PRT_NUP_ORIENTATION_BOX { - Pos = MAP_APPFONT( 155, 110 ); - Size = MAP_APPFONT( 40, 12 ); - Spin = TRUE; + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 40 ); Border = TRUE; - Value = 0; - Unit = FUNIT_MM; - }; - - FixedText SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT - { - Pos = MAP_APPFONT( 10, 130 ); - Size = MAP_APPFONT( 80, 10 ); - Text [en-US] = "~Horizontal spacing"; - }; - MetricField SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT - { - Pos = MAP_APPFONT( 95, 130 ); - Size = MAP_APPFONT( 40, 12 ); - Spin = TRUE; + DropDown = TRUE; + CurPos = 0; + StringList [en-US] = + { + < "Automatic"; SV_PRINT_PRT_NUP_ORIENTATION_AUTOMATIC; >; + < "Portrait"; SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT; >; + < "Landscape"; SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE; >; + }; + }; + FixedText SV_PRINT_PRT_NUP_ORDER_TXT + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "Order"; + }; + ListBox SV_PRINT_PRT_NUP_ORDER_BOX + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 20 ); + DropDown = TRUE; Border = TRUE; - Value = 0; - Unit = FUNIT_MM; + CurPos = 0; + StringList [en-US] = + { + < "left to right, then down"; 1; >; + < "top to bottom, then right"; 2; >; + }; }; - FixedText SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT - { - Pos = MAP_APPFONT( 10, 145 ); - Size = MAP_APPFONT( 80, 10 ); - Text [en-US] = "~Vertical spacing"; - }; - MetricField SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT + CheckBox SV_PRINT_PRT_NUP_BORDER_CB { - Pos = MAP_APPFONT( 95, 145 ); - Size = MAP_APPFONT( 40, 12 ); - Spin = TRUE; - Border = TRUE; - Value = 0; - Unit = FUNIT_MM; + Pos = MAP_APPFONT( 10, 65 ); + Size = MAP_APPFONT( 150, 12 ); + Text [en-US] = "~Draw a Border around each page"; }; }; @@ -382,7 +350,7 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "Options"; Hide = TRUE; - FixedLine SV_PRINT_PRT_NUP + FixedLine SV_PRINT_OPT_PRINT_FL { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 150, 10 ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 3022151e4425..dd618766451c 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -147,39 +147,33 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi { maMtf = i_rNewPreview; maOrigSize = i_rOrigSize; + Resize(); Invalidate(); } PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) - , maNupLine( this, VclResId( SV_PRINT_PRT_NUP ) ) - , maNupRowsTxt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_TXT ) ) + , maNupLine( this, VclResId( SV_PRINT_PRT_NUP_LAYOUT_FL ) ) + , maNupPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_PAGES_TXT ) ) + , maNupPagesBox( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BOX ) ) + , maNupNumPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_NUM_PAGES_TXT ) ) + , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLS_EDT ) ) + , maNupTimesTxt( this, VclResId( SV_PRINT_PRT_NUP_TIMES_TXT ) ) , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) - , maNupColTxt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_TXT ) ) - , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLUMNS_EDT ) ) - , maNupRepTxt( this, VclResId( SV_PRINT_PRT_NUP_PAGEREPEAT_TXT ) ) - , maNupRepEdt( this, VclResId( SV_PRINT_PRT_NUP_PAGEREPEAT_EDT ) ) + , maPageMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT ) ) + , maPageMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT ) ) + , maSheetMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT ) ) + , maSheetMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT ) ) + , maNupOrientationTxt( this, VclResId( SV_PRINT_PRT_NUP_ORIENTATION_TXT ) ) + , maNupOrientationBox( this, VclResId( SV_PRINT_PRT_NUP_ORIENTATION_BOX ) ) + , maNupOrderTxt( this, VclResId( SV_PRINT_PRT_NUP_ORDER_TXT ) ) + , maNupOrderBox( this, VclResId( SV_PRINT_PRT_NUP_ORDER_BOX ) ) , maBorderCB( this, VclResId( SV_PRINT_PRT_NUP_BORDER_CB ) ) - , maNupPortrait( this, VclResId( SV_PRINT_PRT_NUP_PORTRAIT ) ) - , maNupLandscape( this, VclResId( SV_PRINT_PRT_NUP_LANDSCAPE ) ) - , maMargins( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_FL ) ) - , maLeftMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_LEFT_TXT ) ) - , maLeftMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_LEFT_EDT) ) - , maRightMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_RIGHT_TXT ) ) - , maRightMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_RIGHT_EDT ) ) - , maTopMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_TOP_TXT ) ) - , maTopMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_TOP_EDT ) ) - , maBottomMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_BOTTOM_TXT ) ) - , maBottomMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_BOTTOM_EDT ) ) - , maHSpaceTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_HSPACE_TXT ) ) - , maHSpaceEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_HSPACE_EDT ) ) - , maVSpaceTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_VSPACE_TXT ) ) - , maVSpaceEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_VSPACE_EDT ) ) { FreeResource(); // setup field units for metric fields - const LocaleDataWrapper& rLocWrap( maLeftMarginEdt.GetLocaleDataWrapper() ); + const LocaleDataWrapper& rLocWrap( maPageMarginEdt.GetLocaleDataWrapper() ); FieldUnit eUnit = FUNIT_MM; USHORT nDigits = 0; if( rLocWrap.getMeasurementSystemEnum() == MEASURE_US ) @@ -188,162 +182,105 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) nDigits = 2; } // set units - maLeftMarginEdt.SetUnit( eUnit ); - maTopMarginEdt.SetUnit( eUnit ); - maRightMarginEdt.SetUnit( eUnit ); - maBottomMarginEdt.SetUnit( eUnit ); - maHSpaceEdt.SetUnit( eUnit ); - maVSpaceEdt.SetUnit( eUnit ); + maPageMarginEdt.SetUnit( eUnit ); + maSheetMarginEdt.SetUnit( eUnit ); // set precision - maLeftMarginEdt.SetDecimalDigits( nDigits ); - maTopMarginEdt.SetDecimalDigits( nDigits ); - maRightMarginEdt.SetDecimalDigits( nDigits ); - maBottomMarginEdt.SetDecimalDigits( nDigits ); - maHSpaceEdt.SetDecimalDigits( nDigits ); - maVSpaceEdt.SetDecimalDigits( nDigits ); - - maNupLine.SMHID2( "NUpPage", "NUPline" ); - maNupRowsTxt.SMHID2( "NUpPage", "NUPRowsText" ); - maNupRowsEdt.SMHID2( "NUpPage", "NUPRows" ); - maNupColTxt.SMHID2( "NUpPage", "NUPColumnsText" ); - maNupColEdt.SMHID2( "NUpPage", "NUPColumns" ); - maNupRepTxt.SMHID2( "NUpPage", "NUPRepeatText" ); - maNupRepEdt.SMHID2( "NUpPage", "NUPRepeat" ); - maNupPortrait.SMHID2( "NUpPage", "NUPPortrait" ); - maNupLandscape.SMHID2( "NUpPage", "NUPLandscape" ); - maBorderCB.SMHID2( "NUpPage", "NUPBorder" ); - maMargins.SMHID2( "NUpPage", "NUPMargins" ); - maLeftMarginTxt.SMHID2( "NUpPage", "NUPLeftText" ); - maLeftMarginEdt.SMHID2( "NUpPage", "NUPLeft" ); - maTopMarginTxt.SMHID2( "NUpPage", "NUPTopText" ); - maTopMarginEdt.SMHID2( "NUpPage", "NUPTop" ); - maRightMarginTxt.SMHID2( "NUpPage", "NUPRightText" ); - maRightMarginEdt.SMHID2( "NUpPage", "NUPRight" ); - maBottomMarginTxt.SMHID2( "NUpPage", "NUPBottomText" ); - maBottomMarginEdt.SMHID2( "NUpPage", "NUPBottom" ); - maHSpaceTxt.SMHID2( "NUpPage", "NUPHSpaceText" ); - maHSpaceEdt.SMHID2( "NUpPage", "NUPHSpace" ); - maVSpaceTxt.SMHID2( "NUpPage", "NUPVSpaceText" ); - maVSpaceEdt.SMHID2( "NUpPage", "NUPVSpace" ); + maPageMarginEdt.SetDecimalDigits( nDigits ); + maSheetMarginEdt.SetDecimalDigits( nDigits ); + + maNupLine.SMHID2("NUpPage", "Layout"); + maNupPagesTxt.SMHID2( "NUpPage", "PagesPerSheet" ); + maNupPagesBox.SMHID2( "NUpPage", "PagesPerSheetBox" ); + maNupNumPagesTxt.SMHID2( "NUpPage", "Columns" ); + maNupColEdt.SMHID2( "NUpPage", "ColumnsBox" ); + maNupTimesTxt.SMHID2( "NUpPage", "Rows" ); + maNupRowsEdt.SMHID2( "NUpPage", "RowsBox" ); + maPageMarginTxt.SMHID2( "NUpPage", "PageMargin" ); + maPageMarginEdt.SMHID2( "NUpPage", "PageMarginBox" ); + maSheetMarginTxt.SMHID2( "NUpPage", "SheetMargin" ); + maSheetMarginEdt.SMHID2( "NUpPage", "SheetMarginBox" ); + maNupOrientationTxt.SMHID2( "NUpPage", "Orientation" ); + maNupOrientationBox.SMHID2( "NUpPage", "OrientationBox" ); + maNupOrderTxt.SMHID2( "NUpPage", "Order" ); + maNupOrderBox.SMHID2( "NUpPage", "OrderBox" ); + maBorderCB.SMHID2( "NUpPage", "BorderBox" ); + + setupLayout(); } PrintDialog::NUpTabPage::~NUpTabPage() { } -void PrintDialog::NUpTabPage::Resize() +void PrintDialog::NUpTabPage::setupLayout() { Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); - boost::shared_ptr aPage( new vcl::RowOrColumn() ); - aPage->setParentWindow( this ); - aPage->setOuterBorder( aBorder.Width() ); - aPage->addWindow( &maNupLine ); - - boost::shared_ptr aNupIndent( new vcl::Indenter( aPage.get(), aBorder.Width() ) ); - aPage->addChild( aNupIndent ); - boost::shared_ptr aNupColumn( new vcl::RowOrColumn( aNupIndent.get() ) ); - aNupIndent->setChild( aNupColumn ); - - boost::shared_ptr aNupRow( new vcl::RowOrColumn( aNupColumn.get(), false ) ); - aNupColumn->addChild( aNupRow ); - boost::shared_ptr aNupMat( new vcl::MatrixArranger( aNupRow.get(), aBorder.Width(), aBorder.Height() ) ); - aNupRow->addChild( aNupMat ); - aNupMat->addWindow( &maNupRowsTxt, 0, 0 ); - aNupMat->addWindow( &maNupRowsEdt, 1, 0 ); - aNupMat->addWindow( &maNupColTxt, 0, 1 ); - aNupMat->addWindow( &maNupColEdt, 1, 1 ); - aNupMat->addWindow( &maNupRepTxt, 0, 2 ); - aNupMat->addWindow( &maNupRepEdt, 1, 2 ); - boost::shared_ptr aOriCol( new vcl::RowOrColumn( aNupRow.get() ) ); - aNupRow->addChild( aOriCol ); - aOriCol->addWindow( &maNupPortrait ); - aOriCol->addWindow( &maNupLandscape ); - - aNupColumn->addWindow( &maBorderCB ); - - aPage->addWindow( &maMargins ); - - boost::shared_ptr aMargIndent( new vcl::Indenter( aPage.get(), aBorder.Width() ) ); - aPage->addChild( aMargIndent ); - boost::shared_ptr aMargColumn( new vcl::RowOrColumn( aMargIndent.get(), true, 2*aBorder.Height() ) ); - aMargIndent->setChild( aMargColumn ); - - boost::shared_ptr aMargMat( new vcl::MatrixArranger( aMargIndent.get(), aBorder.Width(), aBorder.Height() ) ); - aMargColumn->addChild( aMargMat ); - aMargMat->addWindow( &maLeftMarginTxt, 0, 0 ); - aMargMat->addWindow( &maLeftMarginEdt, 1, 0 ); - aMargMat->addWindow( &maRightMarginTxt, 3, 0 ); - aMargMat->addWindow( &maRightMarginEdt, 4, 0 ); - aMargMat->addWindow( &maTopMarginTxt, 0, 1 ); - aMargMat->addWindow( &maTopMarginEdt, 1, 1 ); - aMargMat->addWindow( &maBottomMarginTxt, 3, 1 ); - aMargMat->addWindow( &maBottomMarginEdt, 4, 1 ); - - boost::shared_ptr aSpacingMat( new vcl::MatrixArranger( aPage.get(), aBorder.Width(), aBorder.Height() ) ); - aMargColumn->addChild( aSpacingMat ); - aSpacingMat->addWindow( &maHSpaceTxt, 0, 0 ); - aSpacingMat->addWindow( &maHSpaceEdt, 1, 0 ); - aSpacingMat->addWindow( &maVSpaceTxt, 0, 1 ); - aSpacingMat->addWindow( &maVSpaceEdt, 1, 1 ); - - aPage->setManagedArea( Rectangle( Point(), GetOutputSizePixel() ) ); + maLayout.setParentWindow( this ); + maLayout.setOuterBorder( aBorder.Width() ); + + maLayout.addWindow( &maNupLine ); + boost::shared_ptr< vcl::RowOrColumn > xRow( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xRow ); + xRow->addWindow( &maNupPagesTxt ); + xRow->addWindow( &maNupPagesBox ); + + boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( &maLayout ) ); + maLayout.addChild( xIndent ); + boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); + xIndent->setChild( xCol ); + + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); + xRow->addWindow( &maNupNumPagesTxt ); + xRow->addWindow( &maNupColEdt ); + xRow->addWindow( &maNupTimesTxt ); + xRow->addWindow( &maNupRowsEdt ); + + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); + xRow->addWindow( &maPageMarginTxt ); + xRow->addWindow( &maPageMarginEdt ); + + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); + xRow->addWindow( &maSheetMarginTxt ); + xRow->addWindow( &maSheetMarginEdt ); + + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); + xRow->addWindow( &maNupOrientationTxt ); + xRow->addWindow( &maNupOrientationBox ); + + xRow.reset( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xRow ); + xRow->addWindow( &maNupOrderTxt ); + xRow->addWindow( &maNupOrderBox ); + + maLayout.addWindow( &maBorderCB ); +} + +void PrintDialog::NUpTabPage::Resize() +{ + maLayout.setManagedArea( Rectangle( Point( 0, 0 ), GetOutputSizePixel() ) ); } void PrintDialog::NUpTabPage::initFromMultiPageSetup( const vcl::PrinterController::MultiPageSetup& i_rMPS ) { - maLeftMarginEdt.SetValue( maLeftMarginEdt.Normalize( i_rMPS.nLeftMargin ), FUNIT_100TH_MM ); - maTopMarginEdt.SetValue( maTopMarginEdt.Normalize( i_rMPS.nTopMargin ), FUNIT_100TH_MM ); - maRightMarginEdt.SetValue( maRightMarginEdt.Normalize( i_rMPS.nRightMargin ), FUNIT_100TH_MM ); - maBottomMarginEdt.SetValue( maBottomMarginEdt.Normalize( i_rMPS.nBottomMargin ), FUNIT_100TH_MM ); - maHSpaceEdt.SetValue( maHSpaceEdt.Normalize( i_rMPS.nHorizontalSpacing ), FUNIT_100TH_MM ); - maVSpaceEdt.SetValue( maVSpaceEdt.Normalize( i_rMPS.nVerticalSpacing ), FUNIT_100TH_MM ); + maSheetMarginEdt.SetValue( maSheetMarginEdt.Normalize( i_rMPS.nLeftMargin ), FUNIT_100TH_MM ); + maPageMarginEdt.SetValue( maPageMarginEdt.Normalize( i_rMPS.nHorizontalSpacing ), FUNIT_100TH_MM ); maBorderCB.Check( i_rMPS.bDrawBorder ); maNupRowsEdt.SetValue( i_rMPS.nRows ); maNupColEdt.SetValue( i_rMPS.nColumns ); - maNupRepEdt.SetValue( i_rMPS.nRepeat ); } void PrintDialog::NUpTabPage::readFromSettings() { - #if 0 - SettingsConfigItem* pItem = SettingsConfigItem::get(); - rtl::OUString aValue; - - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ) ); - sal_Int32 nVal = aValue.toInt32(); - maNupRowsEdt.SetValue( sal_Int64( nVal > 1 ? nVal : 1) ); - - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ) ); - nVal = aValue.toInt32(); - maNupColEdt.SetValue( sal_Int64(nVal > 1 ? nVal : 1) ); - - aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ) ); - if( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ) - maNupPortrait.Check(); - else - maNupLandscape.Check(); - #endif } void PrintDialog::NUpTabPage::storeToSettings() { - #if 0 - SettingsConfigItem* pItem = SettingsConfigItem::get(); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Rows" ) ), - maNupRowsEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Columns" ) ), - maNupColEdt.GetText() ); - pItem->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), - rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NUp-Portrait" ) ), - rtl::OUString::createFromAscii( maNupPortrait.IsChecked() ? "true" : "false" ) ); - #endif } PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) @@ -650,13 +587,11 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetMultipage() ); @@ -670,8 +605,6 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetPageCount() > 0 ) + maFirstPageSize = maPController->getPageFile( 0, aMtf, true ); + } + return maFirstPageSize; +} + void PrintDialog::updateNup() { - int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); - int nCols = int(maNUpPage.maNupColEdt.GetValue()); - int nRepeat = int(maNUpPage.maNupRepEdt.GetValue()); + int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); + int nCols = int(maNUpPage.maNupColEdt.GetValue()); + long nPageMargin = long(maNUpPage.maPageMarginEdt.Denormalize(maNUpPage.maPageMarginEdt.GetValue( FUNIT_100TH_MM ))); + long nSheetMargin = long(maNUpPage.maSheetMarginEdt.Denormalize(maNUpPage.maSheetMarginEdt.GetValue( FUNIT_100TH_MM ))); PrinterController::MultiPageSetup aMPS; aMPS.nRows = nRows; aMPS.nColumns = nCols; - aMPS.nRepeat = nRepeat; - aMPS.aPaperSize = maNUpPage.maNupPortrait.IsChecked() - ? maNupPortraitSize : maNupLandscapeSize; - aMPS.nLeftMargin = long(maNUpPage.maLeftMarginEdt.Denormalize(maNUpPage.maLeftMarginEdt.GetValue( FUNIT_100TH_MM ))); - aMPS.nTopMargin = long(maNUpPage.maTopMarginEdt.Denormalize(maNUpPage.maTopMarginEdt.GetValue( FUNIT_100TH_MM ))); - aMPS.nRightMargin = long(maNUpPage.maRightMarginEdt.Denormalize(maNUpPage.maRightMarginEdt.GetValue( FUNIT_100TH_MM ))); - aMPS.nBottomMargin = long(maNUpPage.maBottomMarginEdt.Denormalize(maNUpPage.maBottomMarginEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nRepeat = 1; + aMPS.nLeftMargin = + aMPS.nTopMargin = + aMPS.nRightMargin = + aMPS.nBottomMargin = nSheetMargin; - aMPS.nHorizontalSpacing = long(maNUpPage.maHSpaceEdt.Denormalize(maNUpPage.maHSpaceEdt.GetValue( FUNIT_100TH_MM ))); - aMPS.nVerticalSpacing = long(maNUpPage.maVSpaceEdt.Denormalize(maNUpPage.maVSpaceEdt.GetValue( FUNIT_100TH_MM ))); + aMPS.nHorizontalSpacing = + aMPS.nVerticalSpacing = nPageMargin; aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); + int nOrientationMode = int(maNUpPage.maNupOrientationBox.GetEntryData( + maNUpPage.maNupOrientationBox.GetSelectEntryPos() )); + if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE ) + { + aMPS.aPaperSize = maNupLandscapeSize; + } + else if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT ) + { + aMPS.aPaperSize = maNupPortraitSize; + } + else // automatic mode + { + // get size of first real page to see if it is portrait or landscape + // we assume same page sizes for all the pages for this + Size aPageSize = getJobPageSize(); + + Size aMultiSize( aPageSize.Width() * nCols, aPageSize.Height() * nRows ); + if( aMultiSize.Width() > aMultiSize.Height() ) // fits better on landscape + aMPS.aPaperSize = maNupLandscapeSize; + else + aMPS.aPaperSize = maNupPortraitSize; + } + maPController->setMultipage( aMPS ); preparePreview( true, true ); @@ -1494,6 +1461,52 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) // update text fields updatePrinterText(); } + else if( pBox == &maNUpPage.maNupOrientationBox ) + { + updateNup(); + } + else if( pBox == &maNUpPage.maNupPagesBox ) + { + long nPages = long(maNUpPage.maNupPagesBox.GetEntryData(maNUpPage.maNupPagesBox.GetSelectEntryPos())); + int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); + int nCols = int(maNUpPage.maNupColEdt.GetValue()); + bool bCustom = false; + + if( nPages == 1 ) + nRows = nCols = 1; + else if( nPages == 2 || nPages == 4 || nPages == 6 || nPages == 9 || nPages == 16 ) + { + Size aJobPageSize( getJobPageSize() ); + bool bPortrait = aJobPageSize.Width() < aJobPageSize.Height(); + if( nPages == 2 ) + { + if( bPortrait ) + nRows = 1, nCols = 2; + else + nRows = 2, nCols = 1; + } + else if( nPages == 4 ) + nRows = nCols = 2; + else if( nPages == 6 ) + { + if( bPortrait ) + nRows = 2, nCols = 3; + else + nRows = 3, nCols = 2; + } + else if( nPages == 9 ) + nRows = nCols = 3; + else if( nPages == 16 ) + nRows = nCols = 4; + } + else + bCustom = true; + + maNUpPage.maNupRowsEdt.SetValue( nRows ); + maNUpPage.maNupColEdt.SetValue( nCols ); + updateNup(); + } + return 0; } @@ -1530,7 +1543,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maPController->getPrinter()->Setup( this ); } checkControlDependencies(); - if( pButton == &maNUpPage.maNupPortrait || pButton == &maNUpPage.maNupLandscape || pButton == &maNUpPage.maBorderCB ) + if( pButton == &maNUpPage.maBorderCB ) updateNup(); } return 0; @@ -1539,10 +1552,8 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) { checkControlDependencies(); - if( pEdit == &maNUpPage.maNupRowsEdt || pEdit == &maNUpPage.maNupColEdt || pEdit == &maNUpPage.maNupRepEdt || - pEdit == &maNUpPage.maLeftMarginEdt || pEdit == &maNUpPage.maTopMarginEdt || - pEdit == &maNUpPage.maRightMarginEdt || pEdit == &maNUpPage.maBottomMarginEdt || - pEdit == &maNUpPage.maHSpaceEdt || pEdit == &maNUpPage.maVSpaceEdt + if( pEdit == &maNUpPage.maNupRowsEdt || pEdit == &maNUpPage.maNupColEdt || + pEdit == &maNUpPage.maSheetMarginEdt || pEdit == &maNUpPage.maPageMarginEdt ) { updateNup(); -- cgit From 93e111d0778d7555df7b5a01042183687595f872 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 27 Jul 2009 18:42:13 +0000 Subject: #i92518# adapting new UX spec --- vcl/inc/vcl/arrange.hxx | 5 +++++ vcl/inc/vcl/print.hxx | 4 ++-- vcl/inc/vcl/prndlg.hxx | 4 ++++ vcl/inc/vcl/svids.hrc | 2 ++ vcl/source/control/button.cxx | 7 +++++-- vcl/source/src/print.src | 11 ++++++++++ vcl/source/window/arrange.cxx | 44 ++++++++++++++++++++++++++++++++-------- vcl/source/window/printdlg.cxx | 46 +++++++++++++++++++++++++++++++++++++----- 8 files changed, 106 insertions(+), 17 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 54727d24755b..b4e32350d685 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -60,11 +60,13 @@ namespace vcl boost::shared_ptr m_pChild; sal_Int32 m_nExpandPriority; Size m_aMinSize; + bool m_bHidden; Element() : m_pElement( NULL ) , m_pChild() , m_nExpandPriority( 0 ) + , m_bHidden( false ) {} Element( Window* i_pWin, @@ -74,6 +76,7 @@ namespace vcl : m_pElement( i_pWin ) , m_pChild( i_pChild ) , m_nExpandPriority( i_nExpandPriority ) + , m_bHidden( false ) {} void deleteChild() { m_pChild.reset(); } @@ -147,6 +150,8 @@ namespace vcl return pEle != NULL; } + void show( bool i_bShow = true, bool i_bImmediateUpdate = true ); + void setManagedArea( const Rectangle& i_rArea ) { m_aManagedArea = i_rArea; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 0241168bba0a..a6563d2b75ed 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -419,8 +419,8 @@ public: MultiPageSetup() : nRows( 1 ), nColumns( 1 ), nRepeat( 1 ), aPaperSize( 21000, 29700 ) - , nLeftMargin( 0 ), nTopMargin( 0 ) - , nRightMargin( 0 ), nBottomMargin( 0 ) + , nLeftMargin( 500 ), nTopMargin( 500 ) + , nRightMargin( 500 ), nBottomMargin( 500 ) , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) , bDrawBorder( true ) { diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 6a8974ccb966..3f2fa7d3eb3b 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -96,6 +96,7 @@ namespace vcl CheckBox maBorderCB; vcl::RowOrColumn maLayout; + boost::shared_ptr< vcl::WindowArranger >mxAdvancedControls; void setupLayout(); @@ -114,6 +115,8 @@ namespace vcl public: FixedLine maPrinterFL; ListBox maPrinters; + PushButton maDetailsBtn; + FixedText maDetailsTxt; FixedText maStatusLabel; FixedText maStatusTxt; FixedText maLocationLabel; @@ -139,6 +142,7 @@ namespace vcl vcl::RowOrColumn maLayout; boost::shared_ptr mxPrintRange; + boost::shared_ptr mxDetails; JobTabPage( Window*, const ResId& ); virtual ~JobTabPage(); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index ed7f16cfb17c..9e24cffe48a1 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -135,6 +135,8 @@ #define SV_PRINT_STATUS_TXT 20 #define SV_PRINT_LOCATION_TXT 21 #define SV_PRINT_COMMENT_TXT 22 +#define SV_PRINT_DETAILS_BTN 23 +#define SV_PRINT_DETAILS_TXT 24 #define SV_PRINT_TAB_OPT 3 #define SV_PRINT_OPT_PRINT_FL 1 diff --git a/vcl/source/control/button.cxx b/vcl/source/control/button.cxx index 2e2342fc6fc8..852e7983ac06 100644 --- a/vcl/source/control/button.cxx +++ b/vcl/source/control/button.cxx @@ -1991,8 +1991,11 @@ Size PushButton::CalcMinimumSize( long nMaxWidth ) const } // cf. ImplDrawPushButton ... - aSize.Width() += 8; - aSize.Height() += 8; + if( (GetStyle() & WB_SMALLSTYLE) == 0 ) + { + aSize.Width() += 8; + aSize.Height() += 8; + } return CalcWindowSize( aSize ); } diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 600a690ef23d..63d5bc6047c5 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -266,6 +266,17 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 100, 80 ); Border = TRUE; }; + PushButton SV_PRINT_DETAILS_BTN + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 5, 5 ); + }; + FixedText SV_PRINT_DETAILS_TXT + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "Printer details"; + }; FixedText SV_PRINT_STATUS_TXT { Pos = MAP_APPFONT( 5, 5 ); diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 4f03706b4264..e392a1cc7d5e 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -53,6 +53,31 @@ void WindowArranger::setParent( WindowArranger* i_pParent ) setParentWindow( m_pParentWindow ); } +void WindowArranger::show( bool i_bShow, bool i_bImmediateUpdate ) +{ + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + Element* pEle = getElement( i ); + if( pEle ) // sanity check + { + pEle->m_bHidden = ! i_bShow; + if( pEle->m_pElement ) + pEle->m_pElement->Show( i_bShow ); + if( pEle->m_pChild.get() ) + pEle->m_pChild->show( i_bShow, false ); + } + } + if( i_bImmediateUpdate ) + { + // find the topmost parent + WindowArranger* pResize = this; + while( pResize->m_pParentArranger ) + pResize = pResize->m_pParentArranger; + pResize->resize(); + } +} + sal_Int32 WindowArranger::Element::getExpandPriority() const { sal_Int32 nPrio = m_nExpandPriority; @@ -72,14 +97,17 @@ sal_Int32 WindowArranger::Element::getExpandPriority() const Size WindowArranger::Element::getOptimalSize( WindowSizeType i_eType ) const { Size aResult; - if( m_pElement ) - aResult = m_pElement->GetOptimalSize( i_eType ); - else if( m_pChild ) - aResult = m_pChild->getOptimalSize( i_eType ); - if( aResult.Width() < m_aMinSize.Width() ) - aResult.Width() = m_aMinSize.Width(); - if( aResult.Height() < m_aMinSize.Height() ) - aResult.Height() = m_aMinSize.Height(); + if( ! m_bHidden ) + { + if( m_pElement && m_pElement->IsVisible() ) + aResult = m_pElement->GetOptimalSize( i_eType ); + else if( m_pChild ) + aResult = m_pChild->getOptimalSize( i_eType ); + if( aResult.Width() < m_aMinSize.Width() ) + aResult.Width() = m_aMinSize.Width(); + if( aResult.Height() < m_aMinSize.Height() ) + aResult.Height() = m_aMinSize.Height(); + } return aResult; } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index dd618766451c..79cb63cbfa3d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -228,6 +228,9 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( &maLayout ) ); maLayout.addChild( xIndent ); + // remember advanced controls to show/hide + mxAdvancedControls = xIndent; + boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); @@ -259,6 +262,9 @@ void PrintDialog::NUpTabPage::setupLayout() xRow->addWindow( &maNupOrderBox ); maLayout.addWindow( &maBorderCB ); + + // initially advanced controls are not show, rows=columns=1 + mxAdvancedControls->show( false, false ); } void PrintDialog::NUpTabPage::Resize() @@ -287,6 +293,8 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maPrinterFL( this, VclResId( SV_PRINT_PRINTERS_FL ) ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS ) ) + , maDetailsBtn( this, VclResId( SV_PRINT_DETAILS_BTN ) ) + , maDetailsTxt( this, VclResId( SV_PRINT_DETAILS_TXT ) ) , maStatusLabel( this, VclResId( SV_PRINT_STATUS_TXT ) ) , maStatusTxt( this, 0 ) , maLocationLabel( this, VclResId( SV_PRINT_LOCATION_TXT ) ) @@ -351,9 +359,25 @@ void PrintDialog::JobTabPage::setupLayout() // add print LB maLayout.addWindow( &maPrinters ); + // create a row for details button/text and properties button + boost::shared_ptr< vcl::RowOrColumn > xDetRow( new vcl::RowOrColumn( &maLayout, false ) ); + maLayout.addChild( xDetRow ); + xDetRow->addWindow( &maDetailsBtn ); + xDetRow->addWindow( &maDetailsTxt ); + xDetRow->addChild( new vcl::Spacer( xDetRow.get(), 2 ) ); + xDetRow->addWindow( &maSetupButton ); + + // create an indent for details + boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( &maLayout ) ); + maLayout.addChild( xIndent ); + // remember details controls + mxDetails = xIndent; + // create a column for the details + boost::shared_ptr< vcl::RowOrColumn > xDetCol( new vcl::RowOrColumn( xIndent.get() ) ); + xIndent->setChild( xDetCol ); // create a row for stati and properties button - boost::shared_ptr< vcl::RowOrColumn > xStateRow( new vcl::RowOrColumn( &maLayout, false ) ); - maLayout.addChild( xStateRow ); + boost::shared_ptr< vcl::RowOrColumn > xStateRow( new vcl::RowOrColumn( xDetCol.get(), false ) ); + xDetCol->addChild( xStateRow ); boost::shared_ptr< vcl::RowOrColumn > xLabelCol( new vcl::RowOrColumn( xStateRow.get(), true, aBorder.Height() ) ); xStateRow->addChild( xLabelCol ); xLabelCol->addWindow( &maStatusLabel ); @@ -366,8 +390,6 @@ void PrintDialog::JobTabPage::setupLayout() xStatusCol->addWindow( &maLocationTxt ); xStatusCol->addWindow( &maCommentTxt ); - xStateRow->addWindow( &maSetupButton ); - // add print range and copies columns maLayout.addWindow( &maCopies ); boost::shared_ptr< vcl::RowOrColumn > xRangeRow( new vcl::RowOrColumn( &maLayout, false, aBorder.Width() ) ); @@ -390,6 +412,11 @@ void PrintDialog::JobTabPage::setupLayout() xCopyCollateCol->addChild( xCollateRow ); xCollateRow->addWindow( &maCollateBox ); xCollateRow->addWindow( &maCollateImage ); + + maDetailsBtn.SetSymbol( SYMBOL_SPIN_DOWN ); + maDetailsBtn.SetSmallSymbol(); + maDetailsBtn.SetStyle( maDetailsBtn.GetStyle() | (WB_SMALLSTYLE | WB_BEVELBUTTON) ); + mxDetails->show( false, false ); } void PrintDialog::JobTabPage::readFromSettings() @@ -605,6 +632,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrGetSelectEntry() ); - maJobPage.maPrinters.SelectEntry( aNewPrinter ); // set new printer maPController->setPrinter( boost::shared_ptr( new Printer( aNewPrinter ) ) ); // update text fields @@ -1505,6 +1534,7 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) maNUpPage.maNupRowsEdt.SetValue( nRows ); maNUpPage.maNupColEdt.SetValue( nCols ); updateNup(); + maNUpPage.mxAdvancedControls->show( bCustom ); } return 0; @@ -1530,6 +1560,12 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maOKButton.SetText( maOptionsPage.maToFileBox.IsChecked() ? maPrintToFileText : maPrintText ); maLayout.resize(); } + else if( pButton == &maJobPage.maDetailsBtn ) + { + bool bShow = ! maJobPage.maStatusTxt.IsVisible(); + maJobPage.maDetailsBtn.SetSymbol( bShow ? SYMBOL_SPIN_UP : SYMBOL_SPIN_DOWN ); + maJobPage.mxDetails->show( bShow ); + } else if( pButton == &maJobPage.maCollateBox ) { maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ), -- cgit From d5f589e89e11326a62312647db3052d52f07de62 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 28 Jul 2009 11:54:16 +0000 Subject: #i92518# need sensible defaults for N-Up printing --- vcl/inc/vcl/print.hxx | 6 +++--- vcl/source/window/printdlg.cxx | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index a6563d2b75ed..5282be1bb5ed 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -419,10 +419,10 @@ public: MultiPageSetup() : nRows( 1 ), nColumns( 1 ), nRepeat( 1 ), aPaperSize( 21000, 29700 ) - , nLeftMargin( 500 ), nTopMargin( 500 ) - , nRightMargin( 500 ), nBottomMargin( 500 ) + , nLeftMargin( 0 ), nTopMargin( 0 ) + , nRightMargin( 0 ), nBottomMargin( 0 ) , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) - , bDrawBorder( true ) + , bDrawBorder( false ) { } }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 79cb63cbfa3d..1a13d2ebca52 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1499,10 +1499,15 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) long nPages = long(maNUpPage.maNupPagesBox.GetEntryData(maNUpPage.maNupPagesBox.GetSelectEntryPos())); int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); int nCols = int(maNUpPage.maNupColEdt.GetValue()); + long nPageMargin = long(maNUpPage.maPageMarginEdt.Denormalize(maNUpPage.maPageMarginEdt.GetValue( FUNIT_100TH_MM ))); + long nSheetMargin = long(maNUpPage.maSheetMarginEdt.Denormalize(maNUpPage.maSheetMarginEdt.GetValue( FUNIT_100TH_MM ))); bool bCustom = false; if( nPages == 1 ) + { nRows = nCols = 1; + nSheetMargin = 0; + } else if( nPages == 2 || nPages == 4 || nPages == 6 || nPages == 9 || nPages == 16 ) { Size aJobPageSize( getJobPageSize() ); @@ -1527,12 +1532,16 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) nRows = nCols = 3; else if( nPages == 16 ) nRows = nCols = 4; + nPageMargin = 500; + nSheetMargin = 500; } else bCustom = true; maNUpPage.maNupRowsEdt.SetValue( nRows ); maNUpPage.maNupColEdt.SetValue( nCols ); + maNUpPage.maPageMarginEdt.SetValue( maNUpPage.maPageMarginEdt.Normalize( nPageMargin ), FUNIT_100TH_MM ); + maNUpPage.maSheetMarginEdt.SetValue( maNUpPage.maSheetMarginEdt.Normalize( nSheetMargin ), FUNIT_100TH_MM ); updateNup(); maNUpPage.mxAdvancedControls->show( bCustom ); } -- cgit From 6c352e02d29d4da91d3c9a5c4add344b8696faed Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 28 Jul 2009 19:01:04 +0000 Subject: #i92518# adapt UI spec --- vcl/inc/vcl/arrange.hxx | 1 + vcl/inc/vcl/print.hxx | 48 ++++++++++------ vcl/inc/vcl/prndlg.hxx | 1 + vcl/source/gdi/print3.cxx | 122 ++++++++++++++++++++--------------------- vcl/source/window/arrange.cxx | 63 +++++++++++++++------ vcl/source/window/printdlg.cxx | 95 +++++++++++++++++++------------- 6 files changed, 196 insertions(+), 134 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index b4e32350d685..3ef93311ee58 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -83,6 +83,7 @@ namespace vcl sal_Int32 getExpandPriority() const; Size getOptimalSize( WindowSizeType ) const; + bool isVisible() const; }; Window* m_pParentWindow; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 5282be1bb5ed..dd276e76c760 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -547,17 +547,34 @@ class VCL_DLLPUBLIC PrinterOptionsHelper { return getStringValue( rtl::OUString::createFromAscii( i_pPropName ), i_rDefault ); } // helper functions for user to create a single control + struct UIControlOptions + { + rtl::OUString maDependsOnName; + sal_Int32 mnDependsOnEntry; + sal_Bool mbAttachToDependency; + rtl::OUString maGroupHint; + sal_Bool mbInternalOnly; + com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > maAddProps; + + UIControlOptions( const rtl::OUString& i_rDependsOnName = rtl::OUString(), + sal_Int32 i_nDependsOnEntry = -1, + sal_Bool i_bAttachToDependency = sal_False, + const rtl::OUString& i_rGroupHint = rtl::OUString(), + sal_Bool i_bInternalOnly = sal_False + ) + : maDependsOnName( i_rDependsOnName ) + , mnDependsOnEntry( i_nDependsOnEntry ) + , mbAttachToDependency( i_bAttachToDependency ) + , maGroupHint( i_rGroupHint ) + , mbInternalOnly( sal_False ) {} + }; // general control static com::sun::star::uno::Any getUIControlOpt( const rtl::OUString& i_rTitle, const com::sun::star::uno::Sequence< rtl::OUString >& i_rHelpText, const rtl::OUString& i_rType, const com::sun::star::beans::PropertyValue* i_pValue = NULL, - const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1, - sal_Bool i_bAttachToDependency = sal_False, - const com::sun::star::beans::PropertyValue* i_pAddProps = NULL, - sal_Int32 i_nAddProps = 0 + const UIControlOptions& i_rControlOptions = UIControlOptions() ); // create a group (e.g. a TabPage); following controls will be grouped in it until the next // group begins @@ -566,16 +583,17 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // create a subgroup (e.g. a FixedLine); following controls will be grouped in it until the next // subgroup or group begins // setting bJobPage = true will make the subgroup appear on the first page of the print dialog - static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, const rtl::OUString& i_rGroupHint = rtl::OUString(), bool i_bInternalOnly = false ); + static com::sun::star::uno::Any getSubgroupControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, + const UIControlOptions& i_rControlOptions = UIControlOptions() + ); // create a bool option (usually a checkbox) static com::sun::star::uno::Any getBoolControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Bool i_bValue, - const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1, - sal_Bool i_bAttachToDependency = sal_False + const UIControlOptions& i_rControlOptions = UIControlOptions() ); // create a set of choices (either a radio button group or a list box) @@ -585,9 +603,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const com::sun::star::uno::Sequence< rtl::OUString >& i_rChoices, sal_Int32 i_nValue, const rtl::OUString& i_rType = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Radio" ) ), - const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1, - sal_Bool i_bAttachToDependency = sal_False + const UIControlOptions& i_rControlOptions = UIControlOptions() ); // create an integer range (e.g. a spin field) @@ -598,9 +614,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper sal_Int32 i_nValue, sal_Int32 i_nMinValue = -1, sal_Int32 i_nMaxValue = -2, - const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1, - sal_Bool i_bAttachToDependency = sal_False + const UIControlOptions& i_rControlOptions = UIControlOptions() ); // create a string field @@ -609,9 +623,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, const rtl::OUString& i_rValue, - const rtl::OUString* i_pDependsOnName = NULL, - sal_Int32 i_nDependsOnEntry = -1, - sal_Bool i_bAttachToDependency = sal_False + const UIControlOptions& i_rControlOptions = UIControlOptions() ); }; diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 3f2fa7d3eb3b..5af1c85cbba6 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -164,6 +164,7 @@ namespace vcl CheckBox maReverseOrderBox; vcl::RowOrColumn maLayout; + boost::shared_ptr mxOptGroup; OutputOptPage( Window*, const ResId& ); virtual ~OutputOptPage(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 53326cb3efbd..64e7bf0c5576 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1195,11 +1195,7 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, const Sequence< rtl::OUString >& i_rHelpTexts, const rtl::OUString& i_rType, const PropertyValue* i_pVal, - const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry, - sal_Bool i_bAttachToDependency, - const PropertyValue* i_pAddProps, - sal_Int32 i_nAddProps + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions ) { sal_Int32 nElements = @@ -1207,10 +1203,18 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + (i_rTitle.getLength() ? 1 : 0) // Text + (i_rHelpTexts.getLength() ? 1 : 0) // HelpText + (i_pVal ? 1 : 0) // Property - + (i_pDependsOnName ? (i_nDependsOnEntry != -1 ? 2 : 1) : 0) // dependencies - + (i_pDependsOnName && i_bAttachToDependency ? 1 : 0) // attach to dependency - + i_nAddProps + + i_rControlOptions.maAddProps.getLength() // additional props + + (i_rControlOptions.maGroupHint.getLength() ? 1 : 0) // grouping + + (i_rControlOptions.mbInternalOnly ? 1 : 0) // internal hint ; + if( i_rControlOptions.maDependsOnName.getLength() ) + { + nElements += 1; + if( i_rControlOptions.mnDependsOnEntry != -1 ) + nElements += 1; + if( i_rControlOptions.mbAttachToDependency ) + nElements += 1; + } Sequence< PropertyValue > aCtrl( nElements ); sal_Int32 nUsed = 0; @@ -1231,23 +1235,35 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Property" ) ); aCtrl[nUsed++].Value = makeAny( *i_pVal ); } - if( i_pDependsOnName ) + if( i_rControlOptions.maDependsOnName.getLength() ) { aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnName" ) ); - aCtrl[nUsed++].Value = makeAny( *i_pDependsOnName ); - if( i_nDependsOnEntry != -1 ) + aCtrl[nUsed++].Value = makeAny( i_rControlOptions.maDependsOnName ); + if( i_rControlOptions.mnDependsOnEntry != -1 ) { aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DependsOnEntry" ) ); - aCtrl[nUsed++].Value = makeAny( i_nDependsOnEntry ); + aCtrl[nUsed++].Value = makeAny( i_rControlOptions.mnDependsOnEntry ); } - if( i_bAttachToDependency ) + if( i_rControlOptions.mbAttachToDependency ) { aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "AttachToDependency" ) ); - aCtrl[nUsed++].Value = makeAny( i_bAttachToDependency ); + aCtrl[nUsed++].Value = makeAny( i_rControlOptions.mbAttachToDependency ); } } - for( sal_Int32 i = 0; i < i_nAddProps; i++ ) - aCtrl[ nUsed++ ] = i_pAddProps[i]; + if( i_rControlOptions.maGroupHint.getLength() ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GroupingHint" ) ); + aCtrl[nUsed++].Value <<= i_rControlOptions.maGroupHint; + } + if( i_rControlOptions.mbInternalOnly ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InternalUIOnly" ) ); + aCtrl[nUsed++].Value <<= sal_True; + } + + sal_Int32 nAddProps = i_rControlOptions.maAddProps.getLength(); + for( sal_Int32 i = 0; i < nAddProps; i++ ) + aCtrl[ nUsed++ ] = i_rControlOptions.maAddProps[i]; DBG_ASSERT( nUsed == nElements, "nUsed != nElements, probable heap corruption" ); @@ -1265,21 +1281,11 @@ Any PrinterOptionsHelper::getGroupControlOpt( const rtl::OUString& i_rTitle, con return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Group" ) ) ); } -Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, - const rtl::OUString& i_rGroupHint, bool i_bInternalOnly ) +Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, + const rtl::OUString& i_rHelpText, + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions + ) { - PropertyValue aAddProps[2]; - sal_Int32 nUsed = 0; - if( i_rGroupHint.getLength() ) - { - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GroupingHint" ) ); - aAddProps[nUsed++].Value <<= i_rGroupHint; - } - if( i_bInternalOnly ) - { - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InternalUIOnly" ) ); - aAddProps[nUsed++].Value <<= sal_True; - } Sequence< rtl::OUString > aHelpText; if( i_rHelpText.getLength() > 0 ) { @@ -1287,16 +1293,14 @@ Any PrinterOptionsHelper::getSubgroupControlOpt( const rtl::OUString& i_rTitle, *aHelpText.getArray() = i_rHelpText; } return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Subgroup" ) ), - NULL, NULL, -1, sal_False, aAddProps, nUsed ); + NULL, i_rControlOptions ); } Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, sal_Bool i_bValue, - const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry, - sal_Bool i_bAttachToDependency + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions ) { Sequence< rtl::OUString > aHelpText; @@ -1308,7 +1312,7 @@ Any PrinterOptionsHelper::getBoolControlOpt( const rtl::OUString& i_rTitle, PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_bValue ); - return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, i_pDependsOnName, i_nDependsOnEntry, i_bAttachToDependency ); + return getUIControlOpt( i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Bool" ) ), &aVal, i_rControlOptions ); } Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, @@ -1317,20 +1321,19 @@ Any PrinterOptionsHelper::getChoiceControlOpt( const rtl::OUString& i_rTitle, const Sequence< rtl::OUString >& i_rChoices, sal_Int32 i_nValue, const rtl::OUString& i_rType, - const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry, - sal_Bool i_bAttachToDependency + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions ) { - PropertyValue aAddProps[2]; - sal_Int32 nUsed = 0; - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Choices" ) ); - aAddProps[nUsed++].Value = makeAny( i_rChoices ); + UIControlOptions aOpt( i_rControlOptions ); + sal_Int32 nUsed = aOpt.maAddProps.getLength(); + aOpt.maAddProps.realloc( nUsed + 1 ); + aOpt.maAddProps[nUsed].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Choices" ) ); + aOpt.maAddProps[nUsed].Value = makeAny( i_rChoices ); PropertyValue aVal; aVal.Name = i_rProperty; aVal.Value = makeAny( i_nValue ); - return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, i_pDependsOnName, i_nDependsOnEntry, i_bAttachToDependency, aAddProps, nUsed ); + return getUIControlOpt( i_rTitle, i_rHelpText, i_rType, &aVal, aOpt ); } Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, @@ -1339,19 +1342,18 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, sal_Int32 i_nValue, sal_Int32 i_nMinValue, sal_Int32 i_nMaxValue, - const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry, - sal_Bool i_bAttachToDependency + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions ) { - PropertyValue aAddProps[2]; - sal_Int32 nUsed = 0; + UIControlOptions aOpt( i_rControlOptions ); if( i_nMaxValue >= i_nMinValue ) { - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MinValue" ) ); - aAddProps[nUsed++].Value = makeAny( i_nMinValue ); - aAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxValue" ) ); - aAddProps[nUsed++].Value = makeAny( i_nMaxValue ); + sal_Int32 nUsed = aOpt.maAddProps.getLength(); + aOpt.maAddProps.realloc( nUsed + 2 ); + aOpt.maAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MinValue" ) ); + aOpt.maAddProps[nUsed++].Value = makeAny( i_nMinValue ); + aOpt.maAddProps[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MaxValue" ) ); + aOpt.maAddProps[nUsed++].Value = makeAny( i_nMaxValue ); } Sequence< rtl::OUString > aHelpText; @@ -1367,19 +1369,15 @@ Any PrinterOptionsHelper::getRangeControlOpt( const rtl::OUString& i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Range" ) ), &aVal, - i_pDependsOnName, - i_nDependsOnEntry, - i_bAttachToDependency, - aAddProps, nUsed ); + aOpt + ); } Any PrinterOptionsHelper::getEditControlOpt( const rtl::OUString& i_rTitle, const rtl::OUString& i_rHelpText, const rtl::OUString& i_rProperty, const rtl::OUString& i_rValue, - const rtl::OUString* i_pDependsOnName, - sal_Int32 i_nDependsOnEntry, - sal_Bool i_bAttachToDependency + const PrinterOptionsHelper::UIControlOptions& i_rControlOptions ) { Sequence< rtl::OUString > aHelpText; @@ -1395,8 +1393,6 @@ Any PrinterOptionsHelper::getEditControlOpt( const rtl::OUString& i_rTitle, aHelpText, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Edit" ) ), &aVal, - i_pDependsOnName, - i_nDependsOnEntry, - i_bAttachToDependency, - 0, 0 ); + i_rControlOptions + ); } diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index e392a1cc7d5e..ae578f8e5337 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -68,6 +68,19 @@ void WindowArranger::show( bool i_bShow, bool i_bImmediateUpdate ) pEle->m_pChild->show( i_bShow, false ); } } + if( m_pParentArranger ) + { + nEle = m_pParentArranger->countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + Element* pEle = m_pParentArranger->getElement( i ); + if( pEle && pEle->m_pChild.get() == this ) + { + pEle->m_bHidden = ! i_bShow; + break; + } + } + } if( i_bImmediateUpdate ) { // find the topmost parent @@ -78,6 +91,18 @@ void WindowArranger::show( bool i_bShow, bool i_bImmediateUpdate ) } } +bool WindowArranger::Element::isVisible() const +{ + bool bVisible = false; + if( ! m_bHidden ) + { + bVisible = true; + if( m_pElement ) + bVisible = m_pElement->IsVisible(); + } + return bVisible; +} + sal_Int32 WindowArranger::Element::getExpandPriority() const { sal_Int32 nPrio = m_nExpandPriority; @@ -178,19 +203,22 @@ void RowOrColumn::distributeRowWidth( std::vector& io_rSizes, long /*i_nUs sal_Int32 nHighPrio = 0; for( size_t i = 0; i < nElements; i++ ) { - sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); - if( nCurPrio > nHighPrio ) + if( m_aElements[ i ].isVisible() ) { - aIndices.clear(); - nHighPrio = nCurPrio; + sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); + if( nCurPrio > nHighPrio ) + { + aIndices.clear(); + nHighPrio = nCurPrio; + } + if( nCurPrio == nHighPrio ) + aIndices.push_back( i ); } - if( nCurPrio == nHighPrio ) - aIndices.push_back( i ); } - // distribute extra space evenly among elements + // distribute extra space evenly among collected elements nElements = aIndices.size(); - if( nElements > 0 ) // sanity check + if( nElements > 0 ) { long nDelta = i_nExtraWidth / nElements; for( size_t i = 0; i < nElements; i++ ) @@ -215,19 +243,22 @@ void RowOrColumn::distributeColumnHeight( std::vector& io_rSizes, long /*i sal_Int32 nHighPrio = 3; for( size_t i = 0; i < nElements; i++ ) { - sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); - if( nCurPrio > nHighPrio ) + if( m_aElements[ i ].isVisible() ) { - aIndices.clear(); - nHighPrio = nCurPrio; + sal_Int32 nCurPrio = m_aElements[ i ].getExpandPriority(); + if( nCurPrio > nHighPrio ) + { + aIndices.clear(); + nHighPrio = nCurPrio; + } + if( nCurPrio == nHighPrio ) + aIndices.push_back( i ); } - if( nCurPrio == nHighPrio ) - aIndices.push_back( i ); } - // distribute extra space evenly among elements + // distribute extra space evenly among collected elements nElements = aIndices.size(); - if( nElements > 0 ) // sanity check + if( nElements > 0 ) { long nDelta = i_nExtraHeight / nElements; for( size_t i = 0; i < nElements; i++ ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1a13d2ebca52..81fa42cc064c 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -498,6 +498,7 @@ void PrintDialog::OutputOptPage::setupLayout() maLayout.addChild( xIndent ); boost::shared_ptr xCol( new vcl::RowOrColumn( xIndent.get(), aBorder.Height() ) ); xIndent->setChild( xCol ); + mxOptGroup = xCol; xCol->addWindow( &maToFileBox ); xCol->addWindow( &maCollateSingleJobsBox ); xCol->addWindow( &maReverseOrderBox ); @@ -829,6 +830,7 @@ void PrintDialog::setupOptionalUI() Window* pCurParent = 0, *pDynamicPageParent = 0; USHORT nOptPageId = 9, nCurSubGroup = 0; bool bOnStaticPage = false; + bool bSubgroupOnStaticPage = false; std::multimap< rtl::OUString, vcl::RowOrColumn* > aPropertyToDependencyRowMap; @@ -917,6 +919,52 @@ void PrintDialog::setupOptionalUI() } } + // is it necessary to switch between static and dynamic pages ? + bool bSwitchPage = false; + if( aGroupingHint.getLength() ) + bSwitchPage = true; + else if( aCtrlType.equalsAscii( "Subgroup" ) || (bOnStaticPage && ! bSubgroupOnStaticPage ) ) + bSwitchPage = true; + if( bSwitchPage ) + { + // restore to dynamic + pCurParent = pDynamicPageParent; + pCurColumn = aDynamicColumns.empty() ? NULL : aDynamicColumns.back(); + bOnStaticPage = false; + bSubgroupOnStaticPage = false; + + if( aGroupingHint.equalsAscii( "PrintRange" ) ) + { + pCurColumn = maJobPage.mxPrintRange.get(); + pCurParent = &maJobPage; // set job page as current parent + bOnStaticPage = true; + } + else if( aGroupingHint.equalsAscii( "OptionsPage" ) ) + { + pCurColumn = &maOptionsPage.maLayout; + pCurParent = &maOptionsPage; // set options page as current parent + bOnStaticPage = true; + } + else if( aGroupingHint.equalsAscii( "OptionsPageOptGroup" ) ) + { + pCurColumn = maOptionsPage.mxOptGroup.get(); + pCurParent = &maOptionsPage; // set options page as current parent + bOnStaticPage = true; + } + else if( aGroupingHint.equalsAscii( "LayoutPage" ) ) + { + pCurColumn = &maNUpPage.maLayout; + pCurParent = &maNUpPage; // set layout page as current parent + bOnStaticPage = true; + } + else if( aGroupingHint.getLength() ) + { + pCurColumn = &maJobPage.maLayout; + pCurParent = &maJobPage; // set job page as current parent + bOnStaticPage = true; + } + } + if( aCtrlType.equalsAscii( "Group" ) || ( ! pCurParent && ! (bOnStaticPage || aGroupingHint.getLength() ) ) ) { @@ -940,45 +988,12 @@ void PrintDialog::setupOptionalUI() pCurColumn = aDynamicColumns.back(); pCurColumn->setParentWindow( pNewGroup ); pCurColumn->setOuterBorder( aBorder.Width() ); + bSubgroupOnStaticPage = false; + bOnStaticPage = false; } else if( aCtrlType.equalsAscii( "Subgroup" ) && (pCurParent || aGroupingHint.getLength() ) ) { - // change to job page or back if necessary - if( (bOnStaticPage && ! aGroupingHint.getLength() ) || - (! bOnStaticPage && aGroupingHint.getLength() ) ) - { - bOnStaticPage = (aGroupingHint.getLength() != 0); - if( bOnStaticPage ) - { - pDynamicPageParent = pCurParent; // save current parent - } - else - { - pCurParent = pDynamicPageParent; // set current tab page as parent - } - } - - if( bOnStaticPage ) - { - if( aGroupingHint.equalsAscii( "PrintRange" ) ) - { - pCurColumn = maJobPage.mxPrintRange.get(); - pCurParent = &maJobPage; // set job page as current parent - } - else if( aGroupingHint.equalsAscii( "OptionsPage" ) ) - { - pCurColumn = &maOptionsPage.maLayout; - pCurParent = &maOptionsPage; // set options page as current parent - } - else - { - pCurColumn = &maJobPage.maLayout; - pCurParent = &maJobPage; // set job page as current parent - } - } - else - pCurColumn = aDynamicColumns.back(); - + bSubgroupOnStaticPage = (aGroupingHint.getLength() != 0); // create group FixedLine if( ! aGroupingHint.equalsAscii( "PrintRange" ) || ! pCurColumn->countElements() == 0 @@ -1235,6 +1250,13 @@ void PrintDialog::setupOptionalUI() } } + // print range empty (currently math only) -> hide print range and spacer line + if( maJobPage.mxPrintRange->countElements() == 0 ) + { + maJobPage.mxPrintRange->show( false, false ); + maJobPage.maCopySpacer.Show( FALSE ); + } + // calculate job page Size aMaxSize = maJobPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ); @@ -1405,7 +1427,6 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) boost::shared_ptr aPrt( maPController->getPrinter() ); - if( i_bNewPage ) { const MapMode aMapMode( MAP_100TH_MM ); -- cgit From a155b13c1e9f7367724c0f24e1bc2ac6397be6ce Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 29 Jul 2009 09:56:25 +0000 Subject: fix a warning --- vcl/inc/vcl/print.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index dd276e76c760..4ceca0d9a3ef 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -566,7 +566,7 @@ class VCL_DLLPUBLIC PrinterOptionsHelper , mnDependsOnEntry( i_nDependsOnEntry ) , mbAttachToDependency( i_bAttachToDependency ) , maGroupHint( i_rGroupHint ) - , mbInternalOnly( sal_False ) {} + , mbInternalOnly( i_bInternalOnly ) {} }; // general control -- cgit From 3599f931a9a021209c1ea0da8bec8d9d07664021 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 29 Jul 2009 11:48:58 +0000 Subject: #i92516# resize dialog if details get to large --- vcl/source/window/printdlg.cxx | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 81fa42cc064c..f2b4ceb89c00 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1595,6 +1595,15 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) bool bShow = ! maJobPage.maStatusTxt.IsVisible(); maJobPage.maDetailsBtn.SetSymbol( bShow ? SYMBOL_SPIN_UP : SYMBOL_SPIN_DOWN ); maJobPage.mxDetails->show( bShow ); + // enlarge dialog if necessary + Size aMinSize( maJobPage.maLayout.getOptimalSize( WINDOWSIZE_MINIMUM ) ); + Size aCurSize( maJobPage.GetSizePixel() ); + if( aCurSize.Height() < aMinSize.Height() ) + { + Size aDlgSize( GetOutputSizePixel() ); + aDlgSize.Height() += aMinSize.Height() - aCurSize.Height(); + SetOutputSizePixel( aDlgSize ); + } } else if( pButton == &maJobPage.maCollateBox ) { -- cgit From 3d292304d4a5c8135558a76d1ff7e819326cff83 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 29 Jul 2009 15:36:16 +0000 Subject: #i92516# make native implementation more palatable --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 123 ++++++++++++++++++-------- vcl/source/src/print.src | 1 + 2 files changed, 89 insertions(+), 35 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 645de97d7ac3..f6d9ff7b7d9c 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -87,7 +87,8 @@ class ControllerProperties NSTextField* mpPageEdit; NSStepper* mpStepper; NSTextView* mpPagesLabel; - + ResStringArray maLocalizedStrings; + public: ControllerProperties( vcl::PrinterController* i_pController, NSPrintOperation* i_pOp, @@ -105,9 +106,18 @@ class ControllerProperties mpPreview( nil ), mpPageEdit( nil ), mpStepper( nil ), - mpPagesLabel( nil ) + mpPagesLabel( nil ), + maLocalizedStrings( VclResId( SV_PRINT_NATIVE_STRINGS ) ) { mpState->bNeedRestart = false; + DBG_ASSERT( maLocalizedStrings.Count() >= 4, "resources not found !" ); + } + + rtl::OUString getMoreString() + { + return maLocalizedStrings.Count() >= 4 + ? rtl::OUString( maLocalizedStrings.GetString( 3 ) ) + : rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "More" ) ); } void updatePrintJob() @@ -131,7 +141,7 @@ class ControllerProperties { #if 0 // Warning: bad hack ahead - // Apple does not give as a chance of changing the page count, + // Apple does not give us a chance of changing the page count, // and they don't let us cancel the dialog either // hack: send a cancel message to the window displaying our views. // this is ugly. @@ -324,11 +334,7 @@ class ControllerProperties void setupPreview( ControlTarget* i_pCtrlTarget ) { - // get some needed resources - ResStringArray aStrings( VclResId( SV_PRINT_NATIVE_STRINGS ) ); - - DBG_ASSERT( aStrings.Count() >= 3, "resources not found !" ); - if( aStrings.Count() < 3 ) + if( maLocalizedStrings.Count() < 3 ) return; // get the preview control @@ -340,7 +346,7 @@ class ControllerProperties // create a box to put the preview controls in mpPreviewBox = [[NSBox alloc] initWithFrame: aPreviewFrame]; - [mpPreviewBox setTitle: [CreateNSString( aStrings.GetString( 0 ) ) autorelease]]; + [mpPreviewBox setTitle: [CreateNSString( maLocalizedStrings.GetString( 0 ) ) autorelease]]; [mpAccessoryView addSubview: [mpPreviewBox autorelease]]; // now create the image view of the preview @@ -368,7 +374,7 @@ class ControllerProperties [mpPagesLabel setSelectable: NO]; [mpPagesLabel setDrawsBackground: NO]; [mpPagesLabel setString: [pText autorelease]]; - [mpPagesLabel setToolTip: [CreateNSString( aStrings.GetString( 2 ) ) autorelease]]; + [mpPagesLabel setToolTip: [CreateNSString( maLocalizedStrings.GetString( 2 ) ) autorelease]]; [mpPreviewBox addSubview: [mpPagesLabel autorelease]]; NSRect aFieldRect = { { 45, 5 }, { 35, 25 } }; @@ -376,7 +382,7 @@ class ControllerProperties [mpPageEdit setEditable: YES]; [mpPageEdit setSelectable: YES]; [mpPageEdit setDrawsBackground: YES]; - [mpPageEdit setToolTip: [CreateNSString( aStrings.GetString( 1 ) ) autorelease]]; + [mpPageEdit setToolTip: [CreateNSString( maLocalizedStrings.GetString( 1 ) ) autorelease]]; [mpPreviewBox addSubview: [mpPageEdit autorelease]]; // add a stepper control @@ -570,6 +576,37 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) rMaxSize.height = aUnion.size.height; } +static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) +{ + // loop over all contained tab pages + NSArray* pTabbedViews = [pTabView tabViewItems]; + int nViews = [pTabbedViews count]; + for( int i = 0; i < nViews; i++ ) + { + NSTabViewItem* pItem = (NSTabViewItem*)[pTabbedViews objectAtIndex: i]; + NSView* pView = [pItem view]; + if( pView ) + { + NSRect aRect = [pView frame]; + double nDiff = aTabSize.height - aRect.size.height; + aRect.size = aTabSize; + [pView setFrame: aRect]; + + NSArray* pSubViews = [pView subviews]; + unsigned int nSubViews = [pSubViews count]; + + // move everything up + for( unsigned int n = 0; n < nSubViews; n++ ) + { + NSView* pCurSubView = [pSubViews objectAtIndex: n]; + NSRect aFrame = [pCurSubView frame]; + aFrame.origin.y += nDiff; + [pCurSubView setFrame: aFrame]; + } + } + } +} + @implementation AquaPrintAccessoryView +(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withController: (vcl::PrinterController*)pController withState: (PrintAccessoryViewState*)pState; @@ -664,8 +701,14 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) { // since our build target is MacOSX 10.4 we can have only one accessory view // so we have a single accessory view that is tabbed for grouping - if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent ) + if( aCtrlType.equalsAscii( "Group" ) + || ! pCurParent + || ( aCtrlType.equalsAscii( "Subgroup" ) && nCurY < -200 && ! bIgnore ) + ) { + rtl::OUString aGroupTitle( aText ); + if( aCtrlType.equalsAscii( "Subgroup" ) ) + aGroupTitle = pControllerProperties->getMoreString(); // set size of current parent if( pCurParent ) adjustViewAndChildren( pCurParent, aMaxTabSize ); @@ -673,7 +716,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // new tab item if( ! aText.getLength() ) aText = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OOo" ) ); - NSString* pLabel = CreateNSString( aText ); + NSString* pLabel = CreateNSString( aGroupTitle ); NSTabViewItem* pItem = [[NSTabViewItem alloc] initWithIdentifier: pLabel ]; [pItem setLabel: pLabel]; [pTabView addTabViewItem: pItem]; @@ -682,7 +725,9 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) [pLabel release]; // reset indent - nCurX = 0; + nCurX = 20; + // reset Y + nCurY = 0; } if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) @@ -690,6 +735,19 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) bIgnoreSubgroup = bIgnore; if( bIgnore ) continue; + + // if this is not the first view on the page + // insert a separator + NSArray* pArray = [pCurParent subviews]; + if( pArray && [pArray count] > 0 ) + { + NSRect aSepRect = { { 0, nCurY - 15 }, { 300, 15 } }; + NSBox* pBox = [[NSBox alloc] initWithFrame: aSepRect]; + [pBox setBoxType: NSBoxSeparator]; + [pCurParent addSubview: pBox]; + + nCurY -= 15; + } NSString* pText = CreateNSString( aText ); NSRect aTextRect = { { 0, 0 }, { 300, 15 } }; @@ -833,21 +891,17 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) NSString* pText = CreateNSString( aText ); // measure the text - NSFont* pFont = [NSFont labelFontOfSize: 0]; + NSFont* pFont = [NSFont controlContentFontOfSize: 0]; NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont forKey: NSFontAttributeName]; NSSize aTextSize = [pText sizeWithAttributes: pDict]; - // FIXME: the only thing reliable about sizeWithAttributes is - // that the size it outputs is way too small for our NSTextView - // that would not matter so much if NSTextView's fitToSize actually - // did something out of the box, alas it doesn't. This probably needs more - // fiddling with NSTextView's and NSTextContainer's parameters, however - // since this already almost cost me my sanity a Murphy factor of 1.5 - // will have to suffice for the time being. - aTextSize.width *= 1.5; + // leave a little space + aTextSize.width += 10; aTextSize.height += 3; - NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; + + // don't indent attached lists, looks bad in the existing cases + NSRect aTextRect = { { nCurX /* + nAttachOffset*/, 0 }, aTextSize }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; [pTextView setEditable: NO]; @@ -861,7 +915,8 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) aTextRect = [pTextView frame]; - NSRect aBtnRect = { { nCurX + nAttachOffset + aTextRect.size.width, 0 }, { 0, 15 } }; + // don't indent attached lists, looks bad in the existing cases + NSRect aBtnRect = { { nCurX /*+ nAttachOffset*/ + aTextRect.size.width, 0 }, { 0, 15 } }; NSPopUpButton* pBtn = [[NSPopUpButton alloc] initWithFrame: aBtnRect pullsDown: NO]; // iterate options @@ -915,20 +970,15 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) { // add a label NSString* pText = CreateNSString( aText ); - NSFont* pFont = [NSFont labelFontOfSize: 0]; + NSFont* pFont = [NSFont controlContentFontOfSize: 0]; NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont forKey: NSFontAttributeName]; NSSize aTextSize = [pText sizeWithAttributes: pDict]; - // FIXME: the only thing reliable about sizeWithAttributes is - // that the size it outputs is way too small for our NSTextView - // that would not matter so much if NSTextView's fitToSize actually - // did something out of the box, alas it doesn't. This probably needs more - // fiddling with NSTextView's and NSTextContainer's parameters, however - // since this already almost cost me my sanity a Murphy factor of 1.5 - // will have to suffice for the time being. - aTextSize.width *= 1.5; + // leave a little space + aTextSize.width += 10; aTextSize.height += 3; + NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; @@ -1049,7 +1099,10 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) } pControllerProperties->updateEnableState(); adjustViewAndChildren( pCurParent, aMaxTabSize ); - + + // now reposition everything again so it is upper bound + adjustTabViews( pTabView, aMaxTabSize ); + // find the minimum needed tab size NSSize aTabCtrlSize = [pTabView minimumSize]; aTabCtrlSize.height += aMaxTabSize.height + 10; diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 63d5bc6047c5..80ad8aee7409 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -419,5 +419,6 @@ StringArray SV_PRINT_NATIVE_STRINGS < "Preview"; >; < "Page Number"; >; < "Number of pages"; >; + < "More"; >; }; }; -- cgit From 20914171a71d95d9451c4e3743f2fcf62045418d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Jul 2009 13:52:50 +0000 Subject: #i92518# n-up ordering --- vcl/inc/vcl/print.hxx | 26 +++++----- vcl/inc/vcl/prndlg.hxx | 23 +++++++++ vcl/inc/vcl/svids.hrc | 2 + vcl/source/gdi/print3.cxx | 16 +++++- vcl/source/src/print.src | 4 +- vcl/source/window/arrange.cxx | 2 +- vcl/source/window/printdlg.cxx | 110 ++++++++++++++++++++++++++++++++++++----- 7 files changed, 155 insertions(+), 28 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 4ceca0d9a3ef..128393f3dd3f 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -402,20 +402,23 @@ class VCL_DLLPUBLIC PrinterController protected: PrinterController( const boost::shared_ptr& ); public: + enum NupOrderType + { LRTB, TBLR }; struct MultiPageSetup { // all metrics in 100th mm - int nRows; - int nColumns; - int nRepeat; - Size aPaperSize; - long nLeftMargin; - long nTopMargin; - long nRightMargin; - long nBottomMargin; - long nHorizontalSpacing; - long nVerticalSpacing; - bool bDrawBorder; + int nRows; + int nColumns; + int nRepeat; + Size aPaperSize; + long nLeftMargin; + long nTopMargin; + long nRightMargin; + long nBottomMargin; + long nHorizontalSpacing; + long nVerticalSpacing; + bool bDrawBorder; + PrinterController::NupOrderType nOrder; MultiPageSetup() : nRows( 1 ), nColumns( 1 ), nRepeat( 1 ), aPaperSize( 21000, 29700 ) @@ -423,6 +426,7 @@ public: , nRightMargin( 0 ), nBottomMargin( 0 ) , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) , bDrawBorder( false ) + , nOrder( LRTB ) { } }; diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 5af1c85cbba6..cb472474aefc 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -70,6 +70,27 @@ namespace vcl void setPreview( const GDIMetaFile&, const Size& ); }; + class ShowNupOrderWindow : public Window + { + int mnOrderMode; + int mnRows; + int mnColumns; + void ImplInitSettings(); + public: + ShowNupOrderWindow( Window* pParent ); + virtual ~ShowNupOrderWindow(); + + virtual void Paint( const Rectangle& ); + + void setValues( int i_nOrderMode, int i_nColumns, int i_nRows ) + { + mnOrderMode = i_nOrderMode; + mnRows = i_nRows; + mnColumns = i_nColumns; + Invalidate(); + } + }; + class NUpTabPage : public TabPage { public: @@ -92,11 +113,13 @@ namespace vcl // page order ("left to right, then down") FixedText maNupOrderTxt; ListBox maNupOrderBox; + ShowNupOrderWindow maNupOrderWin; // border around each page CheckBox maBorderCB; vcl::RowOrColumn maLayout; boost::shared_ptr< vcl::WindowArranger >mxAdvancedControls; + boost::shared_ptr< vcl::RowOrColumn > mxLayoutGroup; void setupLayout(); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 9e24cffe48a1..7550cb9106a7 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -111,6 +111,8 @@ #define SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT 1 #define SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE 2 +#define SV_PRINT_PRT_NUP_ORDER_LRTD 0 +#define SV_PRINT_PRT_NUP_ORDER_TDLR 1 #define SV_PRINT_TAB_JOB 2 #define SV_PRINT_PRINTERS_FL 1 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 64e7bf0c5576..27c326569bfb 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -689,6 +689,18 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o Size aPageSize = getPageFile( nPage, aPageFile, i_bMayUseCache ); if( aPageSize.Width() && aPageSize.Height() ) { + long nCellX = 0, nCellY = 0; + switch( rMPS.nOrder ) + { + case PrinterController::LRTB: + nCellX = (nSubPage % rMPS.nColumns); + nCellY = (nSubPage / rMPS.nColumns); + break; + case PrinterController::TBLR: + nCellX = (nSubPage / rMPS.nRows); + nCellY = (nSubPage % rMPS.nRows); + break; + } // scale the metafile down to a sub page size double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); @@ -699,8 +711,8 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o // move the subpage so it is centered in its "cell" long nOffX = (aSubPageSize.Width() - long(double(aPageSize.Width()) * fScale)) / 2; long nOffY = (aSubPageSize.Height() - long(double(aPageSize.Height()) * fScale)) / 2; - long nX = rMPS.nLeftMargin + nOffX + nAdvX * (nSubPage % rMPS.nColumns); - long nY = rMPS.nTopMargin + nOffY + nAdvY * (nSubPage / rMPS.nColumns); + long nX = rMPS.nLeftMargin + nOffX + nAdvX * nCellX; + long nY = rMPS.nTopMargin + nOffY + nAdvY * nCellY; aPageFile.Move( nX, nY ); aPageFile.WindStart(); // calculate border rectangle diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 80ad8aee7409..e8d418555274 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -237,8 +237,8 @@ ModalDialog SV_DLG_PRINT CurPos = 0; StringList [en-US] = { - < "left to right, then down"; 1; >; - < "top to bottom, then right"; 2; >; + < "left to right, then down"; SV_PRINT_PRT_NUP_ORDER_LRTD; >; + < "top to bottom, then right"; SV_PRINT_PRT_NUP_ORDER_TDLR; >; }; }; CheckBox SV_PRINT_PRT_NUP_BORDER_CB diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index ae578f8e5337..ac92ae56f8d0 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -106,7 +106,7 @@ bool WindowArranger::Element::isVisible() const sal_Int32 WindowArranger::Element::getExpandPriority() const { sal_Int32 nPrio = m_nExpandPriority; - if( m_pChild ) + if( m_pChild && m_nExpandPriority >= 0 ) { size_t nElements = m_pChild->countElements(); for( size_t i = 0; i < nElements; i++ ) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index f2b4ceb89c00..206f5d9f9ac4 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -151,6 +151,70 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi Invalidate(); } +PrintDialog::ShowNupOrderWindow::ShowNupOrderWindow( Window* i_pParent ) + : Window( i_pParent, WB_BORDER ) + , mnOrderMode( 0 ) + , mnRows( 1 ) + , mnColumns( 1 ) +{ + ImplInitSettings(); +} + +PrintDialog::ShowNupOrderWindow::~ShowNupOrderWindow() +{ +} + +void PrintDialog::ShowNupOrderWindow::ImplInitSettings() +{ + SetBackground( Wallpaper( GetSettings().GetStyleSettings().GetFieldColor() ) ); +} + +void PrintDialog::ShowNupOrderWindow::Paint( const Rectangle& i_rRect ) +{ + Window::Paint( i_rRect ); + SetMapMode( MAP_PIXEL ); + SetTextColor( GetSettings().GetStyleSettings().GetFieldTextColor() ); + + int nPages = mnRows * mnColumns; + Font aFont( GetSettings().GetStyleSettings().GetFieldFont() ); + aFont.SetSize( Size( 0, 24 ) ); + SetFont( aFont ); + Size aTextSize( GetTextWidth( rtl::OUString::valueOf( sal_Int32(nPages+1) ) ), GetTextHeight() ); + + Size aOutSize( GetOutputSizePixel() ); + Size aSubSize( aOutSize.Width() / mnColumns, aOutSize.Height() / mnRows ); + // calculate font size: shrink the sample text so it fits + double fX = double(aSubSize.Width())/double(aTextSize.Width()); + double fY = double(aSubSize.Height())/double(aTextSize.Height()); + double fScale = (fX < fY) ? fX : fY; + long nFontHeight = long(24.0*fScale) - 3; + if( nFontHeight < 5 ) + nFontHeight = 5; + aFont.SetSize( Size( 0, nFontHeight ) ); + SetFont( aFont ); + long nTextHeight = GetTextHeight(); + for( int i = 0; i < nPages; i++ ) + { + rtl::OUString aPageText( rtl::OUString::valueOf( sal_Int32(i+1) ) ); + int nX = 0, nY = 0; + switch( mnOrderMode ) + { + case SV_PRINT_PRT_NUP_ORDER_LRTD: + nX = (i % mnColumns); nY = (i / mnColumns); + break; + case SV_PRINT_PRT_NUP_ORDER_TDLR: + nX = (i / mnRows); nY = (i % mnRows); + break; + } + Size aTextSize( GetTextWidth( aPageText ), nTextHeight ); + int nDeltaX = (aSubSize.Width() - aTextSize.Width()) / 2; + int nDeltaY = (aSubSize.Height() - aTextSize.Height()) / 2; + DrawText( Point( nX * aSubSize.Width() + nDeltaX, + nY * aSubSize.Height() + nDeltaY ), + aPageText ); + } +} + PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maNupLine( this, VclResId( SV_PRINT_PRT_NUP_LAYOUT_FL ) ) @@ -168,10 +232,13 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maNupOrientationBox( this, VclResId( SV_PRINT_PRT_NUP_ORIENTATION_BOX ) ) , maNupOrderTxt( this, VclResId( SV_PRINT_PRT_NUP_ORDER_TXT ) ) , maNupOrderBox( this, VclResId( SV_PRINT_PRT_NUP_ORDER_BOX ) ) + , maNupOrderWin( this ) , maBorderCB( this, VclResId( SV_PRINT_PRT_NUP_BORDER_CB ) ) { FreeResource(); + maNupOrderWin.Show(); + // setup field units for metric fields const LocaleDataWrapper& rLocWrap( maPageMarginEdt.GetLocaleDataWrapper() ); FieldUnit eUnit = FUNIT_MM; @@ -223,15 +290,29 @@ void PrintDialog::NUpTabPage::setupLayout() maLayout.addWindow( &maNupLine ); boost::shared_ptr< vcl::RowOrColumn > xRow( new vcl::RowOrColumn( &maLayout, false ) ); maLayout.addChild( xRow ); + boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( xRow.get() ) ); + xRow->addChild( xIndent ); + + boost::shared_ptr< vcl::RowOrColumn > xShowNupCol( new vcl::RowOrColumn( xRow.get() ) ); + xRow->addChild( xShowNupCol, -1 ); + xShowNupCol->setMinimumSize( xShowNupCol->addWindow( &maNupOrderWin ), Size( 70, 70 ) ); + boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xShowNupCol.get() ) ); + xShowNupCol->addChild( xSpacer ); + + boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); + xIndent->setChild( xCol ); + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); xRow->addWindow( &maNupPagesTxt ); xRow->addWindow( &maNupPagesBox ); - boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( &maLayout ) ); - maLayout.addChild( xIndent ); + xIndent.reset( new vcl::Indenter( xCol.get() ) ); + xCol->addChild( xIndent ); // remember advanced controls to show/hide mxAdvancedControls = xIndent; - boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); + mxLayoutGroup = xCol; + xCol.reset( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); @@ -256,12 +337,12 @@ void PrintDialog::NUpTabPage::setupLayout() xRow->addWindow( &maNupOrientationTxt ); xRow->addWindow( &maNupOrientationBox ); - xRow.reset( new vcl::RowOrColumn( &maLayout, false ) ); - maLayout.addChild( xRow ); + xRow.reset( new vcl::RowOrColumn( mxLayoutGroup.get(), false ) ); + mxLayoutGroup->addChild( xRow ); xRow->addWindow( &maNupOrderTxt ); xRow->addWindow( &maNupOrderBox ); - maLayout.addWindow( &maBorderCB ); + mxLayoutGroup->addWindow( &maBorderCB ); // initially advanced controls are not show, rows=columns=1 mxAdvancedControls->show( false, false ); @@ -953,7 +1034,7 @@ void PrintDialog::setupOptionalUI() } else if( aGroupingHint.equalsAscii( "LayoutPage" ) ) { - pCurColumn = &maNUpPage.maLayout; + pCurColumn = maNUpPage.mxLayoutGroup.get(); pCurParent = &maNUpPage; // set layout page as current parent bOnStaticPage = true; } @@ -1473,16 +1554,19 @@ void PrintDialog::updateNup() aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); + int nOrderMode = int(maNUpPage.maNupOrderBox.GetEntryData( + maNUpPage.maNupOrderBox.GetSelectEntryPos() )); + if( nOrderMode == SV_PRINT_PRT_NUP_ORDER_LRTD ) + aMPS.nOrder = PrinterController::LRTB; + else if( nOrderMode == SV_PRINT_PRT_NUP_ORDER_TDLR ) + aMPS.nOrder = PrinterController::TBLR; + int nOrientationMode = int(maNUpPage.maNupOrientationBox.GetEntryData( maNUpPage.maNupOrientationBox.GetSelectEntryPos() )); if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE ) - { aMPS.aPaperSize = maNupLandscapeSize; - } else if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT ) - { aMPS.aPaperSize = maNupPortraitSize; - } else // automatic mode { // get size of first real page to see if it is portrait or landscape @@ -1498,6 +1582,8 @@ void PrintDialog::updateNup() maPController->setMultipage( aMPS ); + maNUpPage.maNupOrderWin.setValues( nOrderMode, nCols, nRows ); + preparePreview( true, true ); } @@ -1511,7 +1597,7 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) // update text fields updatePrinterText(); } - else if( pBox == &maNUpPage.maNupOrientationBox ) + else if( pBox == &maNUpPage.maNupOrientationBox || pBox == &maNUpPage.maNupOrderBox ) { updateNup(); } -- cgit From ea2ff673857fc3a973ab828ffb9b5b32a2c99689 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Jul 2009 15:11:07 +0000 Subject: #i92518# reverse print --- vcl/inc/vcl/print.hxx | 2 ++ vcl/source/gdi/print3.cxx | 29 ++++++++++++++++++++++++++++- vcl/source/src/print.src | 2 +- vcl/source/window/printdlg.cxx | 12 ++++++++++++ 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 128393f3dd3f..94680d10d3e7 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -497,6 +497,8 @@ public: SAL_DLLPRIVATE void setMultipage( const MultiPageSetup& ); SAL_DLLPRIVATE const MultiPageSetup& getMultipage() const; SAL_DLLPRIVATE void setLastPage( sal_Bool i_bLastPage ); + SAL_DLLPRIVATE void setReversePrint( sal_Bool i_bReverse ); + SAL_DLLPRIVATE bool getReversePrint() const; SAL_DLLPRIVATE void pushPropertiesToPrinter(); SAL_DLLPRIVATE void setJobState( com::sun::star::view::PrintableState ); }; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 27c326569bfb..72f955e428cb 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -152,6 +152,7 @@ public: Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; sal_Bool mbLastPage; + sal_Bool mbReversePageOrder; view::PrintableState meJobState; vcl::PrinterController::MultiPageSetup maMultiPage; @@ -162,6 +163,7 @@ public: ImplPrinterControllerData() : mbLastPage( sal_False ), + mbReversePageOrder( sal_False ), meJobState( view::PrintableState_JOB_STARTED ), mpProgress( NULL ) {} @@ -315,6 +317,14 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr } } + beans::PropertyValue* pReverseVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintReverse" ) ) ); + if( pReverseVal ) + { + sal_Bool bReverse = sal_False; + pReverseVal->Value >>= bReverse; + pController->setReversePrint( bReverse ); + } + // check if the printer brings up its own dialog // in that case leave the work to that dialog const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); @@ -654,6 +664,11 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o rMPS.nLeftMargin == 0 && rMPS.nRightMargin == 0 && rMPS.nTopMargin == 0 && rMPS.nBottomMargin == 0 ) { + if( mpImplData->mbReversePageOrder ) + { + int nDocPages = getPageCount(); + i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; + } return getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); } @@ -683,7 +698,9 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o { // map current sub page to real page int nPage = (i_nFilteredPage * nSubPages + nSubPage) / rMPS.nRepeat; - if( nPage < nDocPages ) + if( mpImplData->mbReversePageOrder ) + nPage = nDocPages - 1 - nPage; + if( nPage >= 0 && nPage < nDocPages ) { GDIMetaFile aPageFile; Size aPageSize = getPageFile( nPage, aPageFile, i_bMayUseCache ); @@ -846,6 +863,16 @@ void PrinterController::setLastPage( sal_Bool i_bLastPage ) mpImplData->mbLastPage = i_bLastPage; } +void PrinterController::setReversePrint( sal_Bool i_bReverse ) +{ + mpImplData->mbReversePageOrder = i_bReverse; +} + +bool PrinterController::getReversePrint() const +{ + return mpImplData->mbReversePageOrder; +} + Sequence< PropertyValue > PrinterController::getJobProperties( const Sequence< PropertyValue >& i_rMergeList ) const { std::hash_set< rtl::OUString, rtl::OUStringHash > aMergeSet; diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index e8d418555274..bb2c18af5146 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -305,7 +305,7 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 5, 35 ); Size = MAP_APPFONT( 150, 10 ); - Text [en-US] = "Print Range and Copies"; + Text [en-US] = "Range and Copies"; }; FixedText SV_PRINT_COPYCOUNT { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 206f5d9f9ac4..74b43a4f25aa 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -650,6 +650,9 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrgetReversePrint() ); + // get the first page preparePreview( true, true ); @@ -717,6 +720,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetReversePrint( bChecked ); + maPController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintReverse" ) ), + makeAny( bChecked ) ); + preparePreview( true, true ); + } else { if( pButton == &maJobPage.maSetupButton ) -- cgit From 8cee10d466e46d4f159e639809b7ceae4495355a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Jul 2009 17:31:08 +0000 Subject: #i92518# label cleanup --- vcl/inc/vcl/arrange.hxx | 39 +++++++++-- vcl/source/src/print.src | 2 + vcl/source/window/arrange.cxx | 148 ++++++++++++++++++++++++++++------------- vcl/source/window/printdlg.cxx | 72 +++++++++++--------- 4 files changed, 180 insertions(+), 81 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 3ef93311ee58..5278657b5294 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -113,7 +113,8 @@ namespace vcl // there can be only one parent window and all managed windows MUST // be direct children of that window // violating that condition will result in undefined behavior - virtual void setParentWindow( Window* ) = 0; + virtual void setParentWindow( Window* ); + virtual void setParent( WindowArranger* ); virtual size_t countElements() const = 0; @@ -192,7 +193,6 @@ namespace vcl virtual Size getOptimalSize( WindowSizeType ) const; virtual void resize(); - virtual void setParentWindow( Window* ); virtual size_t countElements() const { return m_aElements.size(); } // add a managed window at the given index @@ -207,6 +207,39 @@ namespace vcl void remove( boost::shared_ptr const & ); }; + class LabeledElement : public WindowArranger + { + WindowArranger::Element m_aLabel; + WindowArranger::Element m_aElement; + long m_nDistance; + protected: + virtual Element* getElement( size_t i_nIndex ) + { + if( i_nIndex == 0 ) + return &m_aLabel; + else if( i_nIndex == 1 ) + return &m_aElement; + return 0; + } + + public: + LabeledElement( WindowArranger* i_pParent = NULL, long i_nDistance = 5 ) + : WindowArranger( i_pParent ) + , m_nDistance( i_nDistance ) + {} + + virtual ~LabeledElement(); + + virtual Size getOptimalSize( WindowSizeType ) const; + virtual void resize(); + virtual size_t countElements() const { return 2; } + + void setLabel( Window* ); + void setLabel( boost::shared_ptr const & ); + void setElement( Window* ); + void setElement( boost::shared_ptr const & ); + }; + class Indenter : public WindowArranger { long m_nIndent; @@ -226,7 +259,6 @@ namespace vcl virtual Size getOptimalSize( WindowSizeType ) const; virtual void resize(); - virtual void setParentWindow( Window* ); virtual size_t countElements() const { return (m_aElement.m_pElement != 0 || m_aElement.m_pChild != 0) ? 1 : 0; } void setIndent( long i_nIndent ) @@ -319,7 +351,6 @@ namespace vcl virtual Size getOptimalSize( WindowSizeType ) const; virtual void resize(); - virtual void setParentWindow( Window* ); virtual size_t countElements() const { return m_aElements.size(); } // add a managed window at the given matrix position diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index bb2c18af5146..aab695f8bf93 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -145,6 +145,7 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 0, 0 ); Size = MAP_APPFONT( 10, 10 ); Text [en-US] = "P~ages"; + VCenter = TRUE; }; NumericField SV_PRINT_PRT_NUP_COLS_EDT { @@ -161,6 +162,7 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 10, 35 ); Size = MAP_APPFONT( 40, 10 ); Text [en-US] = "~by"; + VCenter = TRUE; }; NumericField SV_PRINT_PRT_NUP_ROWS_EDT { diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index ac92ae56f8d0..e09c34d9c1fb 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -53,6 +53,28 @@ void WindowArranger::setParent( WindowArranger* i_pParent ) setParentWindow( m_pParentWindow ); } +void WindowArranger::setParentWindow( Window* i_pNewParent ) +{ + m_pParentWindow = i_pNewParent; + + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + Element* pEle = getElement( i ); + if( pEle ) // sanity check + { + #if OSL_DEBUG_LEVEL > 0 + if( pEle->m_pElement ) + { + OSL_VERIFY( pEle->m_pElement->GetParent() == i_pNewParent ); + } + #endif + if( pEle->m_pChild ) + pEle->m_pChild->setParentWindow( i_pNewParent ); + } + } +} + void WindowArranger::show( bool i_bShow, bool i_bImmediateUpdate ) { size_t nEle = countElements(); @@ -341,23 +363,6 @@ void RowOrColumn::resize() } } -void RowOrColumn::setParentWindow( Window* i_pNewParent ) -{ - m_pParentWindow = i_pNewParent; - for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin(); - it != m_aElements.end(); ++it ) - { - #if OSL_DEBUG_LEVEL > 0 - if( it->m_pElement ) - { - OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent ); - } - #endif - if( it->m_pChild ) - it->m_pChild->setParentWindow( i_pNewParent ); - } -} - size_t RowOrColumn::addWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio, size_t i_nIndex ) { size_t nIndex = i_nIndex; @@ -426,6 +431,85 @@ void RowOrColumn::remove( boost::shared_ptr const & i_pChild ) } } +// ---------------------------------------- +// vcl::LabeledElement +//----------------------------------------- + +LabeledElement::~LabeledElement() +{ + m_aLabel.deleteChild(); + m_aElement.deleteChild(); +} + +Size LabeledElement::getOptimalSize( WindowSizeType i_eType ) const +{ + Size aRet( m_aLabel.getOptimalSize( WINDOWSIZE_MINIMUM ) ); + if( aRet.Width() != 0 ) + aRet.Width() += m_nDistance; + Size aElementSize( m_aElement.getOptimalSize( i_eType ) ); + aRet.Width() += aElementSize.Width(); + if( aElementSize.Height() > aRet.Height() ) + aRet.Height() = aElementSize.Height(); + if( aRet.Height() != 0 ) + aRet.Height() += 2*m_nOuterBorder; + + return aRet; +} + +void LabeledElement::resize() +{ + Size aLabelSize( m_aLabel.getOptimalSize( WINDOWSIZE_MINIMUM ) ); + Size aElementSize( m_aElement.getOptimalSize( WINDOWSIZE_PREFERRED ) ); + if( m_nDistance + aLabelSize.Width() + aElementSize.Width() > m_aManagedArea.GetWidth() ) + aElementSize = m_aElement.getOptimalSize( WINDOWSIZE_MINIMUM ); + + // align label and element vertically in LabeledElement + long nYOff = (m_aManagedArea.GetHeight() - 2*m_nOuterBorder - aLabelSize.Height()) / 2; + Point aPos( m_aManagedArea.Left(), + m_aManagedArea.Top() + m_nOuterBorder + nYOff ); + Size aSize( aLabelSize ); + if( m_aLabel.m_pElement ) + m_aLabel.m_pElement->SetPosSizePixel( aPos, aSize ); + else if( m_aLabel.m_pChild.get() ) + m_aLabel.m_pChild->setManagedArea( Rectangle( aPos, aSize ) ); + + aPos.X() += aSize.Width() + m_nDistance; + nYOff = (m_aManagedArea.GetHeight() - 2*m_nOuterBorder - aElementSize.Height()) / 2; + aPos.Y() = m_aManagedArea.Top() + m_nOuterBorder + nYOff; + aSize.Width() = aElementSize.Width(); + aSize.Height() = m_aManagedArea.GetHeight() - 2*m_nOuterBorder; + if( aPos.X() + aSize.Width() < m_aManagedArea.Right() ) + aSize.Width() = m_aManagedArea.Right() - aPos.X(); + if( m_aElement.m_pElement ) + m_aElement.m_pElement->SetPosSizePixel( aPos, aSize ); + else if( m_aElement.m_pChild.get() ) + m_aElement.m_pChild->setManagedArea( Rectangle( aPos, aSize ) ); +} + +void LabeledElement::setLabel( Window* i_pLabel ) +{ + m_aLabel.m_pElement = i_pLabel; + m_aLabel.m_pChild.reset(); +} + +void LabeledElement::setLabel( boost::shared_ptr const & i_pLabel ) +{ + m_aLabel.m_pElement = NULL; + m_aLabel.m_pChild = i_pLabel; +} + +void LabeledElement::setElement( Window* i_pElement ) +{ + m_aElement.m_pElement = i_pElement; + m_aElement.m_pChild.reset(); +} + +void LabeledElement::setElement( boost::shared_ptr const & i_pElement ) +{ + m_aElement.m_pElement = NULL; + m_aElement.m_pChild = i_pElement; +} + // ---------------------------------------- // vcl::Indenter //----------------------------------------- @@ -472,19 +556,6 @@ void Indenter::setChild( boost::shared_ptr const & i_pChild, sal m_aElement.m_nExpandPriority = i_nExpandPrio; } -void Indenter::setParentWindow( Window* i_pNewParent ) -{ - m_pParentWindow = i_pNewParent; - #if OSL_DEBUG_LEVEL > 0 - if( m_aElement.m_pElement ) - { - OSL_VERIFY( m_aElement.m_pElement->GetParent() == i_pNewParent ); - } - #endif - if( m_aElement.m_pChild ) - m_aElement.m_pChild->setParentWindow( i_pNewParent ); -} - // ---------------------------------------- // vcl::MatrixArranger //----------------------------------------- @@ -588,23 +659,6 @@ void MatrixArranger::resize() } } -void MatrixArranger::setParentWindow( Window* i_pNewParent ) -{ - m_pParentWindow = i_pNewParent; - for( std::vector< MatrixElement >::const_iterator it = m_aElements.begin(); - it != m_aElements.end(); ++it ) - { - #if OSL_DEBUG_LEVEL > 0 - if( it->m_pElement ) - { - OSL_VERIFY( it->m_pElement->GetParent() == i_pNewParent ); - } - #endif - if( it->m_pChild ) - it->m_pChild->setParentWindow( i_pNewParent ); - } -} - size_t MatrixArranger::addWindow( Window* i_pWindow, sal_uInt32 i_nX, sal_uInt32 i_nY, sal_Int32 i_nExpandPrio ) { sal_uInt64 nMapValue = getMap( i_nX, i_nY ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 74b43a4f25aa..9537b2a8eeab 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -301,10 +301,10 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); - xRow->addWindow( &maNupPagesTxt ); - xRow->addWindow( &maNupPagesBox ); + boost::shared_ptr< vcl::LabeledElement > xLabel( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maNupPagesTxt ); + xLabel->setElement( &maNupPagesBox ); xIndent.reset( new vcl::Indenter( xCol.get() ) ); xCol->addChild( xIndent ); @@ -322,25 +322,25 @@ void PrintDialog::NUpTabPage::setupLayout() xRow->addWindow( &maNupTimesTxt ); xRow->addWindow( &maNupRowsEdt ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); - xRow->addWindow( &maPageMarginTxt ); - xRow->addWindow( &maPageMarginEdt ); + xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maPageMarginTxt ); + xLabel->setElement( &maPageMarginEdt ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); - xRow->addWindow( &maSheetMarginTxt ); - xRow->addWindow( &maSheetMarginEdt ); + xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maSheetMarginTxt ); + xLabel->setElement( &maSheetMarginEdt ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); - xRow->addWindow( &maNupOrientationTxt ); - xRow->addWindow( &maNupOrientationBox ); + xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maNupOrientationTxt ); + xLabel->setElement( &maNupOrientationBox ); - xRow.reset( new vcl::RowOrColumn( mxLayoutGroup.get(), false ) ); - mxLayoutGroup->addChild( xRow ); - xRow->addWindow( &maNupOrderTxt ); - xRow->addWindow( &maNupOrderBox ); + xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maNupOrderTxt ); + xLabel->setElement( &maNupOrderBox ); mxLayoutGroup->addWindow( &maBorderCB ); @@ -485,14 +485,14 @@ void PrintDialog::JobTabPage::setupLayout() xRangeRow->addChild( xCopyCollateCol ); // add copies row to copy/collate column - boost::shared_ptr< vcl::RowOrColumn > xCopiesRow( new vcl::RowOrColumn( xCopyCollateCol.get(), false, 0 ) ); + boost::shared_ptr< vcl::LabeledElement > xCopiesRow( new vcl::LabeledElement( xCopyCollateCol.get() ) ); xCopyCollateCol->addChild( xCopiesRow ); - xCopiesRow->addWindow( &maCopyCount ); - xCopiesRow->addWindow( &maCopyCountField ); - boost::shared_ptr< vcl::RowOrColumn > xCollateRow( new vcl::RowOrColumn( xCopyCollateCol.get(), false, 0 ) ); + xCopiesRow->setLabel( &maCopyCount ); + xCopiesRow->setElement( &maCopyCountField ); + boost::shared_ptr< vcl::LabeledElement > xCollateRow( new vcl::LabeledElement( xCopyCollateCol.get() ) ); xCopyCollateCol->addChild( xCollateRow ); - xCollateRow->addWindow( &maCollateBox ); - xCollateRow->addWindow( &maCollateImage ); + xCollateRow->setLabel( &maCollateBox ); + xCollateRow->setElement( &maCollateImage ); maDetailsBtn.SetSymbol( SYMBOL_SPIN_DOWN ); maDetailsBtn.SetSmallSymbol(); @@ -1222,6 +1222,7 @@ void PrintDialog::setupOptionalUI() pCurColumn->addChild( pFieldColumn ); aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pFieldColumn ) ); + vcl::LabeledElement* pLabel = NULL; if( aText.getLength() ) { // add a FixedText: @@ -1234,7 +1235,9 @@ void PrintDialog::setupOptionalUI() setSmartId( pHeading, "FixedText", -1, aPropertyName ); // add to row - pFieldColumn->addWindow( pHeading ); + pLabel = new vcl::LabeledElement( pFieldColumn ); + pFieldColumn->addChild( pLabel ); + pLabel->setLabel( pHeading ); } if( aCtrlType.equalsAscii( "List" ) ) @@ -1266,7 +1269,10 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pList] = aPropertyName; // finish the pair - pFieldColumn->addWindow( pList ); + if( pLabel ) + pLabel->setElement( pList ); + else + pFieldColumn->addWindow( pList ); } else if( aCtrlType.equalsAscii( "Range" ) ) { @@ -1298,7 +1304,10 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pField] = aPropertyName; // add to row - pFieldColumn->addWindow( pField ); + if( pLabel ) + pLabel->setElement( pField ); + else + pFieldColumn->addWindow( pField ); } else if( aCtrlType.equalsAscii( "Edit" ) ) { @@ -1323,7 +1332,10 @@ void PrintDialog::setupOptionalUI() maControlToPropertyMap[pField] = aPropertyName; // add to row - pFieldColumn->addWindow( pField, 2 ); + if( pLabel ) + pLabel->setElement( pField ); + else + pFieldColumn->addWindow( pField, 2 ); } } else -- cgit From d88fd8b7532a5c5564044f27bac699c064ab1a75 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 30 Jul 2009 18:05:46 +0000 Subject: fix a warning --- vcl/source/window/printdlg.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9537b2a8eeab..7cf6a2696b63 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -179,13 +179,13 @@ void PrintDialog::ShowNupOrderWindow::Paint( const Rectangle& i_rRect ) Font aFont( GetSettings().GetStyleSettings().GetFieldFont() ); aFont.SetSize( Size( 0, 24 ) ); SetFont( aFont ); - Size aTextSize( GetTextWidth( rtl::OUString::valueOf( sal_Int32(nPages+1) ) ), GetTextHeight() ); + Size aSampleTextSize( GetTextWidth( rtl::OUString::valueOf( sal_Int32(nPages+1) ) ), GetTextHeight() ); Size aOutSize( GetOutputSizePixel() ); Size aSubSize( aOutSize.Width() / mnColumns, aOutSize.Height() / mnRows ); // calculate font size: shrink the sample text so it fits - double fX = double(aSubSize.Width())/double(aTextSize.Width()); - double fY = double(aSubSize.Height())/double(aTextSize.Height()); + double fX = double(aSubSize.Width())/double(aSampleTextSize.Width()); + double fY = double(aSubSize.Height())/double(aSampleTextSize.Height()); double fScale = (fX < fY) ? fX : fY; long nFontHeight = long(24.0*fScale) - 3; if( nFontHeight < 5 ) -- cgit From b80cb739622f8e2d3bf385249f950803c0e3c8ac Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 07:34:21 +0000 Subject: fix a warning --- vcl/source/window/printdlg.cxx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 7cf6a2696b63..d7f3b68611ef 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1570,15 +1570,15 @@ void PrintDialog::updateNup() aMPS.bDrawBorder = maNUpPage.maBorderCB.IsChecked(); - int nOrderMode = int(maNUpPage.maNupOrderBox.GetEntryData( - maNUpPage.maNupOrderBox.GetSelectEntryPos() )); + int nOrderMode = int(sal_IntPtr(maNUpPage.maNupOrderBox.GetEntryData( + maNUpPage.maNupOrderBox.GetSelectEntryPos() ))); if( nOrderMode == SV_PRINT_PRT_NUP_ORDER_LRTD ) aMPS.nOrder = PrinterController::LRTB; else if( nOrderMode == SV_PRINT_PRT_NUP_ORDER_TDLR ) aMPS.nOrder = PrinterController::TBLR; - int nOrientationMode = int(maNUpPage.maNupOrientationBox.GetEntryData( - maNUpPage.maNupOrientationBox.GetSelectEntryPos() )); + int nOrientationMode = int(sal_IntPtr(maNUpPage.maNupOrientationBox.GetEntryData( + maNUpPage.maNupOrientationBox.GetSelectEntryPos() ))); if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE ) aMPS.aPaperSize = maNupLandscapeSize; else if( nOrientationMode == SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT ) -- cgit From 592a5f3139812ee92f86e0f135da6f0c317f5624 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 11:38:53 +0000 Subject: #i92518# adjust button line margin --- vcl/inc/vcl/arrange.hxx | 28 ++++++++++++++++++++++--- vcl/source/window/arrange.cxx | 47 +++++++++++++++++++++--------------------- vcl/source/window/printdlg.cxx | 8 ++++--- 3 files changed, 53 insertions(+), 30 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index 5278657b5294..e5cc37245f98 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -61,12 +61,20 @@ namespace vcl sal_Int32 m_nExpandPriority; Size m_aMinSize; bool m_bHidden; + long m_nLeftBorder; + long m_nTopBorder; + long m_nRightBorder; + long m_nBottomBorder; Element() : m_pElement( NULL ) , m_pChild() , m_nExpandPriority( 0 ) , m_bHidden( false ) + , m_nLeftBorder( 0 ) + , m_nTopBorder( 0 ) + , m_nRightBorder( 0 ) + , m_nBottomBorder( 0 ) {} Element( Window* i_pWin, @@ -77,6 +85,10 @@ namespace vcl , m_pChild( i_pChild ) , m_nExpandPriority( i_nExpandPriority ) , m_bHidden( false ) + , m_nLeftBorder( 0 ) + , m_nTopBorder( 0 ) + , m_nRightBorder( 0 ) + , m_nBottomBorder( 0 ) {} void deleteChild() { m_pChild.reset(); } @@ -84,6 +96,7 @@ namespace vcl sal_Int32 getExpandPriority() const; Size getOptimalSize( WindowSizeType ) const; bool isVisible() const; + void setPosSize( const Point&, const Size& ); }; Window* m_pParentWindow; @@ -145,13 +158,22 @@ namespace vcl { Element* pEle = getElement( i_nIndex ); if( pEle ) - { pEle->m_aMinSize = i_rMinSize; - resize(); - } return pEle != NULL; } + void setBorders( size_t i_nIndex, long i_nLeft, long i_nTop, long i_nRight, long i_nBottom ) + { + Element* pEle = getElement( i_nIndex ); + if( pEle ) + { + pEle->m_nLeftBorder = i_nLeft; + pEle->m_nRightBorder = i_nRight; + pEle->m_nTopBorder = i_nTop; + pEle->m_nBottomBorder = i_nBottom; + } + } + void show( bool i_bShow = true, bool i_bImmediateUpdate = true ); void setManagedArea( const Rectangle& i_rArea ) diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index e09c34d9c1fb..5f8ef943271e 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -154,11 +154,27 @@ Size WindowArranger::Element::getOptimalSize( WindowSizeType i_eType ) const aResult.Width() = m_aMinSize.Width(); if( aResult.Height() < m_aMinSize.Height() ) aResult.Height() = m_aMinSize.Height(); + aResult.Width() += m_nLeftBorder + m_nRightBorder; + aResult.Height() += m_nTopBorder + m_nBottomBorder; } return aResult; } +void WindowArranger::Element::setPosSize( const Point& i_rPos, const Size& i_rSize ) +{ + Point aPoint( i_rPos ); + Size aSize( i_rSize ); + aPoint.X() += m_nLeftBorder; + aPoint.Y() += m_nTopBorder; + aSize.Width() -= m_nLeftBorder + m_nRightBorder; + aSize.Height() -= m_nTopBorder + m_nBottomBorder; + if( m_pElement ) + m_pElement->SetPosSizePixel( aPoint, aSize ); + else if( m_pChild ) + m_pChild->setManagedArea( Rectangle( aPoint, aSize ) ); +} + // ---------------------------------------- // vcl::RowOrColumn //----------------------------------------- @@ -332,10 +348,12 @@ void RowOrColumn::resize() long nExtraWidth = (m_bColumn ? m_aManagedArea.GetHeight() : m_aManagedArea.GetWidth()) - nUsedWidth; if( nExtraWidth > 0 ) + { if( m_bColumn ) distributeColumnHeight( aElementSizes, nUsedWidth, nExtraWidth ); else distributeRowWidth( aElementSizes, nUsedWidth, nExtraWidth ); + } // get starting position Point aElementPos( m_aManagedArea.TopLeft() ); @@ -348,14 +366,7 @@ void RowOrColumn::resize() { // get the size of type of the managed element - if( m_aElements[i].m_pElement ) // this actually is a window - { - m_aElements[i].m_pElement->SetPosSizePixel( aElementPos, aElementSizes[i] ); - } - else if( m_aElements[i].m_pChild ) - { - m_aElements[i].m_pChild->setManagedArea( Rectangle( aElementPos, aElementSizes[i] ) ); - } + m_aElements[i].setPosSize( aElementPos, aElementSizes[i] ); if( m_bColumn ) aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height(); else @@ -468,10 +479,7 @@ void LabeledElement::resize() Point aPos( m_aManagedArea.Left(), m_aManagedArea.Top() + m_nOuterBorder + nYOff ); Size aSize( aLabelSize ); - if( m_aLabel.m_pElement ) - m_aLabel.m_pElement->SetPosSizePixel( aPos, aSize ); - else if( m_aLabel.m_pChild.get() ) - m_aLabel.m_pChild->setManagedArea( Rectangle( aPos, aSize ) ); + m_aLabel.setPosSize( aPos, aSize ); aPos.X() += aSize.Width() + m_nDistance; nYOff = (m_aManagedArea.GetHeight() - 2*m_nOuterBorder - aElementSize.Height()) / 2; @@ -480,10 +488,7 @@ void LabeledElement::resize() aSize.Height() = m_aManagedArea.GetHeight() - 2*m_nOuterBorder; if( aPos.X() + aSize.Width() < m_aManagedArea.Right() ) aSize.Width() = m_aManagedArea.Right() - aPos.X(); - if( m_aElement.m_pElement ) - m_aElement.m_pElement->SetPosSizePixel( aPos, aSize ); - else if( m_aElement.m_pChild.get() ) - m_aElement.m_pChild->setManagedArea( Rectangle( aPos, aSize ) ); + m_aElement.setPosSize( aPos, aSize ); } void LabeledElement::setLabel( Window* i_pLabel ) @@ -535,10 +540,7 @@ void Indenter::resize() Size aSz( m_aManagedArea.GetSize() ); aSz.Width() -= 2*m_nOuterBorder + m_nIndent; aSz.Height() -= 2*m_nOuterBorder; - if( m_aElement.m_pElement ) - m_aElement.m_pElement->SetPosSizePixel( aPt, aSz ); - else if( m_aElement.m_pChild ) - m_aElement.m_pChild->setManagedArea( Rectangle( aPt, aSz ) ); + m_aElement.setPosSize( aPt, aSz ); } void Indenter::setWindow( Window* i_pWindow, sal_Int32 i_nExpandPrio ) @@ -652,10 +654,7 @@ void MatrixArranger::resize() { Point aCellPos( aColumnX[it->m_nX], aRowY[it->m_nY] ); Size aCellSize( aColumnWidths[it->m_nX], aRowHeights[it->m_nY] ); - if( it->m_pElement ) - it->m_pElement->SetPosSizePixel( aCellPos, aCellSize ); - else if( it->m_pChild ) - it->m_pChild->setManagedArea( Rectangle( aCellPos, aCellSize ) ); + it->setPosSize( aCellPos, aCellSize ); } } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index d7f3b68611ef..6e15d71117c3 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -394,6 +394,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maNoCollateImg( VclResId( SV_PRINT_NOCOLLATE_IMG ) ) , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) , mnCollateUIMode( 0 ) + , maLayout( NULL, true, 0 ) { FreeResource(); maPrinterFL.SMHID2( "JobPage", "Printer" ); @@ -784,10 +785,10 @@ void PrintDialog::setupLayout() Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); maLayout.setParentWindow( this ); - maLayout.setOuterBorder( aBorder.Width() ); boost::shared_ptr< vcl::RowOrColumn > xPreviewAndTab( new vcl::RowOrColumn( &maLayout, false ) ); - maLayout.addChild( xPreviewAndTab, 5 ); + size_t nIndex = maLayout.addChild( xPreviewAndTab, 5 ); + maLayout.setBorders( nIndex, aBorder.Width(), aBorder.Width(), aBorder.Width(), 0 ); // setup column for preview and sub controls boost::shared_ptr< vcl::RowOrColumn > xPreview( new vcl::RowOrColumn( xPreviewAndTab.get() ) ); @@ -811,7 +812,8 @@ void PrintDialog::setupLayout() // add the row for the buttons boost::shared_ptr< vcl::RowOrColumn > xButtons( new vcl::RowOrColumn( &maLayout, false ) ); - maLayout.addChild( xButtons ); + nIndex = maLayout.addChild( xButtons ); + maLayout.setBorders( nIndex, aBorder.Width(), 0, aBorder.Width(), aBorder.Width() ); // insert a spacer, buttons are right aligned xSpacer.reset( new vcl::Spacer( xButtons.get(), 2 ) ); -- cgit From 167cb4386db37471d9038e4b9d52a91d76885d79 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 12:02:23 +0000 Subject: #i92518# border for page preview --- vcl/source/window/printdlg.cxx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 6e15d71117c3..c25eff97d2d1 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -77,6 +77,9 @@ PrintDialog::PrintPreviewWindow::~PrintPreviewWindow() void PrintDialog::PrintPreviewWindow::Resize() { Size aNewSize( GetSizePixel() ); + // leave small space for decoration + aNewSize.Width() -= 2; + aNewSize.Height() -= 2; Size aScaledSize; double fScale = 1.0; if( maOrigSize.Width() > maOrigSize.Height() ) @@ -121,6 +124,10 @@ void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& ) SetMapMode( MAP_PIXEL ); maPageVDev.SetMapMode( MAP_PIXEL ); DrawOutDev( aOffset, aPreviewSize, Point( 0, 0 ), aPreviewSize, maPageVDev ); + + DecorationView aVw( this ); + aOffset.X() -= 1; aOffset.Y() -=1; aPreviewSize.Width() += 2; aPreviewSize.Height() += 2; + aVw.DrawFrame( Rectangle( aOffset, aPreviewSize ), FRAME_DRAW_GROUP ); } void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) -- cgit From 27324679eba1bc69f026a846b2605e8ccff71a35 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 12:23:00 +0000 Subject: #i92518# label layout, set correct tab page size --- vcl/inc/vcl/arrange.hxx | 4 +++- vcl/source/window/arrange.cxx | 17 +++++++++++++++-- vcl/source/window/printdlg.cxx | 14 +++++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index e5cc37245f98..e31be4ac8c67 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -234,6 +234,7 @@ namespace vcl WindowArranger::Element m_aLabel; WindowArranger::Element m_aElement; long m_nDistance; + int m_nLabelStyle; protected: virtual Element* getElement( size_t i_nIndex ) { @@ -245,9 +246,10 @@ namespace vcl } public: - LabeledElement( WindowArranger* i_pParent = NULL, long i_nDistance = 5 ) + LabeledElement( WindowArranger* i_pParent = NULL, int i_nLabelStyle = 0, long i_nDistance = 5 ) : WindowArranger( i_pParent ) , m_nDistance( i_nDistance ) + , m_nLabelStyle( i_nLabelStyle ) {} virtual ~LabeledElement(); diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 5f8ef943271e..8b3ed40db72e 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -486,8 +486,21 @@ void LabeledElement::resize() aPos.Y() = m_aManagedArea.Top() + m_nOuterBorder + nYOff; aSize.Width() = aElementSize.Width(); aSize.Height() = m_aManagedArea.GetHeight() - 2*m_nOuterBorder; - if( aPos.X() + aSize.Width() < m_aManagedArea.Right() ) - aSize.Width() = m_aManagedArea.Right() - aPos.X(); + + // label style + // 0: position left and right + // 1: keep the element close to label and grow it + // 2: keep the element close and don't grow it + if( m_nLabelStyle == 0) + { + if( aPos.X() + aSize.Width() < m_aManagedArea.Right() ) + aPos.X() = m_aManagedArea.Right() - aSize.Width(); + } + else if( m_nLabelStyle == 1 ) + { + if( aPos.X() + aSize.Width() < m_aManagedArea.Right() ) + aSize.Width() = m_aManagedArea.Right() - aPos.X(); + } m_aElement.setPosSize( aPos, aSize ); } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index c25eff97d2d1..48ffb3711ab3 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -324,10 +324,14 @@ void PrintDialog::NUpTabPage::setupLayout() xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); xCol->addChild( xRow ); - xRow->addWindow( &maNupNumPagesTxt ); - xRow->addWindow( &maNupColEdt ); - xRow->addWindow( &maNupTimesTxt ); - xRow->addWindow( &maNupRowsEdt ); + xLabel.reset( new vcl::LabeledElement( xRow.get() ) ); + xRow->addChild( xLabel, 1 ); + xLabel->setLabel( &maNupNumPagesTxt ); + xLabel->setElement( &maNupColEdt ); + xLabel.reset( new vcl::LabeledElement( xRow.get() ) ); + xRow->addChild( xLabel ); + xLabel->setLabel( &maNupTimesTxt ); + xLabel->setElement( &maNupRowsEdt ); xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); xCol->addChild( xLabel ); @@ -1405,7 +1409,7 @@ void PrintDialog::setupOptionalUI() for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); it != aDynamicColumns.end(); ++it ) { - (*it)->setManagedArea( Rectangle( Point(), aMaxPageSize ) ); + (*it)->setManagedArea( Rectangle( Point(), aTabSize ) ); delete *it; *it = NULL; } -- cgit From f6914ef7a3a9821fa0e81e0025dbc0752140fb92 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 12:39:45 +0000 Subject: #i92518# special handle PrintRange subgroups --- vcl/source/window/printdlg.cxx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 48ffb3711ab3..9e02de6908ab 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -807,7 +807,8 @@ void PrintDialog::setupLayout() xPreview->addWindow( &maPreviewWindow, 5 ); // get a row for the preview controls boost::shared_ptr< vcl::RowOrColumn > xPreviewCtrls( new vcl::RowOrColumn( xPreview.get(), false ) ); - xPreview->addChild( xPreviewCtrls ); + nIndex = xPreview->addChild( xPreviewCtrls ); + xPreview->setBorders( nIndex, aBorder.Width()*3, 0, aBorder.Width()*3, 0 ); xPreviewCtrls->addWindow( &maPageEdit ); xPreviewCtrls->addWindow( &maNumPagesText ); boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); @@ -1097,7 +1098,11 @@ void PrintDialog::setupOptionalUI() ! pCurColumn->countElements() == 0 ) { - FixedLine* pNewSub = new FixedLine( pCurParent ); + Window* pNewSub = NULL; + if( aGroupingHint.equalsAscii( "PrintRange" ) ) + pNewSub = new FixedText( pCurParent, WB_VCENTER ); + else + pNewSub = new FixedLine( pCurParent ); maControls.push_front( pNewSub ); pNewSub->SetText( aText ); pNewSub->Show(); -- cgit From d660523d686f1085077b44c9d1b5c79a1724b9d6 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 15:16:11 +0000 Subject: #i92518# lates UI changes --- vcl/inc/vcl/prndlg.hxx | 6 +- vcl/inc/vcl/svids.hrc | 32 ++++++----- vcl/source/src/print.src | 49 +++++++++++++--- vcl/source/window/printdlg.cxx | 123 ++++++++++++++++++++++++++++++++++------- vcl/source/window/window2.cxx | 1 - 5 files changed, 166 insertions(+), 45 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index cb472474aefc..6e3b4b0508c7 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -95,7 +95,9 @@ namespace vcl { public: FixedLine maNupLine; - FixedText maNupPagesTxt; + RadioButton maDefaultBtn; + RadioButton maBrochureBtn; + RadioButton maPagesBtn; ListBox maNupPagesBox; // controls for "Custom" page mode @@ -120,6 +122,7 @@ namespace vcl vcl::RowOrColumn maLayout; boost::shared_ptr< vcl::WindowArranger >mxAdvancedControls; boost::shared_ptr< vcl::RowOrColumn > mxLayoutGroup; + boost::shared_ptr< vcl::RowOrColumn > mxBrochureDep; void setupLayout(); @@ -129,6 +132,7 @@ namespace vcl void readFromSettings(); void storeToSettings(); void initFromMultiPageSetup( const vcl::PrinterController::MultiPageSetup& ); + void enableNupControls( bool bEnable ); virtual void Resize(); }; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 7550cb9106a7..9ce6d2781012 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -91,21 +91,23 @@ #define SV_PRINT_TAB_NUP 1 #define SV_PRINT_PRT_NUP_LAYOUT_FL 1 -#define SV_PRINT_PRT_NUP_PAGES_TXT 2 -#define SV_PRINT_PRT_NUP_PAGES_BOX 2 -#define SV_PRINT_PRT_NUP_NUM_PAGES_TXT 3 -#define SV_PRINT_PRT_NUP_COLS_EDT 4 -#define SV_PRINT_PRT_NUP_TIMES_TXT 5 -#define SV_PRINT_PRT_NUP_ROWS_EDT 6 -#define SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT 7 -#define SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT 8 -#define SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT 9 -#define SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT 10 -#define SV_PRINT_PRT_NUP_ORIENTATION_TXT 12 -#define SV_PRINT_PRT_NUP_ORIENTATION_BOX 13 -#define SV_PRINT_PRT_NUP_ORDER_TXT 14 -#define SV_PRINT_PRT_NUP_ORDER_BOX 15 -#define SV_PRINT_PRT_NUP_BORDER_CB 16 +#define SV_PRINT_PRT_NUP_DEFAULT_BTN 2 +#define SV_PRINT_PRT_NUP_BROCHURE_BTN 3 +#define SV_PRINT_PRT_NUP_PAGES_BTN 4 +#define SV_PRINT_PRT_NUP_PAGES_BOX 5 +#define SV_PRINT_PRT_NUP_NUM_PAGES_TXT 6 +#define SV_PRINT_PRT_NUP_COLS_EDT 7 +#define SV_PRINT_PRT_NUP_TIMES_TXT 8 +#define SV_PRINT_PRT_NUP_ROWS_EDT 9 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT 10 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT 11 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT 12 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT 13 +#define SV_PRINT_PRT_NUP_ORIENTATION_TXT 14 +#define SV_PRINT_PRT_NUP_ORIENTATION_BOX 15 +#define SV_PRINT_PRT_NUP_ORDER_TXT 16 +#define SV_PRINT_PRT_NUP_ORDER_BOX 17 +#define SV_PRINT_PRT_NUP_BORDER_CB 18 #define SV_PRINT_PRT_NUP_ORIENTATION_AUTOMATIC 0 #define SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT 1 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index aab695f8bf93..a7be46fa6a59 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -67,6 +67,7 @@ ModalDialog SV_DLG_PRINT SVLook = TRUE; Spin = FALSE; Border = TRUE; + HelpText [en-US] = "Select page to display in preview."; }; FixedText SV_PRINT_PAGE_TXT { @@ -79,11 +80,13 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 95, 140 ); Size = MAP_APPFONT( 15, 12 ); + HelpText [en-US] = "Scroll one page forward."; }; PushButton SV_PRINT_PAGE_BACKWARD { Pos = MAP_APPFONT( 80, 140 ); Size = MAP_APPFONT( 15, 12 ); + HelpText [en-US] = "Scroll one page backward."; }; TabControl SV_PRINT_TABCTRL { @@ -116,11 +119,25 @@ ModalDialog SV_DLG_PRINT Size = MAP_APPFONT( 150, 10 ); Text [en-US] = "Layout"; }; - FixedText SV_PRINT_PRT_NUP_PAGES_TXT + RadioButton SV_PRINT_PRT_NUP_DEFAULT_BTN { - Pos = MAP_APPFONT( 10, 20 ); - Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Pages per ~sheet"; + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "~Default"; + HelpText [en-US] = "Print one page per sheet of paper."; + }; + RadioButton SV_PRINT_PRT_NUP_BROCHURE_BTN + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text = ""; + }; + RadioButton SV_PRINT_PRT_NUP_PAGES_BTN + { + Pos = MAP_APPFONT( 0, 0 ); + Size = MAP_APPFONT( 10, 10 ); + Text [en-US] = "Pa~ges per sheet"; + HelpText [en-US] = "Print multiple pages per sheet of paper."; }; ListBox SV_PRINT_PRT_NUP_PAGES_BOX { @@ -129,6 +146,7 @@ ModalDialog SV_DLG_PRINT Border = TRUE; DropDown = TRUE; CurPos = 0; + HelpText [en-US] = "Select how many pages to print per sheet of paper."; StringList [en-US] = { < "1"; 1; >; @@ -156,12 +174,13 @@ ModalDialog SV_DLG_PRINT Minimum = 1; Maximum = 32; Value = 1; + HelpText [en-US] = "Select number of columns."; }; FixedText SV_PRINT_PRT_NUP_TIMES_TXT { Pos = MAP_APPFONT( 10, 35 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~by"; + Text [en-US] = "b~y"; VCenter = TRUE; }; NumericField SV_PRINT_PRT_NUP_ROWS_EDT @@ -173,12 +192,13 @@ ModalDialog SV_DLG_PRINT Minimum = 1; Maximum = 32; Value = 1; + HelpText [en-US] = "Select number of rows."; }; FixedText SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT { Pos = MAP_APPFONT( 10, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "~Margin between pages"; + Text [en-US] = "Margin between ~pages"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT { @@ -188,12 +208,13 @@ ModalDialog SV_DLG_PRINT Border = TRUE; Value = 0; Unit = FUNIT_MM; + HelpText [en-US] = "Select margin between individual pages on each sheet of paper."; }; FixedText SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT { Pos = MAP_APPFONT( 110, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Ma~rgin to sheet border"; + Text [en-US] = "Margin to ~sheet border"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT { @@ -203,6 +224,7 @@ ModalDialog SV_DLG_PRINT Border = TRUE; Value = 0; Unit = FUNIT_MM; + HelpText [en-US] = "Select margin between the printed pages and paper edge."; }; FixedText SV_PRINT_PRT_NUP_ORIENTATION_TXT { @@ -223,6 +245,7 @@ ModalDialog SV_DLG_PRINT < "Portrait"; SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT; >; < "Landscape"; SV_PRINT_PRT_NUP_ORIENTATION_LANDSCAPE; >; }; + HelpText [en-US] = "Select the orientation of the paper."; }; FixedText SV_PRINT_PRT_NUP_ORDER_TXT { @@ -242,12 +265,14 @@ ModalDialog SV_DLG_PRINT < "left to right, then down"; SV_PRINT_PRT_NUP_ORDER_LRTD; >; < "top to bottom, then right"; SV_PRINT_PRT_NUP_ORDER_TDLR; >; }; + HelpText [en-US] = "Select order in which pages are to be printed."; }; CheckBox SV_PRINT_PRT_NUP_BORDER_CB { Pos = MAP_APPFONT( 10, 65 ); Size = MAP_APPFONT( 150, 12 ); - Text [en-US] = "~Draw a Border around each page"; + Text [en-US] = "Draw a border around each page"; + HelpText [en-US] = "Check to draw a border around each page."; }; }; @@ -267,11 +292,13 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 100, 80 ); Border = TRUE; + HelpText [en-US] = "Select the printer to print on."; }; PushButton SV_PRINT_DETAILS_BTN { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 5, 5 ); + HelpText [en-US] = "Show/Hide detailed information of the selected printer."; }; FixedText SV_PRINT_DETAILS_TXT { @@ -302,6 +329,7 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 115, 5 ); Size = MAP_APPFONT( 50, 15 ); Text [en-US] = "Properties..."; + HelpText [en-US] = "Call the setup dialog of the selected printer."; }; FixedLine SV_PRINT_COPIES { @@ -324,6 +352,7 @@ ModalDialog SV_DLG_PRINT Minimum = 1; Maximum = 16384; Value = 1; + HelpText [en-US] = "Select the number of copies to be produced."; }; FixedImage SV_PRINT_COLLATE_IMAGE { @@ -335,6 +364,7 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 95, 45 ); Size = MAP_APPFONT( 70, 10 ); Text [en-US] = "Collate"; + HelpText [en-US] = "Select whether copies should be collated or not."; }; Image SV_PRINT_COLLATE_IMG @@ -374,18 +404,21 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 10, 20 ); Size = MAP_APPFONT( 200, 12 ); Text [en-US] = "Print to ~file"; + HelpText [en-US] = "Check to send output to a file instead of the actual printer."; }; CheckBox SV_PRINT_OPT_SINGLEJOBS { Pos = MAP_APPFONT( 10, 35 ); Size = MAP_APPFONT( 200, 12 ); Text [en-US] = "~Create single print jobs for collated output"; + HelpText [en-US] = "Check to not rely on the printer to create collated copies but create a print job for each copy instead."; }; CheckBox SV_PRINT_OPT_REVERSE { Pos = MAP_APPFONT( 10, 50 ); Size = MAP_APPFONT( 200, 12 ); Text [en-US] = "Print in ~reverse page order"; + HelpText [en-US] = "Check to print pages in reverse order."; }; }; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 9e02de6908ab..6613f16a798b 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -225,7 +225,9 @@ void PrintDialog::ShowNupOrderWindow::Paint( const Rectangle& i_rRect ) PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maNupLine( this, VclResId( SV_PRINT_PRT_NUP_LAYOUT_FL ) ) - , maNupPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_PAGES_TXT ) ) + , maDefaultBtn( this, VclResId( SV_PRINT_PRT_NUP_DEFAULT_BTN ) ) + , maBrochureBtn( this, VclResId( SV_PRINT_PRT_NUP_BROCHURE_BTN ) ) + , maPagesBtn( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BTN ) ) , maNupPagesBox( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BOX ) ) , maNupNumPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_NUM_PAGES_TXT ) ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLS_EDT ) ) @@ -245,6 +247,9 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) FreeResource(); maNupOrderWin.Show(); + maDefaultBtn.Check( TRUE ); + maBrochureBtn.Show( FALSE ); + enableNupControls( false ); // setup field units for metric fields const LocaleDataWrapper& rLocWrap( maPageMarginEdt.GetLocaleDataWrapper() ); @@ -264,7 +269,9 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maSheetMarginEdt.SetDecimalDigits( nDigits ); maNupLine.SMHID2("NUpPage", "Layout"); - maNupPagesTxt.SMHID2( "NUpPage", "PagesPerSheet" ); + maDefaultBtn.SMHID2("NUpPage", "Default" ); + maBrochureBtn.SMHID2("NUpPage", "Brochure" ); + maPagesBtn.SMHID2( "NUpPage", "PagesPerSheet" ); maNupPagesBox.SMHID2( "NUpPage", "PagesPerSheetBox" ); maNupNumPagesTxt.SMHID2( "NUpPage", "Columns" ); maNupColEdt.SMHID2( "NUpPage", "ColumnsBox" ); @@ -287,6 +294,25 @@ PrintDialog::NUpTabPage::~NUpTabPage() { } +void PrintDialog::NUpTabPage::enableNupControls( bool bEnable ) +{ + maNupPagesBox.Enable( bEnable ); + maNupNumPagesTxt.Enable( bEnable ); + maNupColEdt.Enable( bEnable ); + maNupTimesTxt.Enable( bEnable ); + maNupRowsEdt.Enable( bEnable ); + maPageMarginTxt.Enable( bEnable ); + maPageMarginEdt.Enable( bEnable ); + maSheetMarginTxt.Enable( bEnable ); + maSheetMarginEdt.Enable( bEnable ); + maNupOrientationTxt.Enable( bEnable ); + maNupOrientationBox.Enable( bEnable ); + maNupOrderTxt.Enable( bEnable ); + maNupOrderBox.Enable( bEnable ); + maNupOrderWin.Enable( bEnable ); + maBorderCB.Enable( bEnable ); +} + void PrintDialog::NUpTabPage::setupLayout() { Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); @@ -308,22 +334,37 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); + xCol->addWindow( &maDefaultBtn ); + xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); + xCol->addChild( xRow ); + xRow->addWindow( &maBrochureBtn ); + // remember brochure row for dependencies + mxBrochureDep = xRow; boost::shared_ptr< vcl::LabeledElement > xLabel( new vcl::LabeledElement( xCol.get() ) ); xCol->addChild( xLabel ); - xLabel->setLabel( &maNupPagesTxt ); + xLabel->setLabel( &maPagesBtn ); xLabel->setElement( &maNupPagesBox ); xIndent.reset( new vcl::Indenter( xCol.get() ) ); xCol->addChild( xIndent ); - // remember advanced controls to show/hide - mxAdvancedControls = xIndent; mxLayoutGroup = xCol; xCol.reset( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); + boost::shared_ptr< vcl::RowOrColumn > xAdvCol( new vcl::RowOrColumn( xCol.get() ) ); + xCol->addChild( xAdvCol ); + // remember advanced controls to show/hide + mxAdvancedControls = xAdvCol; + + xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); + xCol->addChild( xLabel ); + xLabel->setLabel( &maNupOrderTxt ); + xLabel->setElement( &maNupOrderBox ); + xCol->addWindow( &maBorderCB ); + + xRow.reset( new vcl::RowOrColumn( xAdvCol.get(), false ) ); + xAdvCol->addChild( xRow ); xLabel.reset( new vcl::LabeledElement( xRow.get() ) ); xRow->addChild( xLabel, 1 ); xLabel->setLabel( &maNupNumPagesTxt ); @@ -333,28 +374,21 @@ void PrintDialog::NUpTabPage::setupLayout() xLabel->setLabel( &maNupTimesTxt ); xLabel->setElement( &maNupRowsEdt ); - xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); + xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); + xAdvCol->addChild( xLabel ); xLabel->setLabel( &maPageMarginTxt ); xLabel->setElement( &maPageMarginEdt ); - xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); + xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); + xAdvCol->addChild( xLabel ); xLabel->setLabel( &maSheetMarginTxt ); xLabel->setElement( &maSheetMarginEdt ); - xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); + xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); + xAdvCol->addChild( xLabel ); xLabel->setLabel( &maNupOrientationTxt ); xLabel->setElement( &maNupOrientationBox ); - xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); - xLabel->setLabel( &maNupOrderTxt ); - xLabel->setElement( &maNupOrderBox ); - - mxLayoutGroup->addWindow( &maBorderCB ); - // initially advanced controls are not show, rows=columns=1 mxAdvancedControls->show( false, false ); } @@ -733,6 +767,8 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetChild( pCurColumn ); } + // EVIL + else if( aCtrlType.equalsAscii( "Bool" ) && + aGroupingHint.equalsAscii( "LayoutPage" ) && + aPropertyName.equalsAscii( "PrintBrochure" ) + ) + { + maNUpPage.maBrochureBtn.SetText( aText ); + maNUpPage.maBrochureBtn.Show(); + setHelpText( &maNUpPage.maBrochureBtn, aHelpTexts, 0 ); + + sal_Bool bVal = sal_False; + PropertyValue* pVal = maPController->getValue( aPropertyName ); + if( pVal ) + pVal->Value >>= bVal; + maNUpPage.maBrochureBtn.Check( bVal ); + maNUpPage.maBrochureBtn.Enable( maPController->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); + maNUpPage.maBrochureBtn.SetToggleHdl( LINK( this, PrintDialog, ClickHdl ) ); + + maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, &maNUpPage.maBrochureBtn ) ); + maControlToPropertyMap[&maNUpPage.maBrochureBtn] = aPropertyName; + + aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, maNUpPage.mxBrochureDep.get() ) ); + } else { vcl::RowOrColumn* pSaveCurColumn = pCurColumn; @@ -1710,6 +1769,30 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maOKButton.SetText( maOptionsPage.maToFileBox.IsChecked() ? maPrintToFileText : maPrintText ); maLayout.resize(); } + else if( pButton == &maNUpPage.maDefaultBtn ) + { + maNUpPage.enableNupControls( false ); + } + else if( pButton == &maNUpPage.maBrochureBtn ) + { + PropertyValue* pVal = getValueForWindow( pButton ); + if( pVal ) + { + sal_Bool bVal = maNUpPage.maBrochureBtn.IsChecked(); + pVal->Value <<= bVal; + + checkOptionalControlDependencies(); + + // update preview and page settings + preparePreview(); + } + if( maNUpPage.maBrochureBtn.IsChecked() ) + maNUpPage.enableNupControls( false ); + } + else if( pButton == &maNUpPage.maPagesBtn ) + { + maNUpPage.enableNupControls( true ); + } else if( pButton == &maJobPage.maDetailsBtn ) { bool bShow = ! maJobPage.maStatusTxt.IsVisible(); diff --git a/vcl/source/window/window2.cxx b/vcl/source/window/window2.cxx index d70f607a6cc6..af2043fda516 100644 --- a/vcl/source/window/window2.cxx +++ b/vcl/source/window/window2.cxx @@ -1459,7 +1459,6 @@ ULONG Window::GetHelpId() const void Window::SetSmartHelpId( const SmartId& aId, SmartIdUpdateMode aMode ) { - mpWindowImpl->maHelpText = String(); // create SmartId if required if ( (aMode == SMART_SET_STR) || (aMode == SMART_SET_ALL) || ( (aMode == SMART_SET_SMART) && aId.HasString() ) ) { -- cgit From 555cb390d2bffdd7fde2e86e3141f83a2f63017a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 1 Aug 2009 15:43:09 +0000 Subject: #i92518# lates UI changes --- vcl/source/src/print.src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index a7be46fa6a59..673f1f00e54e 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -452,7 +452,7 @@ StringArray SV_PRINT_NATIVE_STRINGS ItemList [en-US] = { < "Preview"; >; - < "Page Number"; >; + < "Page number"; >; < "Number of pages"; >; < "More"; >; }; -- cgit From aa1bc916363ca7ad301aea22bb2e162aadad784b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 3 Aug 2009 11:26:33 +0000 Subject: #i92518# latest fashion updates --- vcl/inc/vcl/prndlg.hxx | 4 +- vcl/source/window/printdlg.cxx | 157 ++++++++++++++++++++++------------------- 2 files changed, 85 insertions(+), 76 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 6e3b4b0508c7..3f82c6aef266 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -95,9 +95,8 @@ namespace vcl { public: FixedLine maNupLine; - RadioButton maDefaultBtn; - RadioButton maBrochureBtn; RadioButton maPagesBtn; + RadioButton maBrochureBtn; ListBox maNupPagesBox; // controls for "Custom" page mode @@ -245,6 +244,7 @@ namespace vcl Size getJobPageSize(); void updateNup(); + void updateNupFromPages(); void preparePreview( bool i_bPrintChanged = true, bool i_bMayUseCache = false ); void setPreviewText( sal_Int32 ); void updatePrinterText(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 6613f16a798b..4bd358035cb6 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -225,9 +225,8 @@ void PrintDialog::ShowNupOrderWindow::Paint( const Rectangle& i_rRect ) PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) : TabPage( i_pParent, rResId ) , maNupLine( this, VclResId( SV_PRINT_PRT_NUP_LAYOUT_FL ) ) - , maDefaultBtn( this, VclResId( SV_PRINT_PRT_NUP_DEFAULT_BTN ) ) - , maBrochureBtn( this, VclResId( SV_PRINT_PRT_NUP_BROCHURE_BTN ) ) , maPagesBtn( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BTN ) ) + , maBrochureBtn( this, VclResId( SV_PRINT_PRT_NUP_BROCHURE_BTN ) ) , maNupPagesBox( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BOX ) ) , maNupNumPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_NUM_PAGES_TXT ) ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLS_EDT ) ) @@ -247,9 +246,8 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) FreeResource(); maNupOrderWin.Show(); - maDefaultBtn.Check( TRUE ); + maPagesBtn.Check( TRUE ); maBrochureBtn.Show( FALSE ); - enableNupControls( false ); // setup field units for metric fields const LocaleDataWrapper& rLocWrap( maPageMarginEdt.GetLocaleDataWrapper() ); @@ -269,7 +267,6 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maSheetMarginEdt.SetDecimalDigits( nDigits ); maNupLine.SMHID2("NUpPage", "Layout"); - maDefaultBtn.SMHID2("NUpPage", "Default" ); maBrochureBtn.SMHID2("NUpPage", "Brochure" ); maPagesBtn.SMHID2( "NUpPage", "PagesPerSheet" ); maNupPagesBox.SMHID2( "NUpPage", "PagesPerSheetBox" ); @@ -323,7 +320,7 @@ void PrintDialog::NUpTabPage::setupLayout() maLayout.addWindow( &maNupLine ); boost::shared_ptr< vcl::RowOrColumn > xRow( new vcl::RowOrColumn( &maLayout, false ) ); maLayout.addChild( xRow ); - boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( xRow.get() ) ); + boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( xRow.get(), 3*aBorder.Width() ) ); xRow->addChild( xIndent ); boost::shared_ptr< vcl::RowOrColumn > xShowNupCol( new vcl::RowOrColumn( xRow.get() ) ); @@ -332,24 +329,19 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xShowNupCol.get() ) ); xShowNupCol->addChild( xSpacer ); - boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); - xIndent->setChild( xCol ); - xCol->addWindow( &maDefaultBtn ); - xRow.reset( new vcl::RowOrColumn( xCol.get(), false ) ); - xCol->addChild( xRow ); - xRow->addWindow( &maBrochureBtn ); - // remember brochure row for dependencies - mxBrochureDep = xRow; - boost::shared_ptr< vcl::LabeledElement > xLabel( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); + boost::shared_ptr< vcl::RowOrColumn > xMainCol( new vcl::RowOrColumn( xIndent.get() ) ); + xIndent->setChild( xMainCol ); + + boost::shared_ptr< vcl::LabeledElement > xLabel( new vcl::LabeledElement( xMainCol.get() ) ); + xMainCol->addChild( xLabel ); xLabel->setLabel( &maPagesBtn ); xLabel->setElement( &maNupPagesBox ); - xIndent.reset( new vcl::Indenter( xCol.get() ) ); - xCol->addChild( xIndent ); + xIndent.reset( new vcl::Indenter( xMainCol.get() ) ); + xMainCol->addChild( xIndent ); - mxLayoutGroup = xCol; - xCol.reset( new vcl::RowOrColumn( xIndent.get() ) ); + mxLayoutGroup = xMainCol; + boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); xIndent->setChild( xCol ); boost::shared_ptr< vcl::RowOrColumn > xAdvCol( new vcl::RowOrColumn( xCol.get() ) ); @@ -389,6 +381,15 @@ void PrintDialog::NUpTabPage::setupLayout() xLabel->setLabel( &maNupOrientationTxt ); xLabel->setElement( &maNupOrientationBox ); + xRow.reset( new vcl::RowOrColumn( xMainCol.get(), false ) ); + xMainCol->addChild( xRow ); + xRow->addWindow( &maBrochureBtn ); + // remember brochure row for dependencies + mxBrochureDep = xRow; + + xSpacer.reset( new vcl::Spacer( xMainCol.get(), 0, Size( 10, 2*aBorder.Width() ) ) ); + xMainCol->addChild( xSpacer ); + // initially advanced controls are not show, rows=columns=1 mxAdvancedControls->show( false, false ); } @@ -439,7 +440,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maNoCollateImg( VclResId( SV_PRINT_NOCOLLATE_IMG ) ) , maNoCollateHCImg( VclResId( SV_PRINT_NOCOLLATE_HC_IMG ) ) , mnCollateUIMode( 0 ) - , maLayout( NULL, true, 0 ) + , maLayout( NULL, true ) { FreeResource(); maPrinterFL.SMHID2( "JobPage", "Printer" ); @@ -767,7 +768,6 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrshow( bCustom ); + + updateNup(); +} + void PrintDialog::updateNup() { int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); @@ -1696,54 +1750,7 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) } else if( pBox == &maNUpPage.maNupPagesBox ) { - long nPages = long(maNUpPage.maNupPagesBox.GetEntryData(maNUpPage.maNupPagesBox.GetSelectEntryPos())); - int nRows = int(maNUpPage.maNupRowsEdt.GetValue()); - int nCols = int(maNUpPage.maNupColEdt.GetValue()); - long nPageMargin = long(maNUpPage.maPageMarginEdt.Denormalize(maNUpPage.maPageMarginEdt.GetValue( FUNIT_100TH_MM ))); - long nSheetMargin = long(maNUpPage.maSheetMarginEdt.Denormalize(maNUpPage.maSheetMarginEdt.GetValue( FUNIT_100TH_MM ))); - bool bCustom = false; - - if( nPages == 1 ) - { - nRows = nCols = 1; - nSheetMargin = 0; - } - else if( nPages == 2 || nPages == 4 || nPages == 6 || nPages == 9 || nPages == 16 ) - { - Size aJobPageSize( getJobPageSize() ); - bool bPortrait = aJobPageSize.Width() < aJobPageSize.Height(); - if( nPages == 2 ) - { - if( bPortrait ) - nRows = 1, nCols = 2; - else - nRows = 2, nCols = 1; - } - else if( nPages == 4 ) - nRows = nCols = 2; - else if( nPages == 6 ) - { - if( bPortrait ) - nRows = 2, nCols = 3; - else - nRows = 3, nCols = 2; - } - else if( nPages == 9 ) - nRows = nCols = 3; - else if( nPages == 16 ) - nRows = nCols = 4; - nPageMargin = 500; - nSheetMargin = 500; - } - else - bCustom = true; - - maNUpPage.maNupRowsEdt.SetValue( nRows ); - maNUpPage.maNupColEdt.SetValue( nCols ); - maNUpPage.maPageMarginEdt.SetValue( maNUpPage.maPageMarginEdt.Normalize( nPageMargin ), FUNIT_100TH_MM ); - maNUpPage.maSheetMarginEdt.SetValue( maNUpPage.maSheetMarginEdt.Normalize( nSheetMargin ), FUNIT_100TH_MM ); - updateNup(); - maNUpPage.mxAdvancedControls->show( bCustom ); + updateNupFromPages(); } return 0; @@ -1769,10 +1776,6 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) maOKButton.SetText( maOptionsPage.maToFileBox.IsChecked() ? maPrintToFileText : maPrintText ); maLayout.resize(); } - else if( pButton == &maNUpPage.maDefaultBtn ) - { - maNUpPage.enableNupControls( false ); - } else if( pButton == &maNUpPage.maBrochureBtn ) { PropertyValue* pVal = getValueForWindow( pButton ); @@ -1787,11 +1790,17 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) preparePreview(); } if( maNUpPage.maBrochureBtn.IsChecked() ) + { + maNUpPage.maNupPagesBox.SelectEntryPos( 0 ); + updateNupFromPages(); + maNUpPage.mxAdvancedControls->show( false ); maNUpPage.enableNupControls( false ); + } } else if( pButton == &maNUpPage.maPagesBtn ) { maNUpPage.enableNupControls( true ); + updateNupFromPages(); } else if( pButton == &maJobPage.maDetailsBtn ) { -- cgit From 360a88378c48cba41958327bb05c8d82f82ba234 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 3 Aug 2009 15:15:39 +0000 Subject: #i92518# latest fashion updates --- vcl/source/window/printdlg.cxx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 4bd358035cb6..902c2213681d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -320,7 +320,7 @@ void PrintDialog::NUpTabPage::setupLayout() maLayout.addWindow( &maNupLine ); boost::shared_ptr< vcl::RowOrColumn > xRow( new vcl::RowOrColumn( &maLayout, false ) ); maLayout.addChild( xRow ); - boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( xRow.get(), 3*aBorder.Width() ) ); + boost::shared_ptr< vcl::Indenter > xIndent( new vcl::Indenter( xRow.get() ) ); xRow->addChild( xIndent ); boost::shared_ptr< vcl::RowOrColumn > xShowNupCol( new vcl::RowOrColumn( xRow.get() ) ); @@ -337,7 +337,7 @@ void PrintDialog::NUpTabPage::setupLayout() xLabel->setLabel( &maPagesBtn ); xLabel->setElement( &maNupPagesBox ); - xIndent.reset( new vcl::Indenter( xMainCol.get() ) ); + xIndent.reset( new vcl::Indenter( xMainCol.get(), 3*aBorder.Width() ) ); xMainCol->addChild( xIndent ); mxLayoutGroup = xMainCol; @@ -381,6 +381,9 @@ void PrintDialog::NUpTabPage::setupLayout() xLabel->setLabel( &maNupOrientationTxt ); xLabel->setElement( &maNupOrientationBox ); + xSpacer.reset( new vcl::Spacer( xMainCol.get(), 0, Size( 10, aBorder.Width() ) ) ); + xMainCol->addChild( xSpacer ); + xRow.reset( new vcl::RowOrColumn( xMainCol.get(), false ) ); xMainCol->addChild( xRow ); xRow->addWindow( &maBrochureBtn ); -- cgit From a793801516881bf70ffbf7dcb8284d53a0f2246d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 3 Aug 2009 15:51:37 +0000 Subject: #i92518# latest fashion updates --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/inc/vcl/svids.hrc | 23 +++++++++--------- vcl/source/src/print.src | 5 ++++ vcl/source/window/printdlg.cxx | 55 +++++++++++++++++++++++++++++++++--------- 4 files changed, 61 insertions(+), 23 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 3f82c6aef266..5cf9faac5b9c 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -205,6 +205,7 @@ namespace vcl OKButton maOKButton; CancelButton maCancelButton; + HelpButton maHelpButton; PrintPreviewWindow maPreviewWindow; NumericField maPageEdit; FixedText maNumPagesText; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 9ce6d2781012..5ec6ff3d9901 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -77,17 +77,18 @@ #define SV_DLG_PRINT 2048 #define SV_PRINT_OK 1 #define SV_PRINT_CANCEL 2 -#define SV_PRINT_PAGE_PREVIEW 3 -#define SV_PRINT_PAGE_TXT 4 -#define SV_PRINT_PAGE_FORWARD 5 -#define SV_PRINT_PAGE_BACKWARD 6 -#define SV_PRINT_PAGE_EDIT 7 -#define SV_PRINT_TABCTRL 8 -#define SV_PRINT_PRT_TYPE 9 -#define SV_PRINT_PRT_STATUS 10 -#define SV_PRINT_PRT_LOCATION 11 -#define SV_PRINT_PRT_COMMENT 12 -#define SV_PRINT_TOFILE_TXT 13 +#define SV_PRINT_HELP 3 +#define SV_PRINT_PAGE_PREVIEW 4 +#define SV_PRINT_PAGE_TXT 5 +#define SV_PRINT_PAGE_FORWARD 6 +#define SV_PRINT_PAGE_BACKWARD 7 +#define SV_PRINT_PAGE_EDIT 8 +#define SV_PRINT_TABCTRL 9 +#define SV_PRINT_PRT_TYPE 10 +#define SV_PRINT_PRT_STATUS 11 +#define SV_PRINT_PRT_LOCATION 12 +#define SV_PRINT_PRT_COMMENT 13 +#define SV_PRINT_TOFILE_TXT 14 #define SV_PRINT_TAB_NUP 1 #define SV_PRINT_PRT_NUP_LAYOUT_FL 1 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 673f1f00e54e..a7cd7bc237e0 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -53,6 +53,11 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 295, 195 ); Size = MAP_APPFONT( 50, 15 ); }; + HelpButton SV_PRINT_HELP + { + Pos = MAP_APPFONT( 5, 5 ); + Size = MAP_APPFONT( 50, 15 ); + }; Window SV_PRINT_PAGE_PREVIEW { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 902c2213681d..eeb42437f47a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -44,6 +44,7 @@ #include "vcl/configsettings.hxx" #include "vcl/help.hxx" #include "vcl/decoview.hxx" +#include "vcl/svapp.hxx" #include "unotools/localedatawrapper.hxx" @@ -393,7 +394,7 @@ void PrintDialog::NUpTabPage::setupLayout() xSpacer.reset( new vcl::Spacer( xMainCol.get(), 0, Size( 10, 2*aBorder.Width() ) ) ); xMainCol->addChild( xSpacer ); - // initially advanced controls are not show, rows=columns=1 + // initially advanced controls are not shown, rows=columns=1 mxAdvancedControls->show( false, false ); } @@ -663,6 +664,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr 1 maCancelButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); #endif + maHelpButton.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maForwardBtn.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maBackwardBtn.SetClickHdl( LINK( this, PrintDialog, ClickHdl ) ); maJobPage.maCollateBox.SetToggleHdl( LINK( this, PrintDialog, ClickHdl ) ); @@ -866,10 +869,12 @@ void PrintDialog::setupLayout() nIndex = maLayout.addChild( xButtons ); maLayout.setBorders( nIndex, aBorder.Width(), 0, aBorder.Width(), aBorder.Width() ); - // insert a spacer, buttons are right aligned + Size aMinSize( maCancelButton.GetSizePixel() ); + // insert help button + xButtons->setMinimumSize( xButtons->addWindow( &maHelpButton ), aMinSize ); + // insert a spacer, cancel and OK buttons are right aligned xSpacer.reset( new vcl::Spacer( xButtons.get(), 2 ) ); xButtons->addChild( xSpacer ); - Size aMinSize( maCancelButton.GetSizePixel() ); xButtons->setMinimumSize( xButtons->addWindow( &maOKButton ), aMinSize ); xButtons->setMinimumSize( xButtons->addWindow( &maCancelButton ), aMinSize ); } @@ -958,6 +963,14 @@ static void setHelpText( Window* i_pWindow, const Sequence< rtl::OUString >& i_r i_pWindow->SetHelpText( i_rHelpTexts.getConstArray()[i_nIndex] ); } +void updateMaxSize( const Size& i_rCheckSize, Size& o_rMaxSize ) +{ + if( i_rCheckSize.Width() > o_rMaxSize.Width() ) + o_rMaxSize.Width() = i_rCheckSize.Width(); + if( i_rCheckSize.Height() > o_rMaxSize.Height() ) + o_rMaxSize.Height() = i_rCheckSize.Height(); +} + void PrintDialog::setupOptionalUI() { Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); @@ -1436,21 +1449,17 @@ void PrintDialog::setupOptionalUI() // calculate job page Size aMaxSize = maJobPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ); + // and layout page + updateMaxSize( maNUpPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ), aMaxSize ); + // and options page + updateMaxSize( maOptionsPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ), aMaxSize ); - Size aMaxPageSize; for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); it != aDynamicColumns.end(); ++it ) { Size aPageSize( (*it)->getOptimalSize( WINDOWSIZE_PREFERRED ) ); - if( aPageSize.Width() > aMaxPageSize.Width() ) - aMaxPageSize.Width() = aPageSize.Width(); - if( aPageSize.Height() > aMaxPageSize.Height() ) - aMaxPageSize.Height() = aPageSize.Height(); + updateMaxSize( aPageSize, aMaxSize ); } - if( aMaxPageSize.Width() > aMaxSize.Width() ) - aMaxSize.Width() = aMaxPageSize.Width(); - if( aMaxPageSize.Height() > aMaxSize.Height() ) - aMaxSize.Height() = aMaxPageSize.Height(); // resize dialog if necessary Size aTabSize = maTabCtrl.GetTabPageSizePixel(); @@ -1679,6 +1688,18 @@ void PrintDialog::updateNupFromPages() maNUpPage.maSheetMarginEdt.SetValue( maNUpPage.maSheetMarginEdt.Normalize( nSheetMargin ), FUNIT_100TH_MM ); maNUpPage.mxAdvancedControls->show( bCustom ); + if( bCustom ) + { + // see if we have to enlarge the dialog to make the tab page fit + Size aCurSize( maNUpPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ) ); + Size aTabSize( maTabCtrl.GetTabPageSizePixel() ); + if( aTabSize.Height() < aCurSize.Height() ) + { + Size aDlgSize( GetSizePixel() ); + aDlgSize.Height() += aCurSize.Height() - aTabSize.Height(); + SetSizePixel( aDlgSize ); + } + } updateNup(); } @@ -1766,6 +1787,16 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) storeToSettings(); EndDialog( pButton == &maOKButton ); } + else if( pButton == &maHelpButton ) + { + // start help system + Help* pHelp = Application::GetHelp(); + if( pHelp ) + { + // FIXME: find out proper help URL and use here + pHelp->Start( 0, GetParent() ); + } + } else if( pButton == &maForwardBtn ) { previewForward(); -- cgit From e22c6a289e98b6ee7889b41851cad6fff5b67361 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Aug 2009 14:46:00 +0000 Subject: #i103253# #i103252# fix headless printing, duplicate free --- vcl/aqua/source/gdi/salprn.cxx | 10 ++++++++-- vcl/source/gdi/print3.cxx | 9 ++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 7a5b0c7ba483..b3bc494bde17 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -40,6 +40,7 @@ #include "vcl/salptype.hxx" #include "vcl/print.hxx" #include "vcl/unohelp.hxx" +#include "vcl/svapp.hxx" #include @@ -545,6 +546,8 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, beans::PropertyValue* pMonitor = i_rController.getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); if( pMonitor ) pMonitor->Value >>= bShowProgressPanel; + if( Application::IsHeadlessModeEnabled() ) + bShowProgressPanel = sal_False; // FIXME: jobStarted() should be done after the print dialog has ended (if there is one) // how do I know when that might be ? @@ -607,7 +610,10 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, [pPrintDict setObject: [[NSNumber numberWithInt: (int)i_rController.getPrinter()->GetCopyCount()] autorelease] forKey: NSPrintCopies]; [pPrintDict setObject: [[NSNumber numberWithBool: YES] autorelease] forKey: NSPrintDetailedErrorReporting]; [pPrintDict setObject: [[NSNumber numberWithInt: 1] autorelease] forKey: NSPrintFirstPage]; - [pPrintDict setObject: [[NSNumber numberWithInt: mnCurPageRangeCount] autorelease] forKey: NSPrintLastPage]; + // #i103253# weird: for some reason, autoreleasing the value below like the others above + // leads do a double free malloc error. Why this value should behave differently from all the others + // is a mystery. + [pPrintDict setObject: [NSNumber numberWithInt: mnCurPageRangeCount] forKey: NSPrintLastPage]; // create print operation @@ -616,7 +622,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( pPrintOperation ) { NSObject* pReleaseAfterUse = nil; - bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() ); + bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() && ! Application::IsHeadlessModeEnabled() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: bShowProgressPanel ? YES : NO]; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 72f955e428cb..8251c5f2f506 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -267,7 +267,7 @@ void Printer::PrintJob( const boost::shared_ptr& i_pControlle ) { sal_Bool bSynchronous = sal_False; - beans::PropertyValue* pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + beans::PropertyValue* pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Wait" ) ) ); if( pVal ) pVal->Value >>= bSynchronous; @@ -329,7 +329,10 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr // in that case leave the work to that dialog const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); bool bIsQuick = rQuick.Len() && rQuick.EqualsIgnoreCaseAscii( "true" ); - if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && ! bIsQuick ) + if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && + ! bIsQuick && + ! Application::IsHeadlessModeEnabled() + ) { try { @@ -1108,7 +1111,7 @@ void PrinterController::createProgressDialog() if( pMonitor ) pMonitor->Value >>= bShow; - if( bShow ) + if( bShow && ! Application::IsHeadlessModeEnabled() ) { mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCount() ); mpImplData->mpProgress->Show(); -- cgit From 4bcda09aeec59e01797f96a163f408b642491a46 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Aug 2009 15:02:39 +0000 Subject: #i96606# fix API print (no dialogs) --- vcl/aqua/source/gdi/salprn.cxx | 5 ++--- vcl/inc/vcl/print.hxx | 2 ++ vcl/source/gdi/print3.cxx | 11 ++++++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index b3bc494bde17..d68c026d5ebe 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -40,7 +40,6 @@ #include "vcl/salptype.hxx" #include "vcl/print.hxx" #include "vcl/unohelp.hxx" -#include "vcl/svapp.hxx" #include @@ -546,7 +545,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, beans::PropertyValue* pMonitor = i_rController.getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); if( pMonitor ) pMonitor->Value >>= bShowProgressPanel; - if( Application::IsHeadlessModeEnabled() ) + if( ! i_rController.isShowDialogs() ) bShowProgressPanel = sal_False; // FIXME: jobStarted() should be done after the print dialog has ended (if there is one) @@ -622,7 +621,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( pPrintOperation ) { NSObject* pReleaseAfterUse = nil; - bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() && ! Application::IsHeadlessModeEnabled() ); + bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() && i_rController.isShowDialogs() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: bShowProgressPanel ? YES : NO]; diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 94680d10d3e7..789571bc7d0e 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -486,6 +486,8 @@ public: void abortJob(); + bool isShowDialogs() const; + // implementation details, not usable outside vcl SAL_DLLPRIVATE int getFilteredPageCount(); SAL_DLLPRIVATE Size getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 8251c5f2f506..c7ad36a48d7c 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -331,7 +331,7 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr bool bIsQuick = rQuick.Len() && rQuick.EqualsIgnoreCaseAscii( "true" ); if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && ! bIsQuick && - ! Application::IsHeadlessModeEnabled() + pController->isShowDialogs() ) { try @@ -1143,6 +1143,15 @@ void PrinterController::pushPropertiesToPrinter() mpImplData->mpPrinter->SetCopyCount( static_cast(nCopyCount), bCollate ); } +bool PrinterController::isShowDialogs() const +{ + sal_Bool bApi = sal_False; + const com::sun::star::beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsApi" ) ) ); + if( pVal ) + pVal->Value >>= bApi; + return ! bApi && ! Application::IsHeadlessModeEnabled(); +} + /* * PrinterOptionsHelper **/ -- cgit From 712176f85a73d77d7cfef92350ebfaa3d30ef79f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Aug 2009 15:46:46 +0000 Subject: get rid of old cruft --- vcl/aqua/inc/salprn.h | 7 ++-- vcl/aqua/source/gdi/salprn.cxx | 22 ++++------- vcl/inc/vcl/print.hxx | 2 +- vcl/inc/vcl/salprn.hxx | 4 +- vcl/os2/inc/salprn.h | 4 +- vcl/os2/source/gdi/salprn.cxx | 4 +- vcl/source/gdi/print.cxx | 82 ---------------------------------------- vcl/source/gdi/print3.cxx | 21 +++++++--- vcl/unx/headless/svpprn.hxx | 4 +- vcl/unx/inc/salprn.h | 4 +- vcl/unx/source/gdi/salprnpsp.cxx | 15 ++------ vcl/win/inc/salprn.h | 4 +- vcl/win/source/gdi/salprn.cxx | 4 +- 13 files changed, 52 insertions(+), 125 deletions(-) diff --git a/vcl/aqua/inc/salprn.h b/vcl/aqua/inc/salprn.h index a572641dd59e..bf9c3c25bc87 100644 --- a/vcl/aqua/inc/salprn.h +++ b/vcl/aqua/inc/salprn.h @@ -106,8 +106,7 @@ class AquaSalInfoPrinter : public SalInfoPrinter const String& rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterController& i_rController, - bool bIsQuickJob ); + vcl::PrinterController& i_rController ); BOOL EndJob(); BOOL AbortJob(); SalGraphics* StartPage( ImplJobSetup* i_pSetupData, BOOL i_bNewJobData ); @@ -142,7 +141,9 @@ class AquaSalPrinter : public SalPrinter virtual BOOL StartJob( const XubString* i_pFileName, const XubString& i_rJobName, const XubString& i_rAppName, - ULONG i_nCopies, BOOL i_bCollate, + ULONG i_nCopies, + bool i_bCollate, + bool i_bDirect, ImplJobSetup* i_pSetupData ); // implement pull model print system virtual BOOL StartJob( const String* i_pFileName, diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index d68c026d5ebe..6575f89d3fa0 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -519,8 +519,8 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, const String& i_rJobName, const String& i_rAppName, ImplJobSetup* i_pSetupData, - vcl::PrinterController& i_rController, - bool bIsQuickJob ) + vcl::PrinterController& i_rController + ) { if( mbJob ) return FALSE; @@ -621,7 +621,7 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, if( pPrintOperation ) { NSObject* pReleaseAfterUse = nil; - bool bShowPanel = (! bIsQuickJob && getUseNativeDialog() && i_rController.isShowDialogs() ); + bool bShowPanel = (! i_rController.isDirectPrint() && getUseNativeDialog() && i_rController.isShowDialogs() ); [pPrintOperation setShowsPrintPanel: bShowPanel ? YES : NO ]; [pPrintOperation setShowsProgressPanel: bShowProgressPanel ? YES : NO]; @@ -736,17 +736,7 @@ BOOL AquaSalPrinter::StartJob( const String* i_pFileName, ImplJobSetup* i_pSetupData, vcl::PrinterController& i_rController ) { - bool bIsQuickJob = false; - std::hash_map< rtl::OUString, rtl::OUString, rtl::OUStringHash >::const_iterator quick_it = - i_pSetupData->maValueMap.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ); - - if( quick_it != i_pSetupData->maValueMap.end() ) - { - if( quick_it->second.equalsIgnoreAsciiCaseAscii( "true" ) ) - bIsQuickJob = true; - } - - return mpInfoPrinter->StartJob( i_pFileName, i_rJobName, i_rAppName, i_pSetupData, i_rController, bIsQuickJob ); + return mpInfoPrinter->StartJob( i_pFileName, i_rJobName, i_rAppName, i_pSetupData, i_rController ); } // ----------------------------------------------------------------------- @@ -754,7 +744,9 @@ BOOL AquaSalPrinter::StartJob( const String* i_pFileName, BOOL AquaSalPrinter::StartJob( const XubString* i_pFileName, const XubString& i_rJobName, const XubString& i_rAppName, - ULONG i_nCopies, BOOL i_bCollate, + ULONG i_nCopies, + bool i_bCollate, + bool i_bDirect, ImplJobSetup* i_pSetupData ) { DBG_ERROR( "should never be called" ); diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 789571bc7d0e..d5d42466b611 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -270,7 +270,6 @@ private: private: SAL_DLLPRIVATE void ImplEndPrint(); - SAL_DLLPRIVATE BOOL StartJob( const XubString& rJobName ); SAL_DLLPRIVATE BOOL EndJob(); SAL_DLLPRIVATE Printer( const Printer& rPrinter ); SAL_DLLPRIVATE Printer& operator =( const Printer& rPrinter ); @@ -487,6 +486,7 @@ public: void abortJob(); bool isShowDialogs() const; + bool isDirectPrint() const; // implementation details, not usable outside vcl SAL_DLLPRIVATE int getFilteredPageCount(); diff --git a/vcl/inc/vcl/salprn.hxx b/vcl/inc/vcl/salprn.hxx index 4ffa969a674f..73f5454457cf 100644 --- a/vcl/inc/vcl/salprn.hxx +++ b/vcl/inc/vcl/salprn.hxx @@ -116,7 +116,9 @@ public: // public for Sal Implementation virtual BOOL StartJob( const String* pFileName, const String& rJobName, const String& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ) = 0; // implement for pull model print systems only, diff --git a/vcl/os2/inc/salprn.h b/vcl/os2/inc/salprn.h index bddb29f61442..2c95965bc609 100644 --- a/vcl/os2/inc/salprn.h +++ b/vcl/os2/inc/salprn.h @@ -135,7 +135,9 @@ public: virtual BOOL StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/os2/source/gdi/salprn.cxx b/vcl/os2/source/gdi/salprn.cxx index b8207ed317f2..a31a4bb779f8 100644 --- a/vcl/os2/source/gdi/salprn.cxx +++ b/vcl/os2/source/gdi/salprn.cxx @@ -1559,7 +1559,9 @@ Os2SalPrinter::~Os2SalPrinter() BOOL Os2SalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ) { DEVOPENSTRUC aDevOpenStruc; diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index 0ff5f283b5fa..eee954076278 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -1257,88 +1257,6 @@ IMPL_LINK( Printer, ImplDestroyPrinterAsync, void*, pSalPrinter ) // ----------------------------------------------------------------------- -BOOL Printer::StartJob( const XubString& rJobName ) -{ - mnError = PRINTER_OK; - - if ( IsDisplayPrinter() ) - return FALSE; - - if ( IsJobActive() || IsPrinting() ) - return FALSE; - - ULONG nCopies = mnCopyCount; - BOOL bCollateCopy = mbCollateCopy; - BOOL bUserCopy = FALSE; - if ( nCopies > 1 ) - { - ULONG nDevCopy; - - if ( bCollateCopy ) - nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COLLATECOPIES ); - else - nDevCopy = GetCapabilities( PRINTER_CAPABILITIES_COPIES ); - - // Muessen Kopien selber gemacht werden? - if ( nCopies > nDevCopy ) - { - bUserCopy = TRUE; - nCopies = 1; - bCollateCopy = FALSE; - } - } - else - bCollateCopy = FALSE; - - ImplSVData* pSVData = ImplGetSVData(); - mpPrinter = pSVData->mpDefInst->CreatePrinter( mpInfoPrinter ); - - if ( !mpPrinter ) - return FALSE; - - XubString* pPrintFile; - if ( mbPrintFile ) - pPrintFile = &maPrintFile; - else - pPrintFile = NULL; - - // #125075# StartJob can Reschedule on Windows, sfx - // depends on IsPrinting() in case of closing a document - BOOL bSaveNewJobSetup = mbNewJobSetup; - mbNewJobSetup = FALSE; - String aSaveJobName = maJobName; - maJobName = rJobName; - mnCurPage = 1; - mnCurPrintPage = 1; - mbPrinting = TRUE; - - if( ! ImplGetSVData()->maGDIData.mbPrinterPullModel ) - { - if ( !mpPrinter->StartJob( pPrintFile, rJobName, Application::GetDisplayName(), - nCopies, bCollateCopy, - maJobSetup.ImplGetConstData() ) ) - { - mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); - if ( !mnError ) - mnError = PRINTER_GENERALERROR; - pSVData->mpDefInst->DestroyPrinter( mpPrinter ); - mbNewJobSetup = bSaveNewJobSetup; - maJobName = aSaveJobName; - mnCurPage = 0; - mnCurPrintPage = 0; - mbPrinting = FALSE; - mpPrinter = NULL; - return FALSE; - } - } - - mbJobActive = TRUE; - - return TRUE; -} - -// ----------------------------------------------------------------------- - BOOL Printer::EndJob() { BOOL bRet = FALSE; diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index c7ad36a48d7c..1888fbdcad49 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -327,10 +327,8 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr // check if the printer brings up its own dialog // in that case leave the work to that dialog - const String& rQuick( i_rInitSetup.GetValue( String( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ) ); - bool bIsQuick = rQuick.Len() && rQuick.EqualsIgnoreCaseAscii( "true" ); if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && - ! bIsQuick && + ! pController->isDirectPrint() && pController->isShowDialogs() ) { @@ -382,8 +380,8 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptr 1 ) { @@ -475,7 +473,9 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrStartJob( pPrintFile, i_rJobName, Application::GetDisplayName(), - nCopies, bCollateCopy, + nCopies, + bCollateCopy, + i_pController->isDirectPrint(), maJobSetup.ImplGetConstData() ) ) { mbJobActive = TRUE; @@ -1152,6 +1152,15 @@ bool PrinterController::isShowDialogs() const return ! bApi && ! Application::IsHeadlessModeEnabled(); } +bool PrinterController::isDirectPrint() const +{ + sal_Bool bDirect = sal_False; + const com::sun::star::beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDirect" ) ) ); + if( pVal ) + pVal->Value >>= bDirect; + return bDirect == sal_True; +} + /* * PrinterOptionsHelper **/ diff --git a/vcl/unx/headless/svpprn.hxx b/vcl/unx/headless/svpprn.hxx index 154273f6da88..8f5a47fed118 100644 --- a/vcl/unx/headless/svpprn.hxx +++ b/vcl/unx/headless/svpprn.hxx @@ -90,7 +90,9 @@ public: virtual BOOL StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/unx/inc/salprn.h b/vcl/unx/inc/salprn.h index b1c92300ac49..59a5c3eef56a 100644 --- a/vcl/unx/inc/salprn.h +++ b/vcl/unx/inc/salprn.h @@ -90,7 +90,9 @@ public: virtual BOOL StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/unx/source/gdi/salprnpsp.cxx b/vcl/unx/source/gdi/salprnpsp.cxx index dcdb3431ce59..d47e30a89633 100644 --- a/vcl/unx/source/gdi/salprnpsp.cxx +++ b/vcl/unx/source/gdi/salprnpsp.cxx @@ -928,7 +928,9 @@ BOOL PspSalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pJobSetup ) { vcl_sal::PrinterUpdate::jobStarted(); @@ -990,15 +992,6 @@ BOOL PspSalPrinter::StartJob( } m_aPrinterGfx.Init( m_aJobData ); - bool bIsQuickJob = false; - std::hash_map< rtl::OUString, rtl::OUString, rtl::OUStringHash >::const_iterator quick_it = - pJobSetup->maValueMap.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsQuickJob" ) ) ); - if( quick_it != pJobSetup->maValueMap.end() ) - { - if( quick_it->second.equalsIgnoreAsciiCaseAscii( "true" ) ) - bIsQuickJob = true; - } - // set/clear backwards compatibility flag bool bStrictSO52Compatibility = false; std::hash_map::const_iterator compat_it = @@ -1011,7 +1004,7 @@ BOOL PspSalPrinter::StartJob( } m_aPrinterGfx.setStrictSO52Compatibility( bStrictSO52Compatibility ); - return m_aPrintJob.StartJob( m_aTmpFile.Len() ? m_aTmpFile : m_aFileName, nMode, rJobName, rAppName, m_aJobData, &m_aPrinterGfx, bIsQuickJob ) ? TRUE : FALSE; + return m_aPrintJob.StartJob( m_aTmpFile.Len() ? m_aTmpFile : m_aFileName, nMode, rJobName, rAppName, m_aJobData, &m_aPrinterGfx, bDirect ) ? TRUE : FALSE; } // ----------------------------------------------------------------------- diff --git a/vcl/win/inc/salprn.h b/vcl/win/inc/salprn.h index 09473cf518e0..890ff70bc3d6 100644 --- a/vcl/win/inc/salprn.h +++ b/vcl/win/inc/salprn.h @@ -116,7 +116,9 @@ public: virtual BOOL StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ); virtual BOOL EndJob(); virtual BOOL AbortJob(); diff --git a/vcl/win/source/gdi/salprn.cxx b/vcl/win/source/gdi/salprn.cxx index 7b0dfaf1fa98..8fe9b5d8f4d0 100644 --- a/vcl/win/source/gdi/salprn.cxx +++ b/vcl/win/source/gdi/salprn.cxx @@ -1966,7 +1966,9 @@ static int lcl_StartDocA( HDC hDC, DOCINFOA* pInfo, WinSalPrinter* pPrt ) BOOL WinSalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString&, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool bDirect, ImplJobSetup* pSetupData ) { mnError = 0; -- cgit From aafa25d0a440418cbcff23521862eadcc3c1466f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 5 Aug 2009 16:16:07 +0000 Subject: get rid of old cruft --- vcl/unx/headless/svpprn.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vcl/unx/headless/svpprn.cxx b/vcl/unx/headless/svpprn.cxx index a0834ed40be6..94d857e230b8 100644 --- a/vcl/unx/headless/svpprn.cxx +++ b/vcl/unx/headless/svpprn.cxx @@ -845,7 +845,9 @@ BOOL PspSalPrinter::StartJob( const XubString* pFileName, const XubString& rJobName, const XubString& rAppName, - ULONG nCopies, BOOL bCollate, + ULONG nCopies, + bool bCollate, + bool /*bDirect*/, ImplJobSetup* pJobSetup ) { vcl_sal::PrinterUpdate::jobStarted(); -- cgit From cda2521771d4166377f72a811e1801337954b22d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 6 Aug 2009 09:00:23 +0000 Subject: #i92516# fix a layout problem, fix a warning --- vcl/source/window/printdlg.cxx | 55 ++++-------------------------------------- vcl/win/source/gdi/salprn.cxx | 2 +- 2 files changed, 6 insertions(+), 51 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index eeb42437f47a..3395e4aff62d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -580,6 +580,7 @@ void PrintDialog::JobTabPage::readFromSettings() rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Collate" ) ) ); maCollateBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); } + Resize(); } void PrintDialog::JobTabPage::storeToSettings() @@ -1489,6 +1490,10 @@ void PrintDialog::setupOptionalUI() delete *it; *it = NULL; } + maJobPage.Resize(); + maNUpPage.Resize(); + maOptionsPage.Resize(); + Resize(); } void PrintDialog::checkControlDependencies() @@ -2029,57 +2034,7 @@ void PrintDialog::Command( const CommandEvent& rEvt ) void PrintDialog::Resize() { - #if 0 - Size aPixDiff( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); - Size aWindowSize( GetOutputSizePixel() ); - - // position buttons from lower end, right to left - Size aBtnSize( maCancelButton.GetSizePixel() ); - Rectangle aBtnRect( Point( aWindowSize.Width() - aPixDiff.Width() - aBtnSize.Width(), - aWindowSize.Height() - aPixDiff.Height() - aBtnSize.Height() ), - aBtnSize ); - maCancelButton.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - aBtnSize = maOKButton.GetSizePixel(); - aBtnRect = Rectangle( Point( aBtnRect.Left() - aPixDiff.Width() - aBtnSize.Width(), - aWindowSize.Height() - aPixDiff.Height() - aBtnSize.Height() ), - aBtnSize ); - maOKButton.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - aBtnSize = maButtonLine.GetSizePixel(); - - // position fixed line above buttons - aBtnRect = Rectangle( Point( 0, aBtnRect.Top() - aPixDiff.Width() - aBtnSize.Height()/2 ), - Size( aWindowSize.Width(), aBtnSize.Height() ) ); - maButtonLine.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - - // position tab control on upper right - aBtnSize = maTabCtrl.GetSizePixel(); - aBtnRect = Rectangle( Point( aWindowSize.Width() - aPixDiff.Width() - aBtnSize.Width(), - aPixDiff.Height() ), - Size( aBtnSize.Width(), maButtonLine.GetPosPixel().Y() - 2*aPixDiff.Height() ) ); - maTabCtrl.SetPosSizePixel( aBtnRect.TopLeft(), aBtnRect.GetSize() ); - - // set size for preview - long nMaxX = maTabCtrl.GetPosPixel().X() - 2*aPixDiff.Width(); - long nMaxY = maButtonLine.GetPosPixel().Y() - - 4 * aPixDiff.Height() - - maForwardBtn.GetSizePixel().Height(); - long nPreviewLength = std::min( nMaxX, nMaxY ); - maPreviewSpace = Rectangle( Point( aPixDiff.Width(), 2 * aPixDiff.Height() ), - Size( nPreviewLength, nPreviewLength ) ); - - // position text and slider below preview, aligned - Size aPrefSize( maPreviewCtrlRow.getOptimalSize( WINDOWSIZE_PREFERRED ) ); - aPrefSize.Width() = nPreviewLength - 2* aPixDiff.Width(); - Point aCtrlPos( 2*aPixDiff.Width(), 3*aPixDiff.Height() + nPreviewLength ); - maPreviewCtrlRow.setManagedArea( Rectangle( aCtrlPos, aPrefSize ) ); - maPreviewBackground.Left() = aPixDiff.Width() - 2; - maPreviewBackground.Top() = aPixDiff.Height() - 2; - maPreviewBackground.Right() = aPixDiff.Width() + nPreviewLength + 2; - maPreviewBackground.Bottom() = maPreviewCtrlRow.getManagedArea().Bottom() + aPixDiff.Height(); - #else maLayout.setManagedArea( Rectangle( Point( 0, 0 ), GetSizePixel() ) ); - #endif - // and do the preview; however the metafile does not need to be gotten anew preparePreview( false ); diff --git a/vcl/win/source/gdi/salprn.cxx b/vcl/win/source/gdi/salprn.cxx index 8fe9b5d8f4d0..f4f55dd0adbf 100644 --- a/vcl/win/source/gdi/salprn.cxx +++ b/vcl/win/source/gdi/salprn.cxx @@ -1968,7 +1968,7 @@ BOOL WinSalPrinter::StartJob( const XubString* pFileName, const XubString&, ULONG nCopies, bool bCollate, - bool bDirect, + bool /*bDirect*/, ImplJobSetup* pSetupData ) { mnError = 0; -- cgit From 1472eca629ac41b88ccd492a7fecfbe90a0a90c7 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 6 Aug 2009 18:36:51 +0000 Subject: #i92516# fix some more layout problems --- vcl/source/control/lstbox.cxx | 6 +++++- vcl/source/window/printdlg.cxx | 15 +++++++++------ vcl/win/source/gdi/salnativewidgets-luna.cxx | 27 +++++++++++++++++++++++++-- 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 553ea46f3bce..7c9842c278d1 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -1274,7 +1274,11 @@ Size ListBox::CalcMinimumSize() const else { aSz.Height() = mpImplLB->CalcSize( 1 ).Height(); - aSz.Width() = mpImplLB->GetMaxEntryWidth(); + // size to maxmimum entry width and add a little breathing space + aSz.Width() = mpImplLB->GetMaxEntryWidth() + 4; + // do not create ultrathin ListBoxes, it doesn't look good + if( aSz.Width() < GetSettings().GetStyleSettings().GetScrollBarSize() ) + aSz.Width() = GetSettings().GetStyleSettings().GetScrollBarSize(); // try native borders; scrollbar size may not be a good indicator // see how large the edit area inside is to estimate what is needed for the dropdown diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 3395e4aff62d..30f96f4d8081 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1467,22 +1467,23 @@ void PrintDialog::setupOptionalUI() maTabCtrl.SetMinimumSizePixel( maTabCtrl.GetSizePixel() ); if( aMaxSize.Height() > aTabSize.Height() || aMaxSize.Width() > aTabSize.Width() ) { - Size aCurSize( GetSizePixel() ); + Size aCurSize( GetOutputSizePixel() ); if( aMaxSize.Height() > aTabSize.Height() ) + { aCurSize.Height() += aMaxSize.Height() - aTabSize.Height(); + aTabSize.Height() = aMaxSize.Height(); + } if( aMaxSize.Width() > aTabSize.Width() ) { aCurSize.Width() += aMaxSize.Width() - aTabSize.Width(); // and the tab ctrl needs more space, too aTabSize.Width() = aMaxSize.Width(); - maTabCtrl.SetSizePixel( aTabSize ); - maTabCtrl.SetMinimumSizePixel( maTabCtrl.GetSizePixel() ); } - SetSizePixel( aCurSize ); + maTabCtrl.SetTabPageSizePixel( aTabSize ); + maTabCtrl.SetMinimumSizePixel( maTabCtrl.GetSizePixel() ); } // and finally arrange controls - aTabSize = maTabCtrl.GetTabPageSizePixel(); for( std::vector< vcl::RowOrColumn* >::iterator it = aDynamicColumns.begin(); it != aDynamicColumns.end(); ++it ) { @@ -1493,7 +1494,9 @@ void PrintDialog::setupOptionalUI() maJobPage.Resize(); maNUpPage.Resize(); maOptionsPage.Resize(); - Resize(); + + Size aSz = maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ); + SetOutputSizePixel( aSz ); } void PrintDialog::checkControlDependencies() diff --git a/vcl/win/source/gdi/salnativewidgets-luna.cxx b/vcl/win/source/gdi/salnativewidgets-luna.cxx index 5a5703e10944..d1fb2b67c3ec 100644 --- a/vcl/win/source/gdi/salnativewidgets-luna.cxx +++ b/vcl/win/source/gdi/salnativewidgets-luna.cxx @@ -337,7 +337,7 @@ BOOL ImplDrawTheme( HTHEME hTheme, HDC hDC, int iPart, int iState, RECT rc, cons } -Rectangle ImplGetThemeRect( HTHEME hTheme, HDC hDC, int iPart, int iState, const Rectangle& aRect ) +Rectangle ImplGetThemeRect( HTHEME hTheme, HDC hDC, int iPart, int iState, const Rectangle& aRect, THEMESIZE eTS = TS_TRUE ) { SIZE aSz; RECT rc; @@ -345,7 +345,7 @@ Rectangle ImplGetThemeRect( HTHEME hTheme, HDC hDC, int iPart, int iState, const rc.right = aRect.nRight; rc.top = aRect.nTop; rc.bottom = aRect.nBottom; - HRESULT hr = vsAPI.GetThemePartSize( hTheme, hDC, iPart, iState, NULL, TS_TRUE, &aSz ); // TS_TRUE returns optimal size + HRESULT hr = vsAPI.GetThemePartSize( hTheme, hDC, iPart, iState, NULL, eTS, &aSz ); // TS_TRUE returns optimal size if( hr == S_OK ) return Rectangle( 0, 0, aSz.cx, aSz.cy ); else @@ -1109,6 +1109,29 @@ BOOL WinSalGraphics::getNativeControlRegion( ControlType nType, bRet = TRUE; } } + + if( (nType == CTRL_LISTBOX || nType == CTRL_COMBOBOX ) && nPart == PART_ENTIRE_CONTROL ) + { + HTHEME hTheme = getThemeHandle( mhWnd, L"Combobox"); + if( hTheme ) + { + Rectangle aBoxRect( rControlRegion.GetBoundRect() ); + Rectangle aRect( ImplGetThemeRect( hTheme, hDC, CP_DROPDOWNBUTTON, + CBXS_NORMAL, aBoxRect ) ); + Rectangle aBrdRect( ImplGetThemeRect( hTheme, hDC, CP_BORDER, + CBB_HOT, aBoxRect ) ); + aRect.Top() -= aBrdRect.GetHeight(); + if( aRect.GetHeight() > aBoxRect.GetHeight() ) + aBoxRect.Bottom() = aBoxRect.Top() + aRect.GetHeight(); + if( aRect.GetWidth() > aBoxRect.GetWidth() ) + aBoxRect.Right() = aBoxRect.Left() + aRect.GetWidth(); + rNativeContentRegion = aBoxRect; + rNativeBoundingRegion = rNativeContentRegion; + if( !aRect.IsEmpty() ) + bRet = TRUE; + } + } + ReleaseDC( mhWnd, hDC ); return( bRet ); } -- cgit From 659a2ca6381666dcfb293aa91e5ae03423e0455b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 7 Aug 2009 12:32:48 +0000 Subject: #i92516# fix some more layout problems --- vcl/source/control/edit.cxx | 16 ++++++++++++- vcl/source/window/printdlg.cxx | 11 +++++++++ vcl/win/source/gdi/salnativewidgets-luna.cxx | 34 ++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/vcl/source/control/edit.cxx b/vcl/source/control/edit.cxx index 2ee0ab168a86..ccdff4d401f7 100644 --- a/vcl/source/control/edit.cxx +++ b/vcl/source/control/edit.cxx @@ -2836,7 +2836,21 @@ Size Edit::CalcMinimumSize() const Size aMinSize ( CalcSize( 3 ) ); if( aSize.Width() < aMinSize.Width() ) aSize.Width() = aMinSize.Width(); - return CalcWindowSize( aSize ); + aSize = CalcWindowSize( aSize ); + + // ask NWF what if it has an opinion, too + ImplControlValue aControlValue; + Rectangle aRect( Point( 0, 0 ), aSize ); + Region aContent, aBound; + if( const_cast(this)->GetNativeControlRegion( + CTRL_EDITBOX, PART_ENTIRE_CONTROL, + aRect, 0, aControlValue, rtl::OUString(), aBound, aContent) ) + { + Rectangle aBoundRect( aBound.GetBoundRect() ); + if( aBoundRect.GetHeight() > aSize.Height() ) + aSize.Height() = aBoundRect.GetHeight(); + } + return aSize; } // ----------------------------------------------------------------------- diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 30f96f4d8081..45c503f51fce 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1448,6 +1448,17 @@ void PrintDialog::setupOptionalUI() maJobPage.maCopySpacer.Show( FALSE ); } +#ifdef WNT + // FIXME: the GetNativeControlRegion call on Windows has some issues + // (which skew the results of GetOptimalSize()) + // however fixing this thoroughly needs to take interaction with paint into + // acoount, making the right fix less simple. Fix this the right way + // at some point. For now simply add some space at the lowest element + size_t nIndex = maJobPage.maLayout.countElements(); + if( nIndex > 0 ) // sanity check + maJobPage.maLayout.setBorders( nIndex-1, 0, 0, 0, aBorder.Width() ); +#endif + // calculate job page Size aMaxSize = maJobPage.maLayout.getOptimalSize( WINDOWSIZE_PREFERRED ); // and layout page diff --git a/vcl/win/source/gdi/salnativewidgets-luna.cxx b/vcl/win/source/gdi/salnativewidgets-luna.cxx index d1fb2b67c3ec..5c85d5d67144 100644 --- a/vcl/win/source/gdi/salnativewidgets-luna.cxx +++ b/vcl/win/source/gdi/salnativewidgets-luna.cxx @@ -1132,6 +1132,40 @@ BOOL WinSalGraphics::getNativeControlRegion( ControlType nType, } } + if( (nType == CTRL_EDITBOX || nType == CTRL_SPINBOX) && nPart == PART_ENTIRE_CONTROL ) + { + HTHEME hTheme = getThemeHandle( mhWnd, L"Edit"); + if( hTheme ) + { + // get borderr size + Rectangle aBoxRect( rControlRegion.GetBoundRect() ); + Rectangle aRect( ImplGetThemeRect( hTheme, hDC, EP_BACKGROUNDWITHBORDER, + EBWBS_HOT, aBoxRect ) ); + // ad app font height + NONCLIENTMETRICSW aNonClientMetrics; + aNonClientMetrics.cbSize = sizeof( aNonClientMetrics ); + if ( SystemParametersInfoW( SPI_GETNONCLIENTMETRICS, sizeof( aNonClientMetrics ), &aNonClientMetrics, 0 ) ) + { + long nFontHeight = aNonClientMetrics.lfMessageFont.lfHeight; + if( nFontHeight < 0 ) + nFontHeight = -nFontHeight; + + if( aRect.GetHeight() && nFontHeight ) + { + aRect.Bottom() += aRect.GetHeight(); + aRect.Bottom() += nFontHeight; + if( aRect.GetHeight() > aBoxRect.GetHeight() ) + aBoxRect.Bottom() = aBoxRect.Top() + aRect.GetHeight(); + if( aRect.GetWidth() > aBoxRect.GetWidth() ) + aBoxRect.Right() = aBoxRect.Left() + aRect.GetWidth(); + rNativeContentRegion = aBoxRect; + rNativeBoundingRegion = rNativeContentRegion; + bRet = TRUE; + } + } + } + } + ReleaseDC( mhWnd, hDC ); return( bRet ); } -- cgit From 052a24595fb966ef7f910865c1ff2cb45cf5471c Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 7 Aug 2009 12:42:34 +0000 Subject: #i92516# fix a layout problem --- vcl/source/control/edit.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/control/edit.cxx b/vcl/source/control/edit.cxx index ccdff4d401f7..2b6f20977689 100644 --- a/vcl/source/control/edit.cxx +++ b/vcl/source/control/edit.cxx @@ -2846,7 +2846,7 @@ Size Edit::CalcMinimumSize() const CTRL_EDITBOX, PART_ENTIRE_CONTROL, aRect, 0, aControlValue, rtl::OUString(), aBound, aContent) ) { - Rectangle aBoundRect( aBound.GetBoundRect() ); + Rectangle aBoundRect( aContent.GetBoundRect() ); if( aBoundRect.GetHeight() > aSize.Height() ) aSize.Height() = aBoundRect.GetHeight(); } -- cgit From 68362c81847e6ce0233e26ad325f331c8907ecd9 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 7 Aug 2009 14:27:26 +0000 Subject: #i99162# override paper format with driver dialog --- vcl/inc/vcl/print.hxx | 1 + vcl/source/gdi/print3.cxx | 58 +++++++++++++++++++++++++++++++++++++----- vcl/source/window/printdlg.cxx | 9 ++++--- 3 files changed, 59 insertions(+), 9 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index d5d42466b611..732a37244d7f 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -503,6 +503,7 @@ public: SAL_DLLPRIVATE bool getReversePrint() const; SAL_DLLPRIVATE void pushPropertiesToPrinter(); SAL_DLLPRIVATE void setJobState( com::sun::star::view::PrintableState ); + SAL_DLLPRIVATE bool setupPrinter( Window* i_pDlgParent ); }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 1888fbdcad49..ef742f36d316 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -161,6 +161,10 @@ public: ImplPageCache maPageCache; + // set by user through printer config dialog + // if set, pages are centered and trimmed onto the fixed page + Size maFixedPageSize; + ImplPrinterControllerData() : mbLastPage( sal_False ), mbReversePageOrder( sal_False ), @@ -168,6 +172,15 @@ public: mpProgress( NULL ) {} ~ImplPrinterControllerData() { delete mpProgress; } + + Size getRealPaperSize( const Size& i_rPageSize ) const + { + if( maFixedPageSize.Width() > 0 && maFixedPageSize.Height() > 0 ) + return maFixedPageSize; + if( maMultiPage.nRows * maMultiPage.nColumns > 1 ) + return maMultiPage.aPaperSize; + return i_rPageSize; + } }; PrinterController::PrinterController() @@ -540,11 +553,32 @@ const boost::shared_ptr& PrinterController::getPrinter() const void PrinterController::setPrinter( const boost::shared_ptr& i_rPrinter ) { mpImplData->mpPrinter = i_rPrinter; - Size aPaperSize( i_rPrinter->PixelToLogic( i_rPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Name" ) ), makeAny( rtl::OUString( i_rPrinter->GetName() ) ) ); } +bool PrinterController::setupPrinter( Window* i_pParent ) +{ + bool bRet = false; + if( mpImplData->mpPrinter.get() ) + { + Size aPaperSize( mpImplData->mpPrinter->PixelToLogic( + mpImplData->mpPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + bRet = mpImplData->mpPrinter->Setup( i_pParent ); + if( bRet ) + { + // was the papersize overridden ? if so we need to take action + Size aNewPaperSize( mpImplData->mpPrinter->PixelToLogic( + mpImplData->mpPrinter->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ) ); + if( aNewPaperSize != aPaperSize ) + { + mpImplData->maFixedPageSize = aNewPaperSize; + } + } + } + return bRet; +} + static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) { Size aPageSize = pPrinter->GetPaperSize(); @@ -660,7 +694,7 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o if( nSubPages < 1 ) nSubPages = 1; - // there is no filtering to be done (and especially the page size of the + // there is no filtering to be done (and possibly the page size of the // original page is to be set), when N-Up is "neutral" that is there is // only one subpage and the margins are 0 if( nSubPages == 1 && @@ -672,10 +706,22 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o int nDocPages = getPageCount(); i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; } - return getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); + Size aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); + Size aPaperSize = mpImplData->getRealPaperSize( aPageSize ); + if( aPaperSize != aPageSize ) + { + // user overridden page size, center Metafile + o_rMtf.WindStart(); + long nDX = (aPaperSize.Width() - aPageSize.Width()) / 2; + long nDY = (aPaperSize.Height() - aPageSize.Height()) / 2; + o_rMtf.Move( nDX, nDY ); + o_rMtf.WindStart(); + o_rMtf.SetPrefSize( aPaperSize ); + } + return aPaperSize; } - Size aPaperSize( mpImplData->maMultiPage.aPaperSize ); + Size aPaperSize( mpImplData->getRealPaperSize( mpImplData->maMultiPage.aPaperSize ) ); // multi page area: paper size minus margins + one time spacing right and down // the added spacing is so each subpage can be calculated including its spacing Size aMPArea( aPaperSize ); @@ -832,8 +878,8 @@ void PrinterController::printFilteredPage( int i_nPage ) // in N-Up printing set the correct page size mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); - if( bMultiPageOutput ) - mpImplData->mpPrinter->SetPaperSizeUser( aPageSize = mpImplData->maMultiPage.aPaperSize ); + // aPageSize was filtered through mpImplData->getRealPaperSize already by getFilteredPageFile() + mpImplData->mpPrinter->SetPaperSizeUser( aPageSize ); // actually print the page mpImplData->mpPrinter->ImplStartPage(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 45c503f51fce..24a94d0e2b3f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1884,15 +1884,18 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) makeAny( bChecked ) ); preparePreview( true, true ); } + else if( pButton == &maNUpPage.maBorderCB ) + { + updateNup(); + } else { if( pButton == &maJobPage.maSetupButton ) { - maPController->getPrinter()->Setup( this ); + maPController->setupPrinter( this ); + preparePreview( true, true ); } checkControlDependencies(); - if( pButton == &maNUpPage.maBorderCB ) - updateNup(); } return 0; } -- cgit From fb470c6f6c2da484102bd338e672d65348d95336 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 10 Aug 2009 16:48:53 +0000 Subject: #i92516# more changes for final UI spec --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 4 +- vcl/inc/vcl/arrange.hxx | 31 ++++ vcl/inc/vcl/print.hxx | 3 + vcl/inc/vcl/prndlg.hxx | 10 +- vcl/inc/vcl/svids.hrc | 40 +++-- vcl/source/gdi/print3.cxx | 37 +++- vcl/source/src/print.src | 20 ++- vcl/source/window/arrange.cxx | 245 +++++++++++++++++++++----- vcl/source/window/printdlg.cxx | 119 ++++++------- 9 files changed, 363 insertions(+), 146 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index f6d9ff7b7d9c..df08faf43686 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -97,7 +97,7 @@ class ControllerProperties PrintAccessoryViewState* i_pState ) : mpController( i_pController ), mnNextTag( 0 ), - mnLastPageCount( i_pController->getPageCount() ), + mnLastPageCount( i_pController->getPageCountProtected() ), mpState( i_pState ), mpOp( i_pOp ), mpAccessoryView( i_pAccessoryView ), @@ -125,7 +125,7 @@ class ControllerProperties // TODO: refresh page count etc from mpController // page range may have changed depending on options - sal_Int32 nPages = mpController->getPageCount(); + sal_Int32 nPages = mpController->getPageCountProtected(); #if OSL_DEBUG_LEVEL > 1 if( nPages != mnLastPageCount ) fprintf( stderr, "trouble: number of pages changed from %ld to %ld !\n", mnLastPageCount, nPages ); diff --git a/vcl/inc/vcl/arrange.hxx b/vcl/inc/vcl/arrange.hxx index e31be4ac8c67..309d0bf930ea 100644 --- a/vcl/inc/vcl/arrange.hxx +++ b/vcl/inc/vcl/arrange.hxx @@ -142,6 +142,8 @@ namespace vcl return pEle ? pEle->m_pElement : NULL; } + virtual bool isVisible() const; // true if any element is visible + sal_Int32 getExpandPriority( size_t i_nIndex ) const { const Element* pEle = getConstElement( i_nIndex ); @@ -227,6 +229,8 @@ namespace vcl size_t addChild( WindowArranger* i_pNewChild, sal_Int32 i_nExpandPrio = 0, size_t i_nIndex = ~0 ) { return addChild( boost::shared_ptr( i_pNewChild ), i_nExpandPrio, i_nIndex ); } void remove( boost::shared_ptr const & ); + + long getBorderWidth() const { return m_nBorderWidth; } }; class LabeledElement : public WindowArranger @@ -234,6 +238,7 @@ namespace vcl WindowArranger::Element m_aLabel; WindowArranger::Element m_aElement; long m_nDistance; + long m_nLabelColumnWidth; int m_nLabelStyle; protected: virtual Element* getElement( size_t i_nIndex ) @@ -249,6 +254,7 @@ namespace vcl LabeledElement( WindowArranger* i_pParent = NULL, int i_nLabelStyle = 0, long i_nDistance = 5 ) : WindowArranger( i_pParent ) , m_nDistance( i_nDistance ) + , m_nLabelColumnWidth( 0 ) , m_nLabelStyle( i_nLabelStyle ) {} @@ -262,6 +268,30 @@ namespace vcl void setLabel( boost::shared_ptr const & ); void setElement( Window* ); void setElement( boost::shared_ptr const & ); + void setLabelColumnWidth( long i_nWidth ) + { m_nLabelColumnWidth = i_nWidth; } + + Size getLabelSize( WindowSizeType i_eType ) const + { return m_aLabel.getOptimalSize( i_eType ); } + Size getElementSize( WindowSizeType i_eType ) const + { return m_aElement.getOptimalSize( i_eType ); } + }; + + class LabelColumn : public RowOrColumn + { + long getLabelWidth() const; + public: + LabelColumn( WindowArranger* i_pParent = NULL, long i_nBorderWidth = 5 ) + : RowOrColumn( i_pParent, true, i_nBorderWidth ) + {} + virtual ~LabelColumn(); + + virtual Size getOptimalSize( WindowSizeType ) const; + virtual void resize(); + + // returns the index of the added label + size_t addRow( Window* i_pLabel, boost::shared_ptr const& i_rElement, long i_nIndent = 0 ); + size_t addRow( Window* i_pLabel, Window* i_pElement, long i_nIndent = 0 ); }; class Indenter : public WindowArranger @@ -321,6 +351,7 @@ namespace vcl virtual void resize() {} virtual void setParentWindow( Window* ) {} virtual size_t countElements() const { return 1; } + virtual bool isVisible() const { return true; } }; class MatrixArranger : public WindowArranger diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 732a37244d7f..ce4bc7ba63cb 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -504,6 +504,9 @@ public: SAL_DLLPRIVATE void pushPropertiesToPrinter(); SAL_DLLPRIVATE void setJobState( com::sun::star::view::PrintableState ); SAL_DLLPRIVATE bool setupPrinter( Window* i_pDlgParent ); + + SAL_DLLPRIVATE int getPageCountProtected() const; + SAL_DLLPRIVATE com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getPageParametersProtected( int i_nPage ) const; }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 5cf9faac5b9c..55874728a536 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -104,10 +104,12 @@ namespace vcl NumericField maNupColEdt; FixedText maNupTimesTxt; NumericField maNupRowsEdt; - FixedText maPageMarginTxt; + FixedText maPageMarginTxt1; MetricField maPageMarginEdt; - FixedText maSheetMarginTxt; + FixedText maPageMarginTxt2; + FixedText maSheetMarginTxt1; MetricField maSheetMarginEdt; + FixedText maSheetMarginTxt2; FixedText maNupOrientationTxt; ListBox maNupOrientationBox; @@ -119,8 +121,6 @@ namespace vcl CheckBox maBorderCB; vcl::RowOrColumn maLayout; - boost::shared_ptr< vcl::WindowArranger >mxAdvancedControls; - boost::shared_ptr< vcl::RowOrColumn > mxLayoutGroup; boost::shared_ptr< vcl::RowOrColumn > mxBrochureDep; void setupLayout(); @@ -133,6 +133,8 @@ namespace vcl void initFromMultiPageSetup( const vcl::PrinterController::MultiPageSetup& ); void enableNupControls( bool bEnable ); + void showAdvancedControls( bool ); + virtual void Resize(); }; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 5ec6ff3d9901..427ee4426a09 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -90,25 +90,27 @@ #define SV_PRINT_PRT_COMMENT 13 #define SV_PRINT_TOFILE_TXT 14 -#define SV_PRINT_TAB_NUP 1 -#define SV_PRINT_PRT_NUP_LAYOUT_FL 1 -#define SV_PRINT_PRT_NUP_DEFAULT_BTN 2 -#define SV_PRINT_PRT_NUP_BROCHURE_BTN 3 -#define SV_PRINT_PRT_NUP_PAGES_BTN 4 -#define SV_PRINT_PRT_NUP_PAGES_BOX 5 -#define SV_PRINT_PRT_NUP_NUM_PAGES_TXT 6 -#define SV_PRINT_PRT_NUP_COLS_EDT 7 -#define SV_PRINT_PRT_NUP_TIMES_TXT 8 -#define SV_PRINT_PRT_NUP_ROWS_EDT 9 -#define SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT 10 -#define SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT 11 -#define SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT 12 -#define SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT 13 -#define SV_PRINT_PRT_NUP_ORIENTATION_TXT 14 -#define SV_PRINT_PRT_NUP_ORIENTATION_BOX 15 -#define SV_PRINT_PRT_NUP_ORDER_TXT 16 -#define SV_PRINT_PRT_NUP_ORDER_BOX 17 -#define SV_PRINT_PRT_NUP_BORDER_CB 18 +#define SV_PRINT_TAB_NUP 1 +#define SV_PRINT_PRT_NUP_LAYOUT_FL 1 +#define SV_PRINT_PRT_NUP_DEFAULT_BTN 2 +#define SV_PRINT_PRT_NUP_BROCHURE_BTN 3 +#define SV_PRINT_PRT_NUP_PAGES_BTN 4 +#define SV_PRINT_PRT_NUP_PAGES_BOX 5 +#define SV_PRINT_PRT_NUP_NUM_PAGES_TXT 6 +#define SV_PRINT_PRT_NUP_COLS_EDT 7 +#define SV_PRINT_PRT_NUP_TIMES_TXT 8 +#define SV_PRINT_PRT_NUP_ROWS_EDT 9 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_1_TXT 10 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT 11 +#define SV_PRINT_PRT_NUP_MARGINS_PAGES_2_TXT 12 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_1_TXT 13 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT 14 +#define SV_PRINT_PRT_NUP_MARGINS_SHEET_2_TXT 15 +#define SV_PRINT_PRT_NUP_ORIENTATION_TXT 16 +#define SV_PRINT_PRT_NUP_ORIENTATION_BOX 17 +#define SV_PRINT_PRT_NUP_ORDER_TXT 18 +#define SV_PRINT_PRT_NUP_ORDER_BOX 19 +#define SV_PRINT_PRT_NUP_BORDER_CB 20 #define SV_PRINT_PRT_NUP_ORIENTATION_AUTOMATIC 0 #define SV_PRINT_PRT_NUP_ORIENTATION_PORTRAIT 1 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index ef742f36d316..bb8c3ba1e041 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -352,7 +352,7 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr { GDIMetaFile aPageFile; i_pController->setLastPage( sal_True ); - if( i_pController->getPageCount() > 0 ) + if( i_pController->getPageCountProtected() > 0 ) i_pController->getFilteredPageFile( 0, aPageFile ); return; } @@ -599,6 +599,28 @@ static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& return aPageSize; } +int PrinterController::getPageCountProtected() const +{ + const MapMode aMapMode( MAP_100TH_MM ); + + mpImplData->mpPrinter->Push(); + mpImplData->mpPrinter->SetMapMode( aMapMode ); + int nPages = getPageCount(); + mpImplData->mpPrinter->Pop(); + return nPages; +} + +Sequence< beans::PropertyValue > PrinterController::getPageParametersProtected( int i_nPage ) const +{ + const MapMode aMapMode( MAP_100TH_MM ); + + mpImplData->mpPrinter->Push(); + mpImplData->mpPrinter->SetMapMode( aMapMode ); + Sequence< beans::PropertyValue > aResult( getPageParameters( i_nPage ) ); + mpImplData->mpPrinter->Pop(); + return aResult; +} + Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { // update progress if necessary @@ -626,7 +648,7 @@ Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, o_rMtf.Clear(); // get page parameters - Sequence< PropertyValue > aPageParm( getPageParameters( i_nUnfilteredPage ) ); + Sequence< PropertyValue > aPageParm( getPageParametersProtected( i_nUnfilteredPage ) ); const MapMode aMapMode( MAP_100TH_MM ); mpImplData->mpPrinter->Push(); @@ -677,7 +699,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD } // clip to page rect - o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); + // o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); // append the subpage io_rSubPage.WindStart(); @@ -703,7 +725,7 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o { if( mpImplData->mbReversePageOrder ) { - int nDocPages = getPageCount(); + int nDocPages = getPageCountProtected(); i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; } Size aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); @@ -742,7 +764,7 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o o_rMtf.SetPrefMapMode( MapMode( MAP_100TH_MM ) ); o_rMtf.AddAction( new MetaMapModeAction( MapMode( MAP_100TH_MM ) ) ); - int nDocPages = getPageCount(); + int nDocPages = getPageCountProtected(); for( int nSubPage = 0; nSubPage < nSubPages; nSubPage++ ) { // map current sub page to real page @@ -801,7 +823,7 @@ int PrinterController::getFilteredPageCount() int nDiv = mpImplData->maMultiPage.nRows * mpImplData->maMultiPage.nColumns; if( nDiv < 1 ) nDiv = 1; - return (getPageCount() * mpImplData->maMultiPage.nRepeat + (nDiv-1)) / nDiv; + return (getPageCountProtected() * mpImplData->maMultiPage.nRepeat + (nDiv-1)) / nDiv; } void PrinterController::printFilteredPage( int i_nPage ) @@ -822,7 +844,6 @@ void PrinterController::printFilteredPage( int i_nPage ) } } - bool bMultiPageOutput = mpImplData->maMultiPage.nRows != 1 || mpImplData->maMultiPage.nColumns != 1; ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); @@ -1159,7 +1180,7 @@ void PrinterController::createProgressDialog() if( bShow && ! Application::IsHeadlessModeEnabled() ) { - mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCount() ); + mpImplData->mpProgress = new PrintProgressDialog( NULL, getPageCountProtected() ); mpImplData->mpProgress->Show(); } } diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index a7cd7bc237e0..5c04af603c93 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -199,11 +199,11 @@ ModalDialog SV_DLG_PRINT Value = 1; HelpText [en-US] = "Select number of rows."; }; - FixedText SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT + FixedText SV_PRINT_PRT_NUP_MARGINS_PAGES_1_TXT { Pos = MAP_APPFONT( 10, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Margin between ~pages"; + Text [en-US] = "~Distance"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT { @@ -215,11 +215,17 @@ ModalDialog SV_DLG_PRINT Unit = FUNIT_MM; HelpText [en-US] = "Select margin between individual pages on each sheet of paper."; }; - FixedText SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT + FixedText SV_PRINT_PRT_NUP_MARGINS_PAGES_2_TXT + { + Pos = MAP_APPFONT( 10, 95 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "between pages"; + }; + FixedText SV_PRINT_PRT_NUP_MARGINS_SHEET_1_TXT { Pos = MAP_APPFONT( 110, 95 ); Size = MAP_APPFONT( 40, 10 ); - Text [en-US] = "Margin to ~sheet border"; + Text [en-US] = "~Margin"; }; MetricField SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT { @@ -231,6 +237,12 @@ ModalDialog SV_DLG_PRINT Unit = FUNIT_MM; HelpText [en-US] = "Select margin between the printed pages and paper edge."; }; + FixedText SV_PRINT_PRT_NUP_MARGINS_SHEET_2_TXT + { + Pos = MAP_APPFONT( 110, 95 ); + Size = MAP_APPFONT( 40, 10 ); + Text [en-US] = "to sheet border"; + }; FixedText SV_PRINT_PRT_NUP_ORIENTATION_TXT { Pos = MAP_APPFONT( 0, 0 ); diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 8b3ed40db72e..7e019dc7e5ac 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -113,14 +113,27 @@ void WindowArranger::show( bool i_bShow, bool i_bImmediateUpdate ) } } +bool WindowArranger::isVisible() const +{ + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + const Element* pEle = getConstElement( i ); + if( pEle->isVisible() ) + return true; + } + return false; +} + bool WindowArranger::Element::isVisible() const { bool bVisible = false; if( ! m_bHidden ) { - bVisible = true; if( m_pElement ) bVisible = m_pElement->IsVisible(); + else if( m_pChild ) + bVisible = m_pChild->isVisible(); } return bVisible; } @@ -191,42 +204,46 @@ RowOrColumn::~RowOrColumn() Size RowOrColumn::getOptimalSize( WindowSizeType i_eType ) const { Size aRet( 0, 0 ); - if( ! m_aElements.empty() ) - { - if( m_bColumn ) - aRet.Height() -= m_nBorderWidth; - else - aRet.Width() -= m_nBorderWidth; - } - for( std::vector< WindowArranger::Element >::const_iterator it = m_aElements.begin(); it != m_aElements.end(); ++it ) { - // get the size of type of the managed element - Size aElementSize( it->getOptimalSize( i_eType ) ); - if( m_bColumn ) + if( it->isVisible() ) { - // add the distance between elements - aRet.Height() += m_nBorderWidth; - // check if the width needs adjustment - if( aRet.Width() < aElementSize.Width() ) - aRet.Width() = aElementSize.Width(); - aRet.Height() += aElementSize.Height(); - } - else - { - // add the distance between elements - aRet.Width() += m_nBorderWidth; - // check if the height needs adjustment - if( aRet.Height() < aElementSize.Height() ) - aRet.Height() = aElementSize.Height(); - aRet.Width() += aElementSize.Width(); + // get the size of type of the managed element + Size aElementSize( it->getOptimalSize( i_eType ) ); + if( m_bColumn ) + { + // add the distance between elements + aRet.Height() += m_nBorderWidth; + // check if the width needs adjustment + if( aRet.Width() < aElementSize.Width() ) + aRet.Width() = aElementSize.Width(); + aRet.Height() += aElementSize.Height(); + } + else + { + // add the distance between elements + aRet.Width() += m_nBorderWidth; + // check if the height needs adjustment + if( aRet.Height() < aElementSize.Height() ) + aRet.Height() = aElementSize.Height(); + aRet.Width() += aElementSize.Width(); + } } } - // add the outer border - aRet.Width() += 2*m_nOuterBorder; - aRet.Height() += 2*m_nOuterBorder; + if( aRet.Width() != 0 || aRet.Height() != 0 ) + { + // subtract the border for the first element + if( m_bColumn ) + aRet.Height() -= m_nBorderWidth; + else + aRet.Width() -= m_nBorderWidth; + + // add the outer border + aRet.Width() += 2*m_nOuterBorder; + aRet.Height() += 2*m_nOuterBorder; + } return aRet; } @@ -333,16 +350,19 @@ void RowOrColumn::resize() long nUsedWidth = 2*m_nOuterBorder - (nElements ? m_nBorderWidth : 0); for( size_t i = 0; i < nElements; i++ ) { - aElementSizes[i] = m_aElements[i].getOptimalSize( eType ); - if( m_bColumn ) - { - aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder; - nUsedWidth += aElementSizes[i].Height() + m_nBorderWidth; - } - else + if( m_aElements[i].isVisible() ) { - aElementSizes[i].Height() = m_aManagedArea.GetHeight() - 2* m_nOuterBorder; - nUsedWidth += aElementSizes[i].Width() + m_nBorderWidth; + aElementSizes[i] = m_aElements[i].getOptimalSize( eType ); + if( m_bColumn ) + { + aElementSizes[i].Width() = m_aManagedArea.GetWidth() - 2* m_nOuterBorder; + nUsedWidth += aElementSizes[i].Height() + m_nBorderWidth; + } + else + { + aElementSizes[i].Height() = m_aManagedArea.GetHeight() - 2* m_nOuterBorder; + nUsedWidth += aElementSizes[i].Width() + m_nBorderWidth; + } } } @@ -365,12 +385,14 @@ void RowOrColumn::resize() for( size_t i = 0; i < nElements; i++ ) { // get the size of type of the managed element - - m_aElements[i].setPosSize( aElementPos, aElementSizes[i] ); - if( m_bColumn ) - aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height(); - else - aElementPos.X() += m_nBorderWidth + aElementSizes[i].Width(); + if( m_aElements[i].isVisible() ) + { + m_aElements[i].setPosSize( aElementPos, aElementSizes[i] ); + if( m_bColumn ) + aElementPos.Y() += m_nBorderWidth + aElementSizes[i].Height(); + else + aElementPos.X() += m_nBorderWidth + aElementSizes[i].Width(); + } } } @@ -456,7 +478,12 @@ Size LabeledElement::getOptimalSize( WindowSizeType i_eType ) const { Size aRet( m_aLabel.getOptimalSize( WINDOWSIZE_MINIMUM ) ); if( aRet.Width() != 0 ) - aRet.Width() += m_nDistance; + { + if( m_nLabelColumnWidth != 0 ) + aRet.Width() = m_nLabelColumnWidth; + else + aRet.Width() += m_nDistance; + } Size aElementSize( m_aElement.getOptimalSize( i_eType ) ); aRet.Width() += aElementSize.Width(); if( aElementSize.Height() > aRet.Height() ) @@ -479,6 +506,8 @@ void LabeledElement::resize() Point aPos( m_aManagedArea.Left(), m_aManagedArea.Top() + m_nOuterBorder + nYOff ); Size aSize( aLabelSize ); + if( m_nLabelColumnWidth != 0 ) + aSize.Width() = m_nLabelColumnWidth; m_aLabel.setPosSize( aPos, aSize ); aPos.X() += aSize.Width() + m_nDistance; @@ -528,6 +557,130 @@ void LabeledElement::setElement( boost::shared_ptr const & i_pEl m_aElement.m_pChild = i_pElement; } +// ---------------------------------------- +// vcl::LabelColumn +//----------------------------------------- +LabelColumn::~LabelColumn() +{ +} + +long LabelColumn::getLabelWidth() const +{ + long nWidth = 0; + + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + const Element* pEle = getConstElement( i ); + if( pEle && pEle->m_pChild.get() ) + { + const LabeledElement* pLabel = dynamic_cast< const LabeledElement* >(pEle->m_pChild.get()); + if( pLabel ) + { + Window* pLW = pLabel->getWindow( 0 ); + if( pLW ) + { + Size aLabSize( pLW->GetOptimalSize( WINDOWSIZE_MINIMUM ) ); + if( aLabSize.Width() > nWidth ) + nWidth = aLabSize.Width(); + } + } + } + } + return nWidth + getBorderWidth(); +} + +Size LabelColumn::getOptimalSize( WindowSizeType i_eType ) const +{ + long nWidth = getLabelWidth(); + Size aColumnSize; + + // every child is a LabeledElement + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + Size aElementSize; + const Element* pEle = getConstElement( i ); + if( pEle && pEle->m_pChild.get() ) + { + const LabeledElement* pLabel = dynamic_cast< const LabeledElement* >(pEle->m_pChild.get()); + if( pLabel ) // we have a label + { + aElementSize = pLabel->getLabelSize( WINDOWSIZE_MINIMUM ); + if( aElementSize.Width() ) + aElementSize.Width() = nWidth; + Size aSize( pLabel->getElementSize( i_eType ) ); + aElementSize.Width() += aSize.Width(); + if( aSize.Height() > aElementSize.Height() ) + aElementSize.Height() = aSize.Height(); + } + else // a non label, just treat it as a row + { + aElementSize = pEle->getOptimalSize( i_eType ); + } + } + else if( pEle && pEle->m_pElement ) // a general window, treat is as a row + { + aElementSize = pEle->getOptimalSize( i_eType ); + } + if( aElementSize.Width() ) + { + aElementSize.Width() += 2*m_nOuterBorder; + if( aElementSize.Width() > aColumnSize.Width() ) + aColumnSize.Width() = aElementSize.Width(); + } + if( aElementSize.Height() ) + { + aColumnSize.Height() += getBorderWidth() + aElementSize.Height(); + } + } + if( nEle > 0 && aColumnSize.Height() ) + { + aColumnSize.Height() -= getBorderWidth(); // for the first element + aColumnSize.Height() += 2*m_nOuterBorder; + } + return aColumnSize; +} + +void LabelColumn::resize() +{ + long nWidth = getLabelWidth(); + size_t nEle = countElements(); + for( size_t i = 0; i < nEle; i++ ) + { + Element* pEle = getElement( i ); + if( pEle && pEle->m_pChild.get() ) + { + LabeledElement* pLabel = dynamic_cast< LabeledElement* >(pEle->m_pChild.get()); + if( pLabel ) + pLabel->setLabelColumnWidth( nWidth ); + } + } + RowOrColumn::resize(); +} + +size_t LabelColumn::addRow( Window* i_pLabel, boost::shared_ptr const& i_rElement, long i_nIndent ) +{ + boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 2 ) ); + xLabel->setLabel( i_pLabel ); + xLabel->setBorders( 0, i_nIndent, 0, 0, 0 ); + xLabel->setElement( i_rElement ); + size_t nIndex = addChild( xLabel ); + resize(); + return nIndex; +} + +size_t LabelColumn::addRow( Window* i_pLabel, Window* i_pElement, long i_nIndent ) +{ + boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 2 ) ); + xLabel->setLabel( i_pLabel ); + xLabel->setBorders( 0, i_nIndent, 0, 0, 0 ); + xLabel->setElement( i_pElement ); + size_t nIndex = addChild( xLabel ); + resize(); + return nIndex; +} + // ---------------------------------------- // vcl::Indenter //----------------------------------------- diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 24a94d0e2b3f..390d53e49fb5 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -233,10 +233,12 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLS_EDT ) ) , maNupTimesTxt( this, VclResId( SV_PRINT_PRT_NUP_TIMES_TXT ) ) , maNupRowsEdt( this, VclResId( SV_PRINT_PRT_NUP_ROWS_EDT ) ) - , maPageMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_TXT ) ) + , maPageMarginTxt1( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_1_TXT ) ) , maPageMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_EDT ) ) - , maSheetMarginTxt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_TXT ) ) + , maPageMarginTxt2( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_PAGES_2_TXT ) ) + , maSheetMarginTxt1( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_1_TXT ) ) , maSheetMarginEdt( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_EDT ) ) + , maSheetMarginTxt2( this, VclResId( SV_PRINT_PRT_NUP_MARGINS_SHEET_2_TXT ) ) , maNupOrientationTxt( this, VclResId( SV_PRINT_PRT_NUP_ORIENTATION_TXT ) ) , maNupOrientationBox( this, VclResId( SV_PRINT_PRT_NUP_ORIENTATION_BOX ) ) , maNupOrderTxt( this, VclResId( SV_PRINT_PRT_NUP_ORDER_TXT ) ) @@ -275,10 +277,12 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maNupColEdt.SMHID2( "NUpPage", "ColumnsBox" ); maNupTimesTxt.SMHID2( "NUpPage", "Rows" ); maNupRowsEdt.SMHID2( "NUpPage", "RowsBox" ); - maPageMarginTxt.SMHID2( "NUpPage", "PageMargin" ); + maPageMarginTxt1.SMHID2( "NUpPage", "PageMargin" ); maPageMarginEdt.SMHID2( "NUpPage", "PageMarginBox" ); - maSheetMarginTxt.SMHID2( "NUpPage", "SheetMargin" ); + maPageMarginTxt2.SMHID2( "NUpPage", "PageMarginCont" ); + maSheetMarginTxt1.SMHID2( "NUpPage", "SheetMargin" ); maSheetMarginEdt.SMHID2( "NUpPage", "SheetMarginBox" ); + maSheetMarginTxt2.SMHID2( "NUpPage", "SheetMarginCont" ); maNupOrientationTxt.SMHID2( "NUpPage", "Orientation" ); maNupOrientationBox.SMHID2( "NUpPage", "OrientationBox" ); maNupOrderTxt.SMHID2( "NUpPage", "Order" ); @@ -299,10 +303,12 @@ void PrintDialog::NUpTabPage::enableNupControls( bool bEnable ) maNupColEdt.Enable( bEnable ); maNupTimesTxt.Enable( bEnable ); maNupRowsEdt.Enable( bEnable ); - maPageMarginTxt.Enable( bEnable ); + maPageMarginTxt1.Enable( bEnable ); maPageMarginEdt.Enable( bEnable ); - maSheetMarginTxt.Enable( bEnable ); + maPageMarginTxt2.Enable( bEnable ); + maSheetMarginTxt1.Enable( bEnable ); maSheetMarginEdt.Enable( bEnable ); + maSheetMarginTxt2.Enable( bEnable ); maNupOrientationTxt.Enable( bEnable ); maNupOrientationBox.Enable( bEnable ); maNupOrderTxt.Enable( bEnable ); @@ -311,9 +317,27 @@ void PrintDialog::NUpTabPage::enableNupControls( bool bEnable ) maBorderCB.Enable( bEnable ); } +void PrintDialog::NUpTabPage::showAdvancedControls( bool i_bShow ) +{ + maNupNumPagesTxt.Show( i_bShow ); + maNupColEdt.Show( i_bShow ); + maNupTimesTxt.Show( i_bShow ); + maNupRowsEdt.Show( i_bShow ); + maPageMarginTxt1.Show( i_bShow ); + maPageMarginEdt.Show( i_bShow ); + maPageMarginTxt2.Show( i_bShow ); + maSheetMarginTxt1.Show( i_bShow ); + maSheetMarginEdt.Show( i_bShow ); + maSheetMarginTxt2.Show( i_bShow ); + maNupOrientationTxt.Show( i_bShow ); + maNupOrientationBox.Show( i_bShow ); + maLayout.resize(); +} + void PrintDialog::NUpTabPage::setupLayout() { Size aBorder( LogicToPixel( Size( 5, 5 ), MapMode( MAP_APPFONT ) ) ); + long nIndent = 3*aBorder.Width(); maLayout.setParentWindow( this ); maLayout.setOuterBorder( aBorder.Width() ); @@ -330,72 +354,41 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xShowNupCol.get() ) ); xShowNupCol->addChild( xSpacer ); - boost::shared_ptr< vcl::RowOrColumn > xMainCol( new vcl::RowOrColumn( xIndent.get() ) ); + boost::shared_ptr< vcl::LabelColumn > xMainCol( new vcl::LabelColumn( xIndent.get() ) ); xIndent->setChild( xMainCol ); - boost::shared_ptr< vcl::LabeledElement > xLabel( new vcl::LabeledElement( xMainCol.get() ) ); - xMainCol->addChild( xLabel ); - xLabel->setLabel( &maPagesBtn ); - xLabel->setElement( &maNupPagesBox ); + xMainCol->addRow( &maPagesBtn, &maNupPagesBox ); + + xRow.reset( new vcl::RowOrColumn( xMainCol.get(), false ) ); + xMainCol->addRow( &maNupNumPagesTxt, xRow, nIndent ); + xRow->addWindow( &maNupColEdt ); + xRow->addWindow( &maNupTimesTxt ); + xRow->addWindow( &maNupRowsEdt ); - xIndent.reset( new vcl::Indenter( xMainCol.get(), 3*aBorder.Width() ) ); - xMainCol->addChild( xIndent ); + boost::shared_ptr< vcl::LabeledElement > xLab( new vcl::LabeledElement( xMainCol.get(), 2 ) ); + xLab->setLabel( &maPageMarginEdt ); + xLab->setElement( &maPageMarginTxt2 ); + xMainCol->addRow( &maPageMarginTxt1, xLab, nIndent ); - mxLayoutGroup = xMainCol; - boost::shared_ptr< vcl::RowOrColumn > xCol( new vcl::RowOrColumn( xIndent.get() ) ); - xIndent->setChild( xCol ); + xLab.reset( new vcl::LabeledElement( xMainCol.get(), 2 ) ); + xLab->setLabel( &maSheetMarginEdt ); + xLab->setElement( &maSheetMarginTxt2 ); + xMainCol->addRow( &maSheetMarginTxt1, xLab, nIndent ); - boost::shared_ptr< vcl::RowOrColumn > xAdvCol( new vcl::RowOrColumn( xCol.get() ) ); - xCol->addChild( xAdvCol ); - // remember advanced controls to show/hide - mxAdvancedControls = xAdvCol; - - xLabel.reset( new vcl::LabeledElement( xCol.get() ) ); - xCol->addChild( xLabel ); - xLabel->setLabel( &maNupOrderTxt ); - xLabel->setElement( &maNupOrderBox ); - xCol->addWindow( &maBorderCB ); - - xRow.reset( new vcl::RowOrColumn( xAdvCol.get(), false ) ); - xAdvCol->addChild( xRow ); - xLabel.reset( new vcl::LabeledElement( xRow.get() ) ); - xRow->addChild( xLabel, 1 ); - xLabel->setLabel( &maNupNumPagesTxt ); - xLabel->setElement( &maNupColEdt ); - xLabel.reset( new vcl::LabeledElement( xRow.get() ) ); - xRow->addChild( xLabel ); - xLabel->setLabel( &maNupTimesTxt ); - xLabel->setElement( &maNupRowsEdt ); - - xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); - xAdvCol->addChild( xLabel ); - xLabel->setLabel( &maPageMarginTxt ); - xLabel->setElement( &maPageMarginEdt ); - - xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); - xAdvCol->addChild( xLabel ); - xLabel->setLabel( &maSheetMarginTxt ); - xLabel->setElement( &maSheetMarginEdt ); - - xLabel.reset( new vcl::LabeledElement( xAdvCol.get() ) ); - xAdvCol->addChild( xLabel ); - xLabel->setLabel( &maNupOrientationTxt ); - xLabel->setElement( &maNupOrientationBox ); + xMainCol->addRow( &maNupOrientationTxt, &maNupOrientationBox, nIndent ); + xMainCol->addRow( &maNupOrderTxt, &maNupOrderBox, nIndent ); + xMainCol->setBorders( xMainCol->addWindow( &maBorderCB ), nIndent, 0, 0, 0 ); xSpacer.reset( new vcl::Spacer( xMainCol.get(), 0, Size( 10, aBorder.Width() ) ) ); xMainCol->addChild( xSpacer ); xRow.reset( new vcl::RowOrColumn( xMainCol.get(), false ) ); - xMainCol->addChild( xRow ); - xRow->addWindow( &maBrochureBtn ); + xMainCol->addRow( &maBrochureBtn, xRow ); // remember brochure row for dependencies mxBrochureDep = xRow; - xSpacer.reset( new vcl::Spacer( xMainCol.get(), 0, Size( 10, 2*aBorder.Width() ) ) ); - xMainCol->addChild( xSpacer ); - // initially advanced controls are not shown, rows=columns=1 - mxAdvancedControls->show( false, false ); + showAdvancedControls( false ); } void PrintDialog::NUpTabPage::Resize() @@ -1105,7 +1098,7 @@ void PrintDialog::setupOptionalUI() } else if( aGroupingHint.equalsAscii( "LayoutPage" ) ) { - pCurColumn = maNUpPage.mxLayoutGroup.get(); + pCurColumn = &maNUpPage.maLayout; pCurParent = &maNUpPage; // set layout page as current parent bOnStaticPage = true; } @@ -1329,7 +1322,7 @@ void PrintDialog::setupOptionalUI() setSmartId( pHeading, "FixedText", -1, aPropertyName ); // add to row - pLabel = new vcl::LabeledElement( pFieldColumn ); + pLabel = new vcl::LabeledElement( pFieldColumn, 2 ); pFieldColumn->addChild( pLabel ); pLabel->setLabel( pHeading ); } @@ -1651,7 +1644,7 @@ Size PrintDialog::getJobPageSize() { maFirstPageSize = maNupPortraitSize; GDIMetaFile aMtf; - if( maPController->getPageCount() > 0 ) + if( maPController->getPageCountProtected() > 0 ) maFirstPageSize = maPController->getPageFile( 0, aMtf, true ); } return maFirstPageSize; @@ -1706,7 +1699,7 @@ void PrintDialog::updateNupFromPages() maNUpPage.maPageMarginEdt.SetValue( maNUpPage.maPageMarginEdt.Normalize( nPageMargin ), FUNIT_100TH_MM ); maNUpPage.maSheetMarginEdt.SetValue( maNUpPage.maSheetMarginEdt.Normalize( nSheetMargin ), FUNIT_100TH_MM ); - maNUpPage.mxAdvancedControls->show( bCustom ); + maNUpPage.showAdvancedControls( bCustom ); if( bCustom ) { // see if we have to enlarge the dialog to make the tab page fit @@ -1846,7 +1839,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) { maNUpPage.maNupPagesBox.SelectEntryPos( 0 ); updateNupFromPages(); - maNUpPage.mxAdvancedControls->show( false ); + maNUpPage.showAdvancedControls( false ); maNUpPage.enableNupControls( false ); } } -- cgit From feb06438cf2e7eca712923305c729874693d6f5a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 10 Aug 2009 18:44:52 +0000 Subject: #i92516# more changes for final UI spec --- vcl/source/window/printdlg.cxx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 390d53e49fb5..1914b0008643 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -160,7 +160,7 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi } PrintDialog::ShowNupOrderWindow::ShowNupOrderWindow( Window* i_pParent ) - : Window( i_pParent, WB_BORDER ) + : Window( i_pParent, WB_NOBORDER ) , mnOrderMode( 0 ) , mnRows( 1 ) , mnColumns( 1 ) @@ -221,6 +221,8 @@ void PrintDialog::ShowNupOrderWindow::Paint( const Rectangle& i_rRect ) nY * aSubSize.Height() + nDeltaY ), aPageText ); } + DecorationView aVw( this ); + aVw.DrawFrame( Rectangle( Point( 0, 0), aOutSize ), FRAME_DRAW_GROUP ); } PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) @@ -487,8 +489,10 @@ void PrintDialog::JobTabPage::setupLayout() // create a row for details button/text and properties button boost::shared_ptr< vcl::RowOrColumn > xDetRow( new vcl::RowOrColumn( &maLayout, false ) ); maLayout.addChild( xDetRow ); - xDetRow->addWindow( &maDetailsBtn ); - xDetRow->addWindow( &maDetailsTxt ); + boost::shared_ptr< vcl::LabeledElement > xDetLbl( new vcl::LabeledElement( xDetRow.get() ) ); + xDetRow->addChild( xDetLbl ); + xDetLbl->setLabel( &maDetailsBtn ); + xDetLbl->setElement( &maDetailsTxt ); xDetRow->addChild( new vcl::Spacer( xDetRow.get(), 2 ) ); xDetRow->addWindow( &maSetupButton ); @@ -1635,6 +1639,10 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); maPreviewWindow.setPreview( aMtf, maCurPageSize ); + + maForwardBtn.Enable( mnCurPage < nPages-1 ); + maBackwardBtn.Enable( mnCurPage != 0 ); + maPageEdit.Enable( nPages > 1 ); } } -- cgit From 5e7db5f15fb042234fc7e3b3b692a03de137da36 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 11 Aug 2009 15:50:07 +0000 Subject: #i92516# final UI changes --- vcl/inc/vcl/prndlg.hxx | 3 +- vcl/source/window/printdlg.cxx | 75 +++++++++++++++++++++++++----------------- 2 files changed, 47 insertions(+), 31 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 55874728a536..182b77c1827d 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -59,6 +59,7 @@ namespace vcl GDIMetaFile maMtf; Size maOrigSize; VirtualDevice maPageVDev; + rtl::OUString maReplacementString; public: PrintPreviewWindow( Window* pParent, const ResId& ); virtual ~PrintPreviewWindow(); @@ -67,7 +68,7 @@ namespace vcl virtual void Command( const CommandEvent& ); virtual void Resize(); - void setPreview( const GDIMetaFile&, const Size& ); + void setPreview( const GDIMetaFile&, const Size&, const rtl::OUString& ); }; class ShowNupOrderWindow : public Window diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1914b0008643..09ae7cabf5d2 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -102,33 +102,49 @@ void PrintDialog::PrintPreviewWindow::Resize() void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& ) { - GDIMetaFile aMtf( maMtf ); - - Size aPreviewSize = maPageVDev.GetOutputSizePixel(); Size aSize( GetSizePixel() ); - Point aOffset( (aSize.Width() - aPreviewSize.Width()) / 2, - (aSize.Height() - aPreviewSize.Height()) / 2 ); + if( maReplacementString.getLength() != 0 ) + { + // replacement is active + Push(); + Rectangle aTextRect( Point( 0, 0 ), aSize ); + Font aFont( GetSettings().GetStyleSettings().GetFieldFont() ); + aFont.SetSize( Size( 0, aSize.Height()/12 ) ); + SetFont( aFont ); + DrawText( aTextRect, maReplacementString, + TEXT_DRAW_CENTER | TEXT_DRAW_VCENTER | TEXT_DRAW_WORDBREAK | TEXT_DRAW_MULTILINE + ); + Pop(); + } + else + { + GDIMetaFile aMtf( maMtf ); - const Size aLogicSize( maPageVDev.PixelToLogic( aPreviewSize, MapMode( MAP_100TH_MM ) ) ); - double fScale = double(aLogicSize.Width())/double(maOrigSize.Width()); + Size aPreviewSize = maPageVDev.GetOutputSizePixel(); + Point aOffset( (aSize.Width() - aPreviewSize.Width()) / 2, + (aSize.Height() - aPreviewSize.Height()) / 2 ); + const Size aLogicSize( maPageVDev.PixelToLogic( aPreviewSize, MapMode( MAP_100TH_MM ) ) ); + double fScale = double(aLogicSize.Width())/double(maOrigSize.Width()); - maPageVDev.Erase(); - maPageVDev.Push(); - maPageVDev.SetMapMode( MAP_100TH_MM ); - aMtf.WindStart(); - aMtf.Scale( fScale, fScale ); - aMtf.WindStart(); - aMtf.Play( &maPageVDev, Point( 0, 0 ), aLogicSize ); - maPageVDev.Pop(); - SetMapMode( MAP_PIXEL ); - maPageVDev.SetMapMode( MAP_PIXEL ); - DrawOutDev( aOffset, aPreviewSize, Point( 0, 0 ), aPreviewSize, maPageVDev ); + maPageVDev.Erase(); + maPageVDev.Push(); + maPageVDev.SetMapMode( MAP_100TH_MM ); + aMtf.WindStart(); + aMtf.Scale( fScale, fScale ); + aMtf.WindStart(); + aMtf.Play( &maPageVDev, Point( 0, 0 ), aLogicSize ); + maPageVDev.Pop(); - DecorationView aVw( this ); - aOffset.X() -= 1; aOffset.Y() -=1; aPreviewSize.Width() += 2; aPreviewSize.Height() += 2; - aVw.DrawFrame( Rectangle( aOffset, aPreviewSize ), FRAME_DRAW_GROUP ); + SetMapMode( MAP_PIXEL ); + maPageVDev.SetMapMode( MAP_PIXEL ); + DrawOutDev( aOffset, aPreviewSize, Point( 0, 0 ), aPreviewSize, maPageVDev ); + + DecorationView aVw( this ); + aOffset.X() -= 1; aOffset.Y() -=1; aPreviewSize.Width() += 2; aPreviewSize.Height() += 2; + aVw.DrawFrame( Rectangle( aOffset, aPreviewSize ), FRAME_DRAW_GROUP ); + } } void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) @@ -151,10 +167,14 @@ void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) } } -void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview, const Size& i_rOrigSize ) +void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview, + const Size& i_rOrigSize, + const rtl::OUString& i_rReplacement + ) { maMtf = i_rNewPreview; maOrigSize = i_rOrigSize; + maReplacementString = i_rReplacement; Resize(); Invalidate(); } @@ -1602,13 +1622,8 @@ void PrintDialog::updatePrinterText() void PrintDialog::setPreviewText( sal_Int32 ) { - if( mnCachedPages != 0 ) - { - rtl::OUString aNewText( searchAndReplace( maPageStr, "%n", 2, rtl::OUString::valueOf( mnCachedPages ) ) ); - maNumPagesText.SetText( aNewText ); - } - else - maNumPagesText.SetText( maNoPageStr ); + rtl::OUString aNewText( searchAndReplace( maPageStr, "%n", 2, rtl::OUString::valueOf( mnCachedPages ) ) ); + maNumPagesText.SetText( aNewText ); } void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) @@ -1638,7 +1653,7 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) else maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); - maPreviewWindow.setPreview( aMtf, maCurPageSize ); + maPreviewWindow.setPreview( aMtf, maCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr ); maForwardBtn.Enable( mnCurPage < nPages-1 ); maBackwardBtn.Enable( mnCurPage != 0 ); -- cgit From 6e492713b1d5f680e7f0f65c184184332c2619f6 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 11 Aug 2009 16:04:23 +0000 Subject: #i92516# add: PrinterOptionsHelper::setValue --- vcl/inc/vcl/print.hxx | 5 +++++ vcl/source/gdi/print3.cxx | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index ce4bc7ba63cb..0a290cb6adcc 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -542,6 +542,11 @@ class VCL_DLLPUBLIC PrinterOptionsHelper // returns an empty Any for not existing properties com::sun::star::uno::Any getValue( const rtl::OUString& i_rPropertyName ) const; + // change a value in the property set; this will not have an effect to an eventual PrinterController + // the user of setValue must decide whether it is necessary to set the value there also + void setValue( const rtl::OUString& i_rPropertyName, const com::sun::star::uno::Any& i_rValue ); + void setValue( const char* i_pPropertyName, const com::sun::star::uno::Any& i_rValue ) + { setValue( rtl::OUString::createFromAscii( i_pPropertyName ), i_rValue ); } sal_Bool getBoolValue( const rtl::OUString& i_rPropertyName, sal_Bool i_bDefault = sal_False ) const; // convenience for fixed strings diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index bb8c3ba1e041..bd18110574b6 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1241,6 +1241,11 @@ Any PrinterOptionsHelper::getValue( const rtl::OUString& i_rPropertyName ) const return aRet; } +void PrinterOptionsHelper::setValue( const rtl::OUString& i_rPropertyName, const Any& i_rValue ) +{ + m_aPropertyMap[ i_rPropertyName ] = i_rValue; +} + bool PrinterOptionsHelper::hasProperty( const rtl::OUString& i_rPropertyName ) const { Any aRet; -- cgit From 4cd5a62fc2763b867e4ef1277110cadc3caea366 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 12 Aug 2009 09:46:09 +0000 Subject: #i92516# add missing help ids --- vcl/source/window/printdlg.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 09ae7cabf5d2..979dbdbde99e 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -291,6 +291,7 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maPageMarginEdt.SetDecimalDigits( nDigits ); maSheetMarginEdt.SetDecimalDigits( nDigits ); + SMHID1( "NUpPage" ); maNupLine.SMHID2("NUpPage", "Layout"); maBrochureBtn.SMHID2("NUpPage", "Brochure" ); maPagesBtn.SMHID2( "NUpPage", "PagesPerSheet" ); @@ -462,6 +463,8 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maLayout( NULL, true ) { FreeResource(); + + SMHID1( "JobPage" ); maPrinterFL.SMHID2( "JobPage", "Printer" ); maPrinters.SMHID2( "JobPage", "PrinterList" ); maStatusLabel.SMHID2( "JobPage", "StatusLabel" ); @@ -624,6 +627,7 @@ PrintDialog::OutputOptPage::OutputOptPage( Window* i_pParent, const ResId& i_rRe , maReverseOrderBox( this, VclResId( SV_PRINT_OPT_REVERSE ) ) { FreeResource(); + SMHID1( "OptPage" ); maOptionsLine.SMHID2( "OptPage", "Options" ); maToFileBox.SMHID2( "OptPage", "ToFile" ); maCollateSingleJobsBox.SMHID2( "OptPage", "SingleJobs" ); @@ -826,6 +830,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Wed, 12 Aug 2009 12:30:24 +0000 Subject: #i96402# set duplex mode from API --- vcl/source/gdi/print3.cxx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index bd18110574b6..8338e6128561 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -45,6 +45,7 @@ #include "com/sun/star/ui/dialogs/XFilterManager.hpp" #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp" +#include "com/sun/star/view/DuplexMode.hpp" #include "com/sun/star/lang/XMultiServiceFactory.hpp" #include "com/sun/star/awt/Size.hpp" #include "comphelper/processfactory.hxx" @@ -1208,6 +1209,20 @@ void PrinterController::pushPropertiesToPrinter() if( pVal ) pVal->Value >>= bCollate; mpImplData->mpPrinter->SetCopyCount( static_cast(nCopyCount), bCollate ); + + // duplex mode + pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DuplexMode" ) ) ); + if( pVal ) + { + sal_Int16 nDuplex = view::DuplexMode::UNKNOWN; + pVal->Value >>= nDuplex; + switch( nDuplex ) + { + case view::DuplexMode::OFF: mpImplData->mpPrinter->SetDuplexMode( DUPLEX_OFF ); break; + case view::DuplexMode::LONGEDGE: mpImplData->mpPrinter->SetDuplexMode( DUPLEX_LONGEDGE ); break; + case view::DuplexMode::SHORTEDGE: mpImplData->mpPrinter->SetDuplexMode( DUPLEX_SHORTEDGE ); break; + } + } } bool PrinterController::isShowDialogs() const -- cgit From 14ede6d1a846952d8a7e283fb174b2804666c7f3 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 12 Aug 2009 12:59:21 +0000 Subject: #i92516# set smart helpid on parent like old help ids --- vcl/inc/vcl/tabctrl.hxx | 2 +- vcl/source/control/tabctrl.cxx | 50 +++++++++++++++++++++++------------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/vcl/inc/vcl/tabctrl.hxx b/vcl/inc/vcl/tabctrl.hxx index f5e0b64b58ee..09f4550dd8e5 100644 --- a/vcl/inc/vcl/tabctrl.hxx +++ b/vcl/inc/vcl/tabctrl.hxx @@ -73,7 +73,7 @@ private: BOOL mbRestoreUnqId; BOOL mbSingleLine; BOOL mbScroll; - BOOL mbColored; + BOOL mbRestoreSmartId; BOOL mbSmallInvalidate; BOOL mbExtraSpace; Link maActivateHdl; diff --git a/vcl/source/control/tabctrl.cxx b/vcl/source/control/tabctrl.cxx index b13be2f43b3d..24da946574de 100644 --- a/vcl/source/control/tabctrl.cxx +++ b/vcl/source/control/tabctrl.cxx @@ -30,26 +30,23 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#include - -#ifndef _SV_RC_H -#include -#endif -#include -#ifndef _SV_APP_HXX -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include "tools/debug.hxx" + +#include "tools/rc.h" +#include "vcl/svdata.hxx" +#include "vcl/svapp.hxx" +#include "vcl/help.hxx" +#include "vcl/event.hxx" +#include "vcl/menu.hxx" +#include "vcl/button.hxx" +#include "vcl/tabpage.hxx" +#include "vcl/tabctrl.hxx" +#include "vcl/controllayout.hxx" +#include "vcl/sound.hxx" +#include "vcl/lstbox.hxx" +#include "vcl/smartid.hxx" + +#include "vcl/window.h" #include #include @@ -156,7 +153,7 @@ void TabControl::ImplInit( Window* pParent, WinBits nStyle ) mbRestoreUnqId = FALSE; mbSingleLine = FALSE; mbScroll = FALSE; - mbColored = FALSE; + mbRestoreSmartId = FALSE; mbSmallInvalidate = FALSE; mbExtraSpace = FALSE; mpTabCtrlData = new ImplTabCtrlData; @@ -713,6 +710,8 @@ void TabControl::ImplChangeTabPage( USHORT nId, USHORT nOldId ) pCtrlParent->SetHelpId( 0 ); if ( mbRestoreUnqId ) pCtrlParent->SetUniqueId( 0 ); + if( mbRestoreSmartId ) + pCtrlParent->SetSmartHelpId( SmartId() ); pOldPage->DeactivatePage(); } @@ -720,8 +719,8 @@ void TabControl::ImplChangeTabPage( USHORT nId, USHORT nOldId ) { pPage->SetPosSizePixel( aRect.TopLeft(), aRect.GetSize() ); - // Hier Page aktivieren, damit die Controls entsprechend umgeschaltet - // werden koennen und HilfeId gegebenenfalls beim Parent umsetzen + // activate page here so the conbtrols can be switched + // also set the help id of the parent window to that of the tab page if ( !GetHelpId() ) { mbRestoreHelpId = TRUE; @@ -732,6 +731,11 @@ void TabControl::ImplChangeTabPage( USHORT nId, USHORT nOldId ) mbRestoreUnqId = TRUE; pCtrlParent->SetUniqueId( pPage->GetUniqueId() ); } + if( ! GetSmartHelpId().HasAny() ) + { + mbRestoreSmartId = TRUE; + pCtrlParent->SetSmartHelpId( pPage->GetSmartHelpId() ); + } pPage->ActivatePage(); -- cgit From 2c142f8529e0a0c3aa18d7d5819f95cab90efc86 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 12 Aug 2009 16:37:34 +0000 Subject: #i92516# corrected paper size handling --- vcl/aqua/source/gdi/salprn.cxx | 10 +++++----- vcl/inc/vcl/prndlg.hxx | 1 - vcl/source/window/printdlg.cxx | 10 ++++------ 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 6575f89d3fa0..a9a58799f4db 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -304,7 +304,7 @@ void AquaSalInfoPrinter::setPaperSize( long i_nWidth, long i_nHeight, Orientatio { Orientation ePaperOrientation = ORIENTATION_PORTRAIT; - const PaperInfo* pPaper = matchPaper( (i_nWidth+50)/100, (i_nHeight+50)/100, ePaperOrientation ); + const PaperInfo* pPaper = matchPaper( i_nWidth, i_nHeight, ePaperOrientation ); if( pPaper ) { @@ -807,8 +807,8 @@ void AquaSalInfoPrinter::InitPaperFormats( const ImplJobSetup* i_pSetupData ) NSSize aPaperSize = [mpPrinter pageSizeForPaper: pPaper]; if( aPaperSize.width > 0 && aPaperSize.height > 0 ) { - PaperInfo aInfo( (PtTo10Mu( aPaperSize.width ) + 50 ) / 100, - (PtTo10Mu( aPaperSize.height ) + 50 ) / 100 ); + PaperInfo aInfo( PtTo10Mu( aPaperSize.width ), + PtTo10Mu( aPaperSize.height ) ); m_aPaperFormats.push_back( aInfo ); } } @@ -828,8 +828,8 @@ const PaperInfo* AquaSalInfoPrinter::matchPaper( long i_nWidth, long i_nHeight, { for( size_t i = 0; i < m_aPaperFormats.size(); i++ ) { - if( abs( m_aPaperFormats[i].getWidth() - i_nWidth ) < 2 && - abs( m_aPaperFormats[i].getHeight() - i_nHeight ) < 2 ) + if( abs( m_aPaperFormats[i].getWidth() - i_nWidth ) < 50 && + abs( m_aPaperFormats[i].getHeight() - i_nHeight ) < 50 ) { pMatch = &m_aPaperFormats[i]; return pMatch; diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 182b77c1827d..6c347900aa3d 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -228,7 +228,6 @@ namespace vcl rtl::OUString maNoPageStr; sal_Int32 mnCurPage; sal_Int32 mnCachedPages; - Size maCurPageSize; std::list< Window* > maControls; std::map< Window*, rtl::OUString > maControlToPropertyMap; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 979dbdbde99e..71adbad3f225 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1647,18 +1647,16 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) maPageEdit.SetMin( 1 ); maPageEdit.SetMax( nPages ); - boost::shared_ptr aPrt( maPController->getPrinter() ); - if( i_bNewPage ) { const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; if( nPages > 0 ) - maCurPageSize = maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); - else - maCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); + maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); - maPreviewWindow.setPreview( aMtf, maCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr ); + boost::shared_ptr aPrt( maPController->getPrinter() ); + Size aCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); + maPreviewWindow.setPreview( aMtf, aCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr ); maForwardBtn.Enable( mnCurPage < nPages-1 ); maBackwardBtn.Enable( mnCurPage != 0 ); -- cgit From 5366ddcc1129a384ec9585d54689b991fbe80efd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 13 Aug 2009 11:31:18 +0000 Subject: #i92516# set correct page size for N-Up in getFilteredPage() --- vcl/source/gdi/print3.cxx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 8338e6128561..375947c867ec 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -816,6 +816,9 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o } o_rMtf.WindStart(); + mpImplData->mpPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); + mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize ); + return aPaperSize; } -- cgit From b0434f112b7e3dc67dec0c0165e3fd49086c7fb5 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 13 Aug 2009 15:10:43 +0000 Subject: #i92516# handle MAP_PIXEL in preview --- vcl/inc/vcl/prndlg.hxx | 4 +++- vcl/inc/vcl/virdev.hxx | 11 +++++++++-- vcl/source/gdi/virdev.cxx | 29 +++++++++++++++++++++-------- vcl/source/window/printdlg.cxx | 10 ++++++++-- 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 6c347900aa3d..9ea5be6e10b8 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -68,7 +68,9 @@ namespace vcl virtual void Command( const CommandEvent& ); virtual void Resize(); - void setPreview( const GDIMetaFile&, const Size&, const rtl::OUString& ); + void setPreview( const GDIMetaFile&, const Size&, const rtl::OUString&, + sal_Int32 i_nDPIX, sal_Int32 i_nDPIY + ); }; class ShowNupOrderWindow : public Window diff --git a/vcl/inc/vcl/virdev.hxx b/vcl/inc/vcl/virdev.hxx index bc21dde6f4ac..ea2b49eb8290 100644 --- a/vcl/inc/vcl/virdev.hxx +++ b/vcl/inc/vcl/virdev.hxx @@ -74,7 +74,6 @@ private: #define REFDEV_FORCE_ZERO_EXTLEAD 0x80 SAL_DLLPRIVATE bool ForceZeroExtleadBug() const { return ((meRefDevMode & REFDEV_FORCE_ZERO_EXTLEAD) != 0); } - public: VirtualDevice( USHORT nBitCount = 0 ); VirtualDevice( const OutputDevice& rCompDev, @@ -115,11 +114,19 @@ public: REFDEV_MODE06 = 1, // 600 dpi REFDEV_MODE48 = 2, // 4800 dpi REFDEV_MODE_MSO1 = 3, - REFDEV_MODE_PDF1 = 4 }; + REFDEV_MODE_PDF1 = 4, + REFDEV_CUSTOM = 5 + }; void SetReferenceDevice( RefDevMode ); void Compat_ZeroExtleadBug(); // enable workaround for #i60495# + + void SetReferenceDevice( sal_Int32 i_nDPIX, sal_Int32 i_nDPIY ); + +private: + SAL_DLLPRIVATE void ImplSetReferenceDevice( RefDevMode, sal_Int32 i_nDPIX, sal_Int32 i_nDPIY ); + }; #endif // _SV_VIRDEV_HXX diff --git a/vcl/source/gdi/virdev.cxx b/vcl/source/gdi/virdev.cxx index f1c532a9295f..a13e272e368b 100644 --- a/vcl/source/gdi/virdev.cxx +++ b/vcl/source/gdi/virdev.cxx @@ -359,27 +359,40 @@ BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase ) // ----------------------------------------------------------------------- -void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode ) +void VirtualDevice::SetReferenceDevice( RefDevMode i_eRefDevMode ) { - switch( eRefDevMode ) + sal_Int32 nDPIX = 600, nDPIY = 600; + switch( i_eRefDevMode ) { case REFDEV_NONE: default: DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" ); - // fall through + break; case REFDEV_MODE06: - mnDPIX = mnDPIY = 600; + nDPIX = nDPIY = 600; break; case REFDEV_MODE48: - mnDPIX = mnDPIY = 4800; + nDPIX = nDPIY = 4800; break; case REFDEV_MODE_MSO1: - mnDPIX = mnDPIY = 6*1440; + nDPIX = nDPIY = 6*1440; break; case REFDEV_MODE_PDF1: - mnDPIX = mnDPIY = 720; + nDPIX = nDPIY = 720; break; } + ImplSetReferenceDevice( i_eRefDevMode, nDPIX, nDPIY ); +} + +void VirtualDevice::SetReferenceDevice( sal_Int32 i_nDPIX, sal_Int32 i_nDPIY ) +{ + ImplSetReferenceDevice( REFDEV_CUSTOM, i_nDPIX, i_nDPIY ); +} + +void VirtualDevice::ImplSetReferenceDevice( RefDevMode i_eRefDevMode, sal_Int32 i_nDPIX, sal_Int32 i_nDPIY ) +{ + mnDPIX = i_nDPIX; + mnDPIY = i_nDPIY; EnableOutput( FALSE ); // prevent output on reference device mbScreenComp = FALSE; @@ -391,7 +404,7 @@ void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode ) // avoid adjusting font lists when already in refdev mode BYTE nOldRefDevMode = meRefDevMode; BYTE nOldCompatFlag = (BYTE)meRefDevMode & REFDEV_FORCE_ZERO_EXTLEAD; - meRefDevMode = (BYTE)(eRefDevMode | nOldCompatFlag); + meRefDevMode = (BYTE)(i_eRefDevMode | nOldCompatFlag); if( (nOldRefDevMode ^ nOldCompatFlag) != REFDEV_NONE ) return; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 71adbad3f225..38ddb66877d0 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -169,12 +169,16 @@ void PrintDialog::PrintPreviewWindow::Command( const CommandEvent& rEvt ) void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPreview, const Size& i_rOrigSize, - const rtl::OUString& i_rReplacement + const rtl::OUString& i_rReplacement, + sal_Int32 i_nDPIX, + sal_Int32 i_nDPIY ) { maMtf = i_rNewPreview; maOrigSize = i_rOrigSize; maReplacementString = i_rReplacement; + maPageVDev.SetReferenceDevice( i_nDPIX, i_nDPIY ); + maPageVDev.EnableOutput( TRUE ); Resize(); Invalidate(); } @@ -1656,7 +1660,9 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) boost::shared_ptr aPrt( maPController->getPrinter() ); Size aCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); - maPreviewWindow.setPreview( aMtf, aCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr ); + maPreviewWindow.setPreview( aMtf, aCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr, + aPrt->ImplGetDPIX(), aPrt->ImplGetDPIY() + ); maForwardBtn.Enable( mnCurPage < nPages-1 ); maBackwardBtn.Enable( mnCurPage != 0 ); -- cgit -- cgit From 12bb9be1d55b74bb2ff7a01f778919b6fead9045 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 15 Aug 2009 16:24:00 +0000 Subject: #92516# hid for vcl dialog --- vcl/inc/vcl/solar.hrc | 314 ++++++++++++++++++++++++++++++++++++++++++++++++++ vcl/inc/vcl/svids.hrc | 4 + vcl/prj/d.lst | 1 + vcl/util/hidother.src | 34 ++++++ vcl/util/makefile.mk | 1 + 5 files changed, 354 insertions(+) create mode 100644 vcl/inc/vcl/solar.hrc create mode 100644 vcl/util/hidother.src diff --git a/vcl/inc/vcl/solar.hrc b/vcl/inc/vcl/solar.hrc new file mode 100644 index 000000000000..a0cfcddd1b92 --- /dev/null +++ b/vcl/inc/vcl/solar.hrc @@ -0,0 +1,314 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _SOLAR_HRC +#define _SOLAR_HRC + +// defines ------------------------------------------------------------------ + +#define CREATERESMGR_NAME( Name ) #Name +#define CREATERESMGR( Name ) ResMgr::CreateResMgr( CREATERESMGR_NAME( Name ) ) + +#define RID_SFX_START 260 +#define RID_SFX_END 9999 + +#define RID_LIB_START 10000 +#define RID_LIB_END 19999 + +#define RID_SVX_START (RID_LIB_START) +#define RID_SVX_END (RID_LIB_START+499) + +#define RID_SBASIC_START (RID_LIB_START+500) +#define RID_SBASIC_END (RID_LIB_START+2999) + +#define RID_BASIC_START (RID_LIB_START+3000) +#define RID_BASIC_END (RID_LIB_START+4499) + +#define RID_UUI_START (RID_LIB_START+4500) +#define RID_UUI_END (RID_LIB_START+4599) + +#define RID_HELP_START (RID_LIB_START+4600) +#define RID_HELP_END (RID_LIB_START+4799) + +#define RID_MAIL_START (RID_LIB_START+4800) +#define RID_MAIL_END (RID_LIB_START+4849) + +#define RID_BASICIDE_START (RID_LIB_START+4850) +#define RID_BASICIDE_END (RID_LIB_START+4949) + +#define RID_SVXITEMS_START (RID_LIB_START+4950) +#define RID_SVXITEMS_END (RID_LIB_START+5599) + +#define RID_SBA_START (RID_LIB_START+5600) +#define RID_SBA_END (RID_LIB_START+5649) + +#define RID_ISETBRW_START (RID_LIB_START+5650) +#define RID_ISETBRW_END (RID_LIB_START+5699) + +#define RID_EXTENSIONS_START (RID_LIB_START+5700) +#define RID_EXTENSIONS_END (RID_LIB_START+5799) + +#define RID_EDIT_START (RID_LIB_START+5800) +#define RID_EDIT_END (RID_LIB_START+5899) + +#define RID_EDIT_START (RID_LIB_START+5800) +#define RID_EDIT_END (RID_LIB_START+5899) + +#define RID_OUTL_START (RID_LIB_START+5900) +#define RID_OUTL_END (RID_LIB_START+5919) + +#define RID_SVTOOLS_START (RID_LIB_START+5920) +#define RID_SVTOOLS_END (RID_LIB_START+5999) + +#define RID_INET_START (RID_LIB_START+6000) +#define RID_INET_END (RID_LIB_START+6059) + +#define RID_SO2_START (RID_LIB_START+6060) +#define RID_SO2_END (RID_LIB_START+6099) + +#define RID_GOODIES_START (RID_LIB_START+6100) +#define RID_GOODIES_END (RID_LIB_START+6149) + +#define RID_SJ_START (RID_LIB_START+6150) +#define RID_SJ_END (RID_LIB_START+6199) + +#define RID_SI_START (RID_LIB_START+6200) +#define RID_SI_END (RID_LIB_START+6399) + +#define RID_DLG_START (RID_LIB_START+6400) +#define RID_DLG_END (RID_LIB_START+6499) + +#define RID_OFA_START (RID_LIB_START+6500) +#define RID_OFA_END (RID_LIB_START+6999) + +#define RID_CHANNEL_START (RID_LIB_START+7000) +#define RID_CHANNEL_END (RID_LIB_START+7499) + +#define RID_CHAOS_START (RID_LIB_START+7500) +#define RID_CHAOS_END (RID_LIB_START+7999) + +#define RID_FORMS_START (RID_LIB_START+8000) +#define RID_FORMS_END (RID_LIB_START+8999) + +#define RID_FORMLAYER_START (RID_LIB_START+9000) +#define RID_FORMLAYER_END (RID_LIB_START+9199) + +#define RID_DBACCESS_START (RID_LIB_START+9200) +#define RID_DBACCESS_END (RID_LIB_START+9699) + +#define RID_MORE_EXTENSIONS_START (RID_LIB_START+9700) +#define RID_MORE_EXTENSIONS_END (RID_LIB_START+9999) + +#define RID_DB_EXTENSIONS_START (RID_LIB_START+10000) +#define RID_DB_EXTENSIONS_END (RID_LIB_START+10199) + +#define RID_FILTER_START (RID_LIB_START+10200) +#define RID_FILTER_END (RID_LIB_START+10299) + +#define RID_APP_START 20000 +#define RID_APP_END 31999 + +#define RID_SW_START (20000) +#define RID_SW_END (25999) + +#define RID_SC_START (26000) +#define RID_SC_END (26999) + +#define RID_SD_START (27000) +#define RID_SD_END (27999) + +#define RID_Sa_START (28000) +#define RID_Sa_END (28999) + +#define RID_Sb_START (29000) +#define RID_Sb_END (29999) + +#define RID_OBJ_START (30000) +#define RID_OBJ_END (32767) + +#define RID_SIM_START (RID_OBJ_START+ 0) +#define RID_SIM_END (RID_OBJ_START+ 255) + +#define RID_SMA_START (RID_OBJ_START+ 256) +#define RID_SMA_END (RID_OBJ_START+ 511) + +#define RID_SCH_START (RID_OBJ_START+ 512) +#define RID_SCH_END (RID_OBJ_START+ 767) + +#define RID_RPT_START (RID_OBJ_START+768) +#define RID_RPT_END (RID_OBJ_START+1000) + +#define RID_FORMULA_START (RID_OBJ_START+1001) +#define RID_FORMULA_END (RID_OBJ_START+1200) +// Help-Ids -------------------------------------------------------------- + +#define HID_OK_BUTTON 0 +#define HID_CANCEL_BUTTON 0 +#define HID_HELP_BUTTON 0 + +#define HID_START 32768 + +#define HID_VCL_START (HID_START+100) +#define HID_VCL_END (HID_START+150) + +#define HID_SVTOOLS_START (HID_START+200) +#define HID_SVTOOLS_END (HID_START+299) + +#define HID_SFX_START (HID_START+300) +#define HID_SFX_END (HID_START+999) + +#define HID_LIB_START (HID_START+1000) +#define HID_LIB_END (HID_START+19999) + +#define HID_SVX_START (HID_LIB_START) +#define HID_SVX_END (HID_LIB_START+431) + +#define HID_WIZARD_START (HID_LIB_START+432) +#define HID_WIZARD_END (HID_LIB_START+999) +//please note: There is also HID_WIZARD2 below + +#define HID_EXTENSIONS_START (HID_LIB_START+1000) +#define HID_EXTENSIONS_END (HID_LIB_START+1099) + +#define HID_SO2_START (HID_LIB_START+1100) +#define HID_SO2_END (HID_LIB_START+1149) + +#define HID_MAIL_START (HID_LIB_START+1150) +#define HID_MAIL_END (HID_LIB_START+1199) + +#define HID_INET_START (HID_LIB_START+1200) +#define HID_INET_END (HID_LIB_START+1259) + +#define HID_OFA_START (HID_LIB_START+1260) +#define HID_OFA_END (HID_LIB_START+1399) + +#define HID_HELP_START (HID_LIB_START+2000) +#define HID_HELP_END (HID_LIB_START+2050) + +#define HID_CHAOS_START (HID_LIB_START+2051) +#define HID_CHAOS_END (HID_LIB_START+2069) + +#define HID_UUI_START (HID_LIB_START+2070) +#define HID_UUI_END (HID_LIB_START+2099) + +#define HID_GOODIES_START (HID_LIB_START+2100) +#define HID_GOODIES_END (HID_LIB_START+2199) + +#if 0 // currently unused range +#define HID_SCHEDULE_START (HID_LIB_START+2200) +#define HID_SCHEDULE_END (HID_LIB_START+3399) +#endif + +#define HID_CHANNEL_START (HID_LIB_START+3400) +#define HID_CHANNEL_END (HID_LIB_START+3499) + +#define HID_SBA_START (HID_LIB_START+ 3500) +#define HID_SBA_END (HID_LIB_START+ 3999) + +#define HID_FORMS_START (HID_LIB_START+4000) +#define HID_FORMS_END (HID_LIB_START+4999) + +#define HID_DBACCESS_START (HID_LIB_START+5000) +#define HID_DBACCESS_END (HID_LIB_START+5299) + +#define HID_PORTAL_START (HID_LIB_START+5300) +#define HID_PORTAL_END (HID_LIB_START+5599) + +#define HID_PORTAL_ADMIN_START (HID_LIB_START+5600) +#define HID_PORTAL_ADMIN_END (HID_LIB_START+5999) + +#define HID_SYNCACCESS_START (HID_LIB_START+6000) +#define HID_SYNCACCESS_END (HID_LIB_START+6099) + +#define HID_SVX_EXT0_START (HID_LIB_START+6100) +#define HID_SVX_EXT0_END (HID_LIB_START+6599) + +#define HID_FRAMEWORK_START (HID_LIB_START+6600) +#define HID_FRAMEWORK_END (HID_LIB_START+6999) + +#define HID_WIZARD2_START (HID_LIB_START+7000) +#define HID_WIZARD2_END (HID_LIB_START+8999) + +#define HID_DESKTOP_START (HID_LIB_START+9000) +#define HID_DESKTOP_END (HID_LIB_START+9299) + +#define HID_XMLSECURITY_START (HID_LIB_START+9300) +#define HID_XMLSECURITY_END (HID_LIB_START+9999) + +#define HID_APP_START (HID_START+20000) +#define HID_APP_END (HID_START+29999) + +#define HID_SW_START (HID_START+20000) +#define HID_SW_END (HID_START+24999) + +#define HID_SC_START (HID_START+25000) +#define HID_SC_END (HID_START+26999) + +#define HID_SD_START (HID_START+27000) +#define HID_SD_END (HID_START+27999) + +#define HID_Sa_START (HID_START+28000) +#define HID_Sa_END (HID_START+28999) + +#define HID_Sb_START (HID_START+29000) +#define HID_Sb_END (HID_START+29999) + +#define HID_OBJ_START (HID_START+30000) +#define HID_OBJ_END (HID_START+32767) + +#define HID_SIM_START (HID_OBJ_START+ 0) +#define HID_SIM_END (HID_OBJ_START+ 239) + +#define HID_AVMEDIA_START (HID_OBJ_START+ 240) +#define HID_AVMEDIA_END (HID_OBJ_START+ 255) + +#define HID_SMA_START (HID_OBJ_START+ 256) +#define HID_SMA_END (HID_OBJ_START+ 511) + +#define HID_SCH_START (HID_OBJ_START+ 512) +#define HID_SCH_END (HID_OBJ_START+ 767) + +#define HID_BASICIDE_START (HID_OBJ_START+ 768) +#define HID_BASICIDE_END (HID_OBJ_START+1023) + +#define HID_SMA2_START (HID_OBJ_START+1024) +#define HID_SMA2_END (HID_OBJ_START+1280) + +#define HID_FILTER_START (HID_OBJ_START+1281) +#define HID_FILTER_END (HID_OBJ_START+1580) + +#define HID_LICENSING_START (HID_OBJ_START+1581) +#define HID_LICENSING_END (HID_OBJ_START+1680) + +#define HID_RPT_START (HID_OBJ_START+1681) +#define HID_RPT_END (HID_OBJ_START+2080) + +#define HID_FORMULA_START (HID_OBJ_START+2081) +#define HID_FORMULA_END (HID_OBJ_START+2280) + +#endif + diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 427ee4426a09..f21aa6a4cd20 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -31,6 +31,8 @@ #ifndef _SV_SVIDS_HRC #define _SV_SVIDS_HRC +#include "vcl/solar.hrc" + #define SV_RESID_STDOFFSET 0 #define SV_RESID_WINOFFSET 1 #define SV_RESID_OS2OFFSET 2 @@ -249,4 +251,6 @@ #define SV_ICON_ID_MACRO 17 #define SV_ICON_ID_PRINTERADMIN 501 +#define HID_PRINTDLG HID_VCL_START + #endif // _SV_SVIDS_HRC diff --git a/vcl/prj/d.lst b/vcl/prj/d.lst index a8b308aea462..1fb975c129d9 100644 --- a/vcl/prj/d.lst +++ b/vcl/prj/d.lst @@ -15,6 +15,7 @@ mkdir: %_DEST%\inc%_EXT%\vcl\plug\vcl ..\%__SRC%\obj\salmain.obj %_DEST%\lib%_EXT%\salmain.obj ..\%__SRC%\obj\salmain.o %_DEST%\lib%_EXT%\salmain.o +..\inc\vcl\solar.hrc %_DEST%\inc%_EXT%\vcl\solar.hrc ..\inc\vcl\accel.hxx %_DEST%\inc%_EXT%\vcl\accel.hxx ..\inc\vcl\alpha.hxx %_DEST%\inc%_EXT%\vcl\alpha.hxx ..\inc\vcl\animate.hxx %_DEST%\inc%_EXT%\vcl\animate.hxx diff --git a/vcl/util/hidother.src b/vcl/util/hidother.src new file mode 100644 index 000000000000..ab10a1e4c4ea --- /dev/null +++ b/vcl/util/hidother.src @@ -0,0 +1,34 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: hidother.src,v $ + * $Revision: 1.20 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "vcl/svids.hrc" + +hidspecial HID_PRINTDLG { HelpID = HID_PRINTDLG; }; + diff --git a/vcl/util/makefile.mk b/vcl/util/makefile.mk index 96c28980118f..000db0e34f3d 100644 --- a/vcl/util/makefile.mk +++ b/vcl/util/makefile.mk @@ -35,6 +35,7 @@ PRJNAME=vcl TARGET=vcl TARGETTYPE=GUI USE_DEFFILE=TRUE +GEN_HID_OTHER=TRUE .IF "$(SNDFILE_LIBS)"!="" SNDFILELIB=$(SNDFILE_LIBS) -- cgit From 25b00175008c8a8f027d752e92dee0df7c4fb0bd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 15 Aug 2009 16:25:13 +0000 Subject: #92516# hid for vcl dialog --- svtools/bmpmaker/bmp.cxx | 2 +- svtools/bmpmaker/bmpsum.cxx | 2 +- svtools/inc/svtools/helpid.hrc | 2 +- svtools/inc/svtools/solar.hrc | 312 --------------------- svtools/inc/svtools/svtools.hrc | 2 +- svtools/prj/d.lst | 1 - .../filter.vcl/filter/SvFilterOptionsDialog.cxx | 2 +- svtools/source/filter.vcl/filter/filter.cxx | 2 +- svtools/source/plugapp/testtool.src | 2 +- svtools/source/uno/unoifac2.hrc | 2 +- svtools/workben/unodialog/udlg_global.hrc | 2 +- 11 files changed, 9 insertions(+), 322 deletions(-) delete mode 100644 svtools/inc/svtools/solar.hrc diff --git a/svtools/bmpmaker/bmp.cxx b/svtools/bmpmaker/bmp.cxx index df20c7e05376..52e2cb5fa7b0 100644 --- a/svtools/bmpmaker/bmp.cxx +++ b/svtools/bmpmaker/bmp.cxx @@ -43,7 +43,7 @@ using namespace std; #include -#include "svtools/solar.hrc" +#include "vcl/solar.hrc" #include "filedlg.hxx" #include "bmpcore.hxx" #include "bmp.hrc" diff --git a/svtools/bmpmaker/bmpsum.cxx b/svtools/bmpmaker/bmpsum.cxx index 0633eb4c6a09..6ba0ac3cfc78 100644 --- a/svtools/bmpmaker/bmpsum.cxx +++ b/svtools/bmpmaker/bmpsum.cxx @@ -45,7 +45,7 @@ #include #include -#include "svtools/solar.hrc" +#include "vcl/solar.hrc" #define EXIT_NOERROR 0x00000000 #define EXIT_INVALIDFILE 0x00000001 diff --git a/svtools/inc/svtools/helpid.hrc b/svtools/inc/svtools/helpid.hrc index efbb0d2628d9..d18120b8c0d4 100644 --- a/svtools/inc/svtools/helpid.hrc +++ b/svtools/inc/svtools/helpid.hrc @@ -33,7 +33,7 @@ // include --------------------------------------------------------------- -#include +#include // Help-Ids -------------------------------------------------------------- diff --git a/svtools/inc/svtools/solar.hrc b/svtools/inc/svtools/solar.hrc deleted file mode 100644 index 348422ef6477..000000000000 --- a/svtools/inc/svtools/solar.hrc +++ /dev/null @@ -1,312 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: solar.hrc,v $ - * $Revision: 1.6 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef _SOLAR_HRC -#define _SOLAR_HRC - -// defines ------------------------------------------------------------------ - -#define CREATERESMGR_NAME( Name ) #Name -#define CREATERESMGR( Name ) ResMgr::CreateResMgr( CREATERESMGR_NAME( Name ) ) - -#define RID_SFX_START 260 -#define RID_SFX_END 9999 - -#define RID_LIB_START 10000 -#define RID_LIB_END 19999 - -#define RID_SVX_START (RID_LIB_START) -#define RID_SVX_END (RID_LIB_START+499) - -#define RID_SBASIC_START (RID_LIB_START+500) -#define RID_SBASIC_END (RID_LIB_START+2999) - -#define RID_BASIC_START (RID_LIB_START+3000) -#define RID_BASIC_END (RID_LIB_START+4499) - -#define RID_UUI_START (RID_LIB_START+4500) -#define RID_UUI_END (RID_LIB_START+4599) - -#define RID_HELP_START (RID_LIB_START+4600) -#define RID_HELP_END (RID_LIB_START+4799) - -#define RID_MAIL_START (RID_LIB_START+4800) -#define RID_MAIL_END (RID_LIB_START+4849) - -#define RID_BASICIDE_START (RID_LIB_START+4850) -#define RID_BASICIDE_END (RID_LIB_START+4949) - -#define RID_SVXITEMS_START (RID_LIB_START+4950) -#define RID_SVXITEMS_END (RID_LIB_START+5599) - -#define RID_SBA_START (RID_LIB_START+5600) -#define RID_SBA_END (RID_LIB_START+5649) - -#define RID_ISETBRW_START (RID_LIB_START+5650) -#define RID_ISETBRW_END (RID_LIB_START+5699) - -#define RID_EXTENSIONS_START (RID_LIB_START+5700) -#define RID_EXTENSIONS_END (RID_LIB_START+5799) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_OUTL_START (RID_LIB_START+5900) -#define RID_OUTL_END (RID_LIB_START+5919) - -#define RID_SVTOOLS_START (RID_LIB_START+5920) -#define RID_SVTOOLS_END (RID_LIB_START+5999) - -#define RID_INET_START (RID_LIB_START+6000) -#define RID_INET_END (RID_LIB_START+6059) - -#define RID_SO2_START (RID_LIB_START+6060) -#define RID_SO2_END (RID_LIB_START+6099) - -#define RID_GOODIES_START (RID_LIB_START+6100) -#define RID_GOODIES_END (RID_LIB_START+6149) - -#define RID_SJ_START (RID_LIB_START+6150) -#define RID_SJ_END (RID_LIB_START+6199) - -#define RID_SI_START (RID_LIB_START+6200) -#define RID_SI_END (RID_LIB_START+6399) - -#define RID_DLG_START (RID_LIB_START+6400) -#define RID_DLG_END (RID_LIB_START+6499) - -#define RID_OFA_START (RID_LIB_START+6500) -#define RID_OFA_END (RID_LIB_START+6999) - -#define RID_CHANNEL_START (RID_LIB_START+7000) -#define RID_CHANNEL_END (RID_LIB_START+7499) - -#define RID_CHAOS_START (RID_LIB_START+7500) -#define RID_CHAOS_END (RID_LIB_START+7999) - -#define RID_FORMS_START (RID_LIB_START+8000) -#define RID_FORMS_END (RID_LIB_START+8999) - -#define RID_FORMLAYER_START (RID_LIB_START+9000) -#define RID_FORMLAYER_END (RID_LIB_START+9199) - -#define RID_DBACCESS_START (RID_LIB_START+9200) -#define RID_DBACCESS_END (RID_LIB_START+9699) - -#define RID_MORE_EXTENSIONS_START (RID_LIB_START+9700) -#define RID_MORE_EXTENSIONS_END (RID_LIB_START+9999) - -#define RID_DB_EXTENSIONS_START (RID_LIB_START+10000) -#define RID_DB_EXTENSIONS_END (RID_LIB_START+10199) - -#define RID_FILTER_START (RID_LIB_START+10200) -#define RID_FILTER_END (RID_LIB_START+10299) - -#define RID_APP_START 20000 -#define RID_APP_END 31999 - -#define RID_SW_START (20000) -#define RID_SW_END (25999) - -#define RID_SC_START (26000) -#define RID_SC_END (26999) - -#define RID_SD_START (27000) -#define RID_SD_END (27999) - -#define RID_Sa_START (28000) -#define RID_Sa_END (28999) - -#define RID_Sb_START (29000) -#define RID_Sb_END (29999) - -#define RID_OBJ_START (30000) -#define RID_OBJ_END (32767) - -#define RID_SIM_START (RID_OBJ_START+ 0) -#define RID_SIM_END (RID_OBJ_START+ 255) - -#define RID_SMA_START (RID_OBJ_START+ 256) -#define RID_SMA_END (RID_OBJ_START+ 511) - -#define RID_SCH_START (RID_OBJ_START+ 512) -#define RID_SCH_END (RID_OBJ_START+ 767) - -#define RID_RPT_START (RID_OBJ_START+768) -#define RID_RPT_END (RID_OBJ_START+1000) - -#define RID_FORMULA_START (RID_OBJ_START+1001) -#define RID_FORMULA_END (RID_OBJ_START+1200) -// Help-Ids -------------------------------------------------------------- - -#define HID_OK_BUTTON 0 -#define HID_CANCEL_BUTTON 0 -#define HID_HELP_BUTTON 0 - -#define HID_START 32768 - -#define HID_SVTOOLS_START (HID_START+200) -#define HID_SVTOOLS_END (HID_START+299) - -#define HID_SFX_START (HID_START+300) -#define HID_SFX_END (HID_START+999) - -#define HID_LIB_START (HID_START+1000) -#define HID_LIB_END (HID_START+19999) - -#define HID_SVX_START (HID_LIB_START) -#define HID_SVX_END (HID_LIB_START+431) - -#define HID_WIZARD_START (HID_LIB_START+432) -#define HID_WIZARD_END (HID_LIB_START+999) -//please note: There is also HID_WIZARD2 below - -#define HID_EXTENSIONS_START (HID_LIB_START+1000) -#define HID_EXTENSIONS_END (HID_LIB_START+1099) - -#define HID_SO2_START (HID_LIB_START+1100) -#define HID_SO2_END (HID_LIB_START+1149) - -#define HID_MAIL_START (HID_LIB_START+1150) -#define HID_MAIL_END (HID_LIB_START+1199) - -#define HID_INET_START (HID_LIB_START+1200) -#define HID_INET_END (HID_LIB_START+1259) - -#define HID_OFA_START (HID_LIB_START+1260) -#define HID_OFA_END (HID_LIB_START+1399) - -#define HID_HELP_START (HID_LIB_START+2000) -#define HID_HELP_END (HID_LIB_START+2050) - -#define HID_CHAOS_START (HID_LIB_START+2051) -#define HID_CHAOS_END (HID_LIB_START+2069) - -#define HID_UUI_START (HID_LIB_START+2070) -#define HID_UUI_END (HID_LIB_START+2099) - -#define HID_GOODIES_START (HID_LIB_START+2100) -#define HID_GOODIES_END (HID_LIB_START+2199) - -#define HID_SCHEDULE_START (HID_LIB_START+2200) -#define HID_SCHEDULE_END (HID_LIB_START+3399) - -#define HID_CHANNEL_START (HID_LIB_START+3400) -#define HID_CHANNEL_END (HID_LIB_START+3499) - -#define HID_SBA_START (HID_LIB_START+ 3500) -#define HID_SBA_END (HID_LIB_START+ 3999) - -#define HID_FORMS_START (HID_LIB_START+4000) -#define HID_FORMS_END (HID_LIB_START+4999) - -#define HID_DBACCESS_START (HID_LIB_START+5000) -#define HID_DBACCESS_END (HID_LIB_START+5299) - -#define HID_PORTAL_START (HID_LIB_START+5300) -#define HID_PORTAL_END (HID_LIB_START+5599) - -#define HID_PORTAL_ADMIN_START (HID_LIB_START+5600) -#define HID_PORTAL_ADMIN_END (HID_LIB_START+5999) - -#define HID_SYNCACCESS_START (HID_LIB_START+6000) -#define HID_SYNCACCESS_END (HID_LIB_START+6099) - -#define HID_SVX_EXT0_START (HID_LIB_START+6100) -#define HID_SVX_EXT0_END (HID_LIB_START+6599) - -#define HID_FRAMEWORK_START (HID_LIB_START+6600) -#define HID_FRAMEWORK_END (HID_LIB_START+6999) - -#define HID_WIZARD2_START (HID_LIB_START+7000) -#define HID_WIZARD2_END (HID_LIB_START+8999) - -#define HID_DESKTOP_START (HID_LIB_START+9000) -#define HID_DESKTOP_END (HID_LIB_START+9299) - -#define HID_XMLSECURITY_START (HID_LIB_START+9300) -#define HID_XMLSECURITY_END (HID_LIB_START+9999) - -#define HID_APP_START (HID_START+20000) -#define HID_APP_END (HID_START+29999) - -#define HID_SW_START (HID_START+20000) -#define HID_SW_END (HID_START+24999) - -#define HID_SC_START (HID_START+25000) -#define HID_SC_END (HID_START+26999) - -#define HID_SD_START (HID_START+27000) -#define HID_SD_END (HID_START+27999) - -#define HID_Sa_START (HID_START+28000) -#define HID_Sa_END (HID_START+28999) - -#define HID_Sb_START (HID_START+29000) -#define HID_Sb_END (HID_START+29999) - -#define HID_OBJ_START (HID_START+30000) -#define HID_OBJ_END (HID_START+32767) - -#define HID_SIM_START (HID_OBJ_START+ 0) -#define HID_SIM_END (HID_OBJ_START+ 239) - -#define HID_AVMEDIA_START (HID_OBJ_START+ 240) -#define HID_AVMEDIA_END (HID_OBJ_START+ 255) - -#define HID_SMA_START (HID_OBJ_START+ 256) -#define HID_SMA_END (HID_OBJ_START+ 511) - -#define HID_SCH_START (HID_OBJ_START+ 512) -#define HID_SCH_END (HID_OBJ_START+ 767) - -#define HID_BASICIDE_START (HID_OBJ_START+ 768) -#define HID_BASICIDE_END (HID_OBJ_START+1023) - -#define HID_SMA2_START (HID_OBJ_START+1024) -#define HID_SMA2_END (HID_OBJ_START+1280) - -#define HID_FILTER_START (HID_OBJ_START+1281) -#define HID_FILTER_END (HID_OBJ_START+1580) - -#define HID_LICENSING_START (HID_OBJ_START+1581) -#define HID_LICENSING_END (HID_OBJ_START+1680) - -#define HID_RPT_START (HID_OBJ_START+1681) -#define HID_RPT_END (HID_OBJ_START+2080) - -#define HID_FORMULA_START (HID_OBJ_START+2081) -#define HID_FORMULA_END (HID_OBJ_START+2280) - -#endif - diff --git a/svtools/inc/svtools/svtools.hrc b/svtools/inc/svtools/svtools.hrc index 245d31a2dd21..0be076d6333a 100644 --- a/svtools/inc/svtools/svtools.hrc +++ b/svtools/inc/svtools/svtools.hrc @@ -30,7 +30,7 @@ #ifndef _SVTOOLS_HRC #define _SVTOOLS_HRC "$Revision: 1.0" -#include +#include #define RID_SVTOOLS_BITMAP_START (RID_SVTOOLS_START + 0) #define RID_SVTOOLS_IMAGELIST_START (RID_SVTOOLS_START + 0) diff --git a/svtools/prj/d.lst b/svtools/prj/d.lst index 6b85194db6c1..0db11da707f3 100644 --- a/svtools/prj/d.lst +++ b/svtools/prj/d.lst @@ -117,7 +117,6 @@ mkdir: %_DEST%\inc%_EXT%\svtools ..\inc\svtools\cnclhint.hxx %_DEST%\inc%_EXT%\svtools\cnclhint.hxx ..\inc\svtools\inettype.hxx %_DEST%\inc%_EXT%\svtools\inettype.hxx ..\inc\svtools\brwhead.hxx %_DEST%\inc%_EXT%\svtools\brwhead.hxx -..\inc\svtools\solar.hrc %_DEST%\inc%_EXT%\svtools\solar.hrc ..\inc\scriptedtext.hxx %_DEST%\inc%_EXT%\svtools\scriptedtext.hxx ..\inc\svtools\stdctrl.hxx %_DEST%\inc%_EXT%\svtools\stdctrl.hxx ..\inc\svtools\stritem.hxx %_DEST%\inc%_EXT%\svtools\stritem.hxx diff --git a/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx b/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx index 1bc83575ec38..2502a8bcea01 100644 --- a/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx +++ b/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx @@ -37,7 +37,7 @@ #include "FilterConfigCache.hxx" #include #include -#include +#include #include #include "dlgexpor.hxx" #include "dlgejpg.hxx" diff --git a/svtools/source/filter.vcl/filter/filter.cxx b/svtools/source/filter.vcl/filter/filter.cxx index f87fabc7973d..7465a925627f 100644 --- a/svtools/source/filter.vcl/filter/filter.cxx +++ b/svtools/source/filter.vcl/filter/filter.cxx @@ -54,7 +54,7 @@ #include "jpeg.hxx" #include "xbmread.hxx" #include "xpmread.hxx" -#include +#include #include "strings.hrc" #include "sgffilt.hxx" #include "osl/module.hxx" diff --git a/svtools/source/plugapp/testtool.src b/svtools/source/plugapp/testtool.src index 599675a6c494..4333dedd4255 100644 --- a/svtools/source/plugapp/testtool.src +++ b/svtools/source/plugapp/testtool.src @@ -28,7 +28,7 @@ * ************************************************************************/ #include "testtool.hrc" -#include +#include #define Control_Control 5 diff --git a/svtools/source/uno/unoifac2.hrc b/svtools/source/uno/unoifac2.hrc index 4e8cf0303da5..64941b1c3013 100644 --- a/svtools/source/uno/unoifac2.hrc +++ b/svtools/source/uno/unoifac2.hrc @@ -33,7 +33,7 @@ #ifndef _SOLAR_HRC -#include +#include #endif //! Um den Überblick über alle benutzten HelpID's zu behalten sind diese diff --git a/svtools/workben/unodialog/udlg_global.hrc b/svtools/workben/unodialog/udlg_global.hrc index 71a67cd2b7e8..6fa2679e3386 100644 --- a/svtools/workben/unodialog/udlg_global.hrc +++ b/svtools/workben/unodialog/udlg_global.hrc @@ -31,7 +31,7 @@ #ifndef SVTOOLS_UDLG_GLOBAL_HRC #define SVTOOLS_UDLG_GLOBAL_HRC -#include +#include //===================================================================== //= bases -- cgit From 5ea9defaaa271df2fd8d42341ea04796c91f31af Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 15 Aug 2009 16:43:25 +0000 Subject: #i92516# move solar.hrc to vcl --- goodies/inc/goodies.hrc | 2 +- goodies/inc/pch/precompiled_goodies.hxx | 2 +- goodies/source/filter.vcl/egif/egif.cxx | 2 +- goodies/source/filter.vcl/eos2met/eos2met.cxx | 2 +- goodies/source/filter.vcl/epbm/epbm.cxx | 2 +- goodies/source/filter.vcl/epgm/epgm.cxx | 2 +- goodies/source/filter.vcl/epict/epict.cxx | 2 +- goodies/source/filter.vcl/eppm/eppm.cxx | 2 +- goodies/source/filter.vcl/eps/eps.cxx | 2 +- goodies/source/filter.vcl/etiff/etiff.cxx | 2 +- goodies/source/filter.vcl/ipcd/ipcd.cxx | 2 +- goodies/source/inv/invader.cxx | 2 +- goodies/source/unographic/provider.cxx | 2 +- goodies/source/unographic/transformer.cxx | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/goodies/inc/goodies.hrc b/goodies/inc/goodies.hrc index 18584985a603..0cad63e4efdd 100644 --- a/goodies/inc/goodies.hrc +++ b/goodies/inc/goodies.hrc @@ -31,7 +31,7 @@ #define _GOODIES_HRC #ifndef _SOLAR_HRC -#include +#include #endif // Dialoge --------------------------------------------------------------- diff --git a/goodies/inc/pch/precompiled_goodies.hxx b/goodies/inc/pch/precompiled_goodies.hxx index b0d1ba09410b..8df95abff7ce 100644 --- a/goodies/inc/pch/precompiled_goodies.hxx +++ b/goodies/inc/pch/precompiled_goodies.hxx @@ -100,7 +100,7 @@ #include "svtools/fltcall.hxx" #include "svtools/itemprop.hxx" #include "svtools/lstner.hxx" -#include "svtools/solar.hrc" +#include "vcl/solar.hrc" #include "svtools/stdctrl.hxx" #include "svtools/svarray.hxx" diff --git a/goodies/source/filter.vcl/egif/egif.cxx b/goodies/source/filter.vcl/egif/egif.cxx index e1547c7339d0..6cef33de0187 100644 --- a/goodies/source/filter.vcl/egif/egif.cxx +++ b/goodies/source/filter.vcl/egif/egif.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "giflzwc.hxx" diff --git a/goodies/source/filter.vcl/eos2met/eos2met.cxx b/goodies/source/filter.vcl/eos2met/eos2met.cxx index b176d186a217..eabf720f7838 100644 --- a/goodies/source/filter.vcl/eos2met/eos2met.cxx +++ b/goodies/source/filter.vcl/eos2met/eos2met.cxx @@ -47,7 +47,7 @@ #include #include #include -#include +#include #include "strings.hrc" #include "dlgeos2.hxx" diff --git a/goodies/source/filter.vcl/epbm/epbm.cxx b/goodies/source/filter.vcl/epbm/epbm.cxx index 92aeb501e141..2913452df4a9 100644 --- a/goodies/source/filter.vcl/epbm/epbm.cxx +++ b/goodies/source/filter.vcl/epbm/epbm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/epgm/epgm.cxx b/goodies/source/filter.vcl/epgm/epgm.cxx index b6056339f11e..435a53da6b9f 100644 --- a/goodies/source/filter.vcl/epgm/epgm.cxx +++ b/goodies/source/filter.vcl/epgm/epgm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/epict/epict.cxx b/goodies/source/filter.vcl/epict/epict.cxx index 4df7abea01fc..3de76263538d 100644 --- a/goodies/source/filter.vcl/epict/epict.cxx +++ b/goodies/source/filter.vcl/epict/epict.cxx @@ -33,7 +33,7 @@ #include #include -#include +#include #include #include diff --git a/goodies/source/filter.vcl/eppm/eppm.cxx b/goodies/source/filter.vcl/eppm/eppm.cxx index 8cd71176e31b..5d682a215f6a 100644 --- a/goodies/source/filter.vcl/eppm/eppm.cxx +++ b/goodies/source/filter.vcl/eppm/eppm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/eps/eps.cxx b/goodies/source/filter.vcl/eps/eps.cxx index 8a163659050a..cda3da68aaa5 100644 --- a/goodies/source/filter.vcl/eps/eps.cxx +++ b/goodies/source/filter.vcl/eps/eps.cxx @@ -46,7 +46,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/goodies/source/filter.vcl/etiff/etiff.cxx b/goodies/source/filter.vcl/etiff/etiff.cxx index 12289cb8f0a9..c4bd6524627b 100644 --- a/goodies/source/filter.vcl/etiff/etiff.cxx +++ b/goodies/source/filter.vcl/etiff/etiff.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include diff --git a/goodies/source/filter.vcl/ipcd/ipcd.cxx b/goodies/source/filter.vcl/ipcd/ipcd.cxx index f70d1c8b84c5..b0d7cbc1eabb 100644 --- a/goodies/source/filter.vcl/ipcd/ipcd.cxx +++ b/goodies/source/filter.vcl/ipcd/ipcd.cxx @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include //============================ PCDReader ================================== diff --git a/goodies/source/inv/invader.cxx b/goodies/source/inv/invader.cxx index be15ff2e75d4..4e91536e577b 100644 --- a/goodies/source/inv/invader.cxx +++ b/goodies/source/inv/invader.cxx @@ -37,7 +37,7 @@ #include "invader.hrc" #include "strings.hrc" #include "score.hxx" -#include +#include #include #include #include diff --git a/goodies/source/unographic/provider.cxx b/goodies/source/unographic/provider.cxx index 2eb0aede9bdf..b332dd4233e2 100644 --- a/goodies/source/unographic/provider.cxx +++ b/goodies/source/unographic/provider.cxx @@ -46,7 +46,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/goodies/source/unographic/transformer.cxx b/goodies/source/unographic/transformer.cxx index 4422d161d7c4..ee4371172514 100644 --- a/goodies/source/unographic/transformer.cxx +++ b/goodies/source/unographic/transformer.cxx @@ -43,7 +43,7 @@ #include #include #include -#include +#include #include #include #include -- cgit From b1a1ddc401bb154812ab311339381747c48c531f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 17 Aug 2009 14:40:01 +0000 Subject: #i92516# fix several small issues (helpids, taborder, property names) --- vcl/source/window/printdlg.cxx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 38ddb66877d0..7d8dc893c1be 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -58,8 +58,8 @@ using namespace com::sun::star::uno; using namespace com::sun::star::beans; #define HELPID_PREFIX ".HelpId:vcl:PrintDialog" -#define SMHID2( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ":" b ) ) ) ) -#define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ) ) ) +#define SMHID2( a, b ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ":" b ) ), HID_PRINTDLG ) ) +#define SMHID1( a ) SetSmartHelpId( SmartId( String( RTL_CONSTASCII_USTRINGPARAM( HELPID_PREFIX ":" a ) ), HID_PRINTDLG ) ) PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const ResId& i_rId ) : Window( i_pParent, i_rId ) @@ -477,7 +477,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) maLocationTxt.SMHID2( "JobPage", "LocationText" ); maCommentLabel.SMHID2( "JobPage", "CommentLabel" ); maCommentTxt.SMHID2( "JobPage", "CommentText" ); - maSetupButton.SMHID2( "JobPage", "Setup" ); + maSetupButton.SMHID2( "JobPage", "Properties" ); maCopies.SMHID2( "JobPage", "CopiesLine" ); maCopySpacer.SMHID2( "JobPage", "CopySpacer" ); maCopyCount.SMHID2( "JobPage", "CopiesText" ); @@ -981,7 +981,7 @@ static void setSmartId( Window* i_pWindow, const char* i_pType, sal_Int32 i_nId aBuf.append( sal_Unicode( ':' ) ); aBuf.append( i_nId ); } - i_pWindow->SetSmartHelpId( SmartId( aBuf.makeStringAndClear() ) ); + i_pWindow->SetSmartHelpId( SmartId( aBuf.makeStringAndClear(), HID_PRINTDLG ) ); } static void setHelpText( Window* i_pWindow, const Sequence< rtl::OUString >& i_rHelpTexts, sal_Int32 i_nIndex ) @@ -1204,7 +1204,7 @@ void PrintDialog::setupOptionalUI() // EVIL else if( aCtrlType.equalsAscii( "Bool" ) && aGroupingHint.equalsAscii( "LayoutPage" ) && - aPropertyName.equalsAscii( "PrintBrochure" ) + aPropertyName.equalsAscii( "PrintProspect" ) ) { maNUpPage.maBrochureBtn.SetText( aText ); -- cgit From 6b0adfa6f596666120cc069a4b1a6d486a122852 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 17 Aug 2009 15:41:35 +0000 Subject: dispatch HID_PRINTDLG on help button --- vcl/source/window/printdlg.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 7d8dc893c1be..fef24e58ce5a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1838,7 +1838,7 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) if( pHelp ) { // FIXME: find out proper help URL and use here - pHelp->Start( 0, GetParent() ); + pHelp->Start( HID_PRINTDLG, GetParent() ); } } else if( pButton == &maForwardBtn ) -- cgit From f604695c795a5d608bb35d64885beb7e6b7e6296 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 17 Aug 2009 17:34:09 +0000 Subject: #i92516# handle pageoffset in vcl instead of application --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 10 +-- vcl/inc/vcl/print.hxx | 14 +++- vcl/source/gdi/print.cxx | 20 +++++ vcl/source/gdi/print3.cxx | 105 +++++++++++++++----------- vcl/source/window/printdlg.cxx | 5 +- 5 files changed, 104 insertions(+), 50 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index df08faf43686..52f6c8c5b575 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -307,17 +307,17 @@ class ControllerProperties if( i_nPage >= 0 && nPages > i_nPage ) { GDIMetaFile aMtf; - Size aPageSize( mpController->getFilteredPageFile( i_nPage, aMtf, false ) ); + PrinterController::PageSize aPageSize( mpController->getFilteredPageFile( i_nPage, aMtf, false ) ); VirtualDevice aDev; Size aLogicSize( aDev.PixelToLogic( aPixelSize, MapMode( MAP_100TH_MM ) ) ); - double fScaleX = double(aLogicSize.Width())/double(aPageSize.Width()); - double fScaleY = double(aLogicSize.Height())/double(aPageSize.Height()); + double fScaleX = double(aLogicSize.Width())/double(aPageSize.aSize.Width()); + double fScaleY = double(aLogicSize.Height())/double(aPageSize.aSize.Height()); double fScale = (fScaleX < fScaleY) ? fScaleX : fScaleY; aMtf.WindStart(); aMtf.Scale( fScale, fScale ); aMtf.WindStart(); - aLogicSize.Width() = long(double(aPageSize.Width()) * fScale); - aLogicSize.Height() = long(double(aPageSize.Height()) * fScale); + aLogicSize.Width() = long(double(aPageSize.aSize.Width()) * fScale); + aLogicSize.Height() = long(double(aPageSize.aSize.Height()) * fScale); aPixelSize = aDev.LogicToPixel( aLogicSize, MapMode( MAP_100TH_MM ) ); aDev.SetOutputSizePixel( aPixelSize ); aMtf.WindStart(); diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 0a290cb6adcc..fe6d5b7c6f00 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -430,6 +430,16 @@ public: } }; + struct PageSize + { + Size aSize; // in 100th mm + bool bFullPaper; // full paper, not only imageable area is printed + + PageSize( const Size& i_rSize = Size( 21000, 29700 ), + bool i_bFullPaper = false + ) : aSize( i_rSize ), bFullPaper( i_bFullPaper ) {} + }; + PrinterController(); virtual ~PrinterController(); @@ -490,8 +500,8 @@ public: // implementation details, not usable outside vcl SAL_DLLPRIVATE int getFilteredPageCount(); - SAL_DLLPRIVATE Size getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); - SAL_DLLPRIVATE Size getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache = false ); + SAL_DLLPRIVATE PageSize getPageFile( int i_inUnfilteredPage, GDIMetaFile& rMtf, bool i_bMayUseCache = false ); + SAL_DLLPRIVATE PageSize getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache = false ); SAL_DLLPRIVATE void printFilteredPage( int i_nPage ); SAL_DLLPRIVATE void setPrinter( const boost::shared_ptr& ); SAL_DLLPRIVATE void setOptionChangeHdl( const Link& ); diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index eee954076278..72e8380b28a0 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -510,6 +510,26 @@ void Printer::ImplUpdatePageData() mnOutWidth, mnOutHeight, maPageOffset.X(), maPageOffset.Y(), maPaperSize.Width(), maPaperSize.Height() ); + static const char* pDebugOffset = getenv( "SAL_DBG_PAGEOFFSET" ); + if( pDebugOffset ) + { + rtl::OString aLine( pDebugOffset ); + sal_Int32 nIndex = 0; + rtl::OString aToken( aLine.getToken( 0, ',', nIndex ) ); + sal_Int32 nLeft = aToken.toInt32(); + sal_Int32 nTop = nLeft; + if( nIndex > 0 ) + { + rtl::OString aToken( aLine.getToken( 0, ',', nIndex ) ); + nTop = aToken.toInt32(); + } + maPageOffset = LogicToPixel( Point( static_cast(nLeft), + static_cast(nTop) ), + MapMode( MAP_100TH_MM ) + ); + mnOutWidth = maPaperSize.Width() - 2*maPageOffset.X(); + mnOutWidth = maPaperSize.Width() - 2*maPageOffset.Y(); + } } // ----------------------------------------------------------------------- diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 375947c867ec..c134a0d21f8c 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -60,7 +60,13 @@ using namespace vcl; class ImplPageCache { - std::vector< GDIMetaFile > maPages; + struct CacheEntry + { + GDIMetaFile aPage; + PrinterController::PageSize aSize; + }; + + std::vector< CacheEntry > maPages; std::vector< sal_Int32 > maPageNumbers; std::vector< sal_Int32 > maCacheRanking; @@ -92,10 +98,11 @@ public: } // caution: does not ensure uniqueness - void insert( sal_Int32 i_nPageNo, const GDIMetaFile& i_rPage ) + void insert( sal_Int32 i_nPageNo, const GDIMetaFile& i_rPage, const PrinterController::PageSize& i_rSize ) { sal_Int32 nReplacePage = maCacheRanking.back(); - maPages[ nReplacePage ] = i_rPage; + maPages[ nReplacePage ].aPage = i_rPage; + maPages[ nReplacePage ].aSize = i_rSize; maPageNumbers[ nReplacePage ] = i_nPageNo; // cache insertion means in our case, the page was just queried // so update the ranking @@ -105,19 +112,19 @@ public: // caution: bad algorithm; should there ever be reason to increase the cache size beyond 6 // this needs to be urgently rewritten. However do NOT increase the cache size lightly, // whole pages can be rather memory intensive - const GDIMetaFile* get( sal_Int32 i_nPageNo ) + bool get( sal_Int32 i_nPageNo, GDIMetaFile& o_rPageFile, PrinterController::PageSize& o_rSize ) { - const GDIMetaFile* pRet = NULL; for( sal_Int32 i = 0; i < nCacheSize; ++i ) { if( maPageNumbers[i] == i_nPageNo ) { updateRanking( i ); - pRet = &maPages[i]; - break; + o_rPageFile = maPages[i].aPage; + o_rSize = maPages[i].aSize; + return true; } } - return pRet; + return false; } void invalidate() @@ -125,7 +132,7 @@ public: for( sal_Int32 i = 0; i < nCacheSize; ++i ) { maPageNumbers[i] = -1; - maPages[i].Clear(); + maPages[i].aPage.Clear(); maCacheRanking[i] = nCacheSize - i - 1; } } @@ -580,21 +587,28 @@ bool PrinterController::setupPrinter( Window* i_pParent ) return bRet; } -static Size modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) +static PrinterController::PageSize modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) { - Size aPageSize = pPrinter->GetPaperSize(); + PrinterController::PageSize aPageSize; + aPageSize.aSize = pPrinter->GetPaperSize(); for( sal_Int32 nProperty = 0, nPropertyCount = i_rProps.getLength(); nProperty < nPropertyCount; ++nProperty ) { if( i_rProps[ nProperty ].Name.equalsAscii( "PageSize" ) ) { awt::Size aSize; i_rProps[ nProperty].Value >>= aSize; - aPageSize.Width() = aSize.Width; - aPageSize.Height() = aSize.Height; + aPageSize.aSize.Width() = aSize.Width; + aPageSize.aSize.Height() = aSize.Height; Size aCurSize( pPrinter->GetPaperSize() ); - if( aPageSize != aCurSize ) - pPrinter->SetPaperSizeUser( aPageSize ); + if( aPageSize.aSize != aCurSize ) + pPrinter->SetPaperSizeUser( aPageSize.aSize ); + } + if( i_rProps[ nProperty ].Name.equalsAscii( "PageIncludesNonprintableArea" ) ) + { + sal_Bool bVal = sal_False; + i_rProps[ nProperty].Value >>= bVal; + aPageSize.bFullPaper = static_cast(bVal); } } return aPageSize; @@ -622,25 +636,24 @@ Sequence< beans::PropertyValue > PrinterController::getPageParametersProtected( return aResult; } -Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) +PrinterController::PageSize PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { // update progress if necessary if( mpImplData->mpProgress ) { // do nothing if printing is canceled if( mpImplData->mpProgress->isCanceled() ) - return Size(); + return PrinterController::PageSize(); mpImplData->mpProgress->tick(); Application::Reschedule( true ); } if( i_bMayUseCache ) { - const GDIMetaFile* pCached = mpImplData->maPageCache.get( i_nUnfilteredPage ); - if( pCached ) + PrinterController::PageSize aPageSize; + if( mpImplData->maPageCache.get( i_nUnfilteredPage, o_rMtf, aPageSize ) ) { - o_rMtf = *pCached; - return pCached->GetPrefSize(); + return aPageSize; } } else @@ -656,9 +669,9 @@ Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, mpImplData->mpPrinter->SetMapMode( aMapMode ); // modify job setup if necessary - Size aPageSize = modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); + PrinterController::PageSize aPageSize = modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); - o_rMtf.SetPrefSize( aPageSize ); + o_rMtf.SetPrefSize( aPageSize.aSize ); o_rMtf.SetPrefMapMode( aMapMode ); mpImplData->mpPrinter->EnableOutput( FALSE ); @@ -672,7 +685,7 @@ Size PrinterController::getPageFile( int i_nUnfilteredPage, GDIMetaFile& o_rMtf, mpImplData->mpPrinter->Pop(); if( i_bMayUseCache ) - mpImplData->maPageCache.insert( i_nUnfilteredPage, o_rMtf ); + mpImplData->maPageCache.insert( i_nUnfilteredPage, o_rMtf, aPageSize ); return aPageSize; } @@ -710,7 +723,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD o_rMtf.AddAction( new MetaPopAction() ); } -Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) +PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) { const MultiPageSetup& rMPS( mpImplData->maMultiPage ); int nSubPages = rMPS.nRows * rMPS.nColumns; @@ -729,19 +742,20 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o int nDocPages = getPageCountProtected(); i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; } - Size aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); - Size aPaperSize = mpImplData->getRealPaperSize( aPageSize ); - if( aPaperSize != aPageSize ) + PrinterController::PageSize aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); + Size aPaperSize = mpImplData->getRealPaperSize( aPageSize.aSize ); + if( aPaperSize != aPageSize.aSize ) { // user overridden page size, center Metafile o_rMtf.WindStart(); - long nDX = (aPaperSize.Width() - aPageSize.Width()) / 2; - long nDY = (aPaperSize.Height() - aPageSize.Height()) / 2; + long nDX = (aPaperSize.Width() - aPageSize.aSize.Width()) / 2; + long nDY = (aPaperSize.Height() - aPageSize.aSize.Height()) / 2; o_rMtf.Move( nDX, nDY ); o_rMtf.WindStart(); o_rMtf.SetPrefSize( aPaperSize ); + aPageSize.aSize = aPaperSize; } - return aPaperSize; + return aPageSize; } Size aPaperSize( mpImplData->getRealPaperSize( mpImplData->maMultiPage.aPaperSize ) ); @@ -775,8 +789,8 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o if( nPage >= 0 && nPage < nDocPages ) { GDIMetaFile aPageFile; - Size aPageSize = getPageFile( nPage, aPageFile, i_bMayUseCache ); - if( aPageSize.Width() && aPageSize.Height() ) + PrinterController::PageSize aPageSize = getPageFile( nPage, aPageFile, i_bMayUseCache ); + if( aPageSize.aSize.Width() && aPageSize.aSize.Height() ) { long nCellX = 0, nCellY = 0; switch( rMPS.nOrder ) @@ -791,23 +805,23 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o break; } // scale the metafile down to a sub page size - double fScaleX = double(aSubPageSize.Width())/double(aPageSize.Width()); - double fScaleY = double(aSubPageSize.Height())/double(aPageSize.Height()); + double fScaleX = double(aSubPageSize.Width())/double(aPageSize.aSize.Width()); + double fScaleY = double(aSubPageSize.Height())/double(aPageSize.aSize.Height()); double fScale = std::min( fScaleX, fScaleY ); aPageFile.Scale( fScale, fScale ); aPageFile.WindStart(); // move the subpage so it is centered in its "cell" - long nOffX = (aSubPageSize.Width() - long(double(aPageSize.Width()) * fScale)) / 2; - long nOffY = (aSubPageSize.Height() - long(double(aPageSize.Height()) * fScale)) / 2; + long nOffX = (aSubPageSize.Width() - long(double(aPageSize.aSize.Width()) * fScale)) / 2; + long nOffY = (aSubPageSize.Height() - long(double(aPageSize.aSize.Height()) * fScale)) / 2; long nX = rMPS.nLeftMargin + nOffX + nAdvX * nCellX; long nY = rMPS.nTopMargin + nOffY + nAdvY * nCellY; aPageFile.Move( nX, nY ); aPageFile.WindStart(); // calculate border rectangle Rectangle aSubPageRect( Point( nX, nY ), - Size( long(double(aPageSize.Width())*fScale), - long(double(aPageSize.Height())*fScale) ) ); + Size( long(double(aPageSize.aSize.Width())*fScale), + long(double(aPageSize.aSize.Height())*fScale) ) ); // append subpage to page appendSubPage( o_rMtf, aSubPageRect, aPageFile, rMPS.bDrawBorder ); @@ -819,7 +833,7 @@ Size PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o mpImplData->mpPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize ); - return aPaperSize; + return PrinterController::PageSize( aPaperSize ); } int PrinterController::getFilteredPageCount() @@ -836,7 +850,7 @@ void PrinterController::printFilteredPage( int i_nPage ) return; GDIMetaFile aPageFile; - Size aPageSize = getFilteredPageFile( i_nPage, aPageFile ); + PrinterController::PageSize aPageSize = getFilteredPageFile( i_nPage, aPageFile ); if( mpImplData->mpProgress ) { @@ -904,7 +918,14 @@ void PrinterController::printFilteredPage( int i_nPage ) // in N-Up printing set the correct page size mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); // aPageSize was filtered through mpImplData->getRealPaperSize already by getFilteredPageFile() - mpImplData->mpPrinter->SetPaperSizeUser( aPageSize ); + mpImplData->mpPrinter->SetPaperSizeUser( aPageSize.aSize ); + // if full paper are is meant, move the output to accomodate for pageoffset + if( aPageSize.bFullPaper ) + { + Point aPageOffset( mpImplData->mpPrinter->GetPageOffset() ); + aCleanedFile.WindStart(); + aCleanedFile.Move( -aPageOffset.X(), -aPageOffset.Y() ); + } // actually print the page mpImplData->mpPrinter->ImplStartPage(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index fef24e58ce5a..1128a1f52e10 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1677,7 +1677,10 @@ Size PrintDialog::getJobPageSize() maFirstPageSize = maNupPortraitSize; GDIMetaFile aMtf; if( maPController->getPageCountProtected() > 0 ) - maFirstPageSize = maPController->getPageFile( 0, aMtf, true ); + { + PrinterController::PageSize aPageSize = maPController->getPageFile( 0, aMtf, true ); + maFirstPageSize = aPageSize.aSize; + } } return maFirstPageSize; } -- cgit From 7b510ce2c097f6b9d57d48afb48f0d1e92b4196b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 18 Aug 2009 15:58:46 +0000 Subject: #i92516# getNativeControlRegion for edits and spinboxes --- vcl/unx/gtk/gdi/salnativewidgets-gtk.cxx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/vcl/unx/gtk/gdi/salnativewidgets-gtk.cxx b/vcl/unx/gtk/gdi/salnativewidgets-gtk.cxx index 9dbb218403d0..a49ef063af57 100644 --- a/vcl/unx/gtk/gdi/salnativewidgets-gtk.cxx +++ b/vcl/unx/gtk/gdi/salnativewidgets-gtk.cxx @@ -1087,6 +1087,19 @@ BOOL GtkSalGraphics::getNativeControlRegion( ControlType nType, rNativeContentRegion = Region( aIndicatorRect ); returnVal = TRUE; } + if( (nType == CTRL_EDITBOX || nType == CTRL_SPINBOX) && nPart == PART_ENTIRE_CONTROL ) + { + NWEnsureGTKEditBox( m_nScreen ); + GtkWidget* widget = gWidgetData[m_nScreen].gEditBoxWidget; + GtkRequisition aReq; + gtk_widget_size_request( widget, &aReq ); + Rectangle aEditRect = rControlRegion.GetBoundRect(); + aEditRect = Rectangle( aEditRect.TopLeft(), + Size( aEditRect.GetWidth(), aReq.height+1 ) ); + rNativeBoundingRegion = Region( aEditRect ); + rNativeContentRegion = rNativeBoundingRegion; + returnVal = TRUE; + } return( returnVal ); } -- cgit From 8802e7ab5f59b4e4a8ba6dced48660710d9ea9ab Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 18 Aug 2009 16:07:05 +0000 Subject: #i92516# align radio buttons and dependencies properly --- vcl/source/window/printdlg.cxx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1128a1f52e10..bf1d38678821 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1309,9 +1309,11 @@ void PrintDialog::setupOptionalUI() pVal->Value >>= nSelectVal; for( sal_Int32 m = 0; m < aChoices.getLength(); m++ ) { - vcl::RowOrColumn* pDependencyRow = new vcl::RowOrColumn( pCurColumn, false ); - pRadioColumn->addChild( pDependencyRow ); - aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pDependencyRow ) ); + boost::shared_ptr pLabel( new vcl::LabeledElement( pRadioColumn, 1 ) ); + pRadioColumn->addChild( pLabel ); + boost::shared_ptr pDependencyRow( new vcl::RowOrColumn( pLabel.get(), false ) ); + pLabel->setElement( pDependencyRow ); + aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, pDependencyRow.get() ) ); RadioButton* pBtn = new RadioButton( pCurParent, m == 0 ? WB_GROUP : 0 ); maControls.push_front( pBtn ); @@ -1329,7 +1331,7 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pBtn, aHelpTexts, nCurHelpText++ ); // add the radio button to the column - pDependencyRow->addWindow( pBtn ); + pLabel->setLabel( pBtn ); } } else if( ( aCtrlType.equalsAscii( "List" ) || -- cgit From a45b7400bb5d3d0ae0521789c67a7e2700734973 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 19 Aug 2009 08:31:45 +0000 Subject: fix a warning --- vcl/source/gdi/print.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index 72e8380b28a0..f7db0b56f4ca 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -520,7 +520,7 @@ void Printer::ImplUpdatePageData() sal_Int32 nTop = nLeft; if( nIndex > 0 ) { - rtl::OString aToken( aLine.getToken( 0, ',', nIndex ) ); + aToken = aLine.getToken( 0, ',', nIndex ); nTop = aToken.toInt32(); } maPageOffset = LogicToPixel( Point( static_cast(nLeft), -- cgit From 0f190044c038ccd3cd0dc12f6c5a81a9f2b9216e Mon Sep 17 00:00:00 2001 From: Thomas Lange Date: Wed, 19 Aug 2009 09:12:32 +0000 Subject: #i92516# new print UI --- vcl/source/gdi/print3.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index c134a0d21f8c..479095d94265 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -581,6 +581,7 @@ bool PrinterController::setupPrinter( Window* i_pParent ) if( aNewPaperSize != aPaperSize ) { mpImplData->maFixedPageSize = aNewPaperSize; + mpImplData->maPageCache.invalidate(); } } } -- cgit From b3b4d3b4b58c7346bf7bc22d415960c7eaab1d6b Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Thu, 20 Aug 2009 04:25:53 +0000 Subject: A little hack to get border floating window to be recognized by accessibility framework. I'll come back to clean this up later. --- vcl/unx/gtk/a11y/atkwindow.cxx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/vcl/unx/gtk/a11y/atkwindow.cxx b/vcl/unx/gtk/a11y/atkwindow.cxx index 5961556e85d7..4d1fa6c016e6 100644 --- a/vcl/unx/gtk/a11y/atkwindow.cxx +++ b/vcl/unx/gtk/a11y/atkwindow.cxx @@ -108,6 +108,13 @@ init_from_window( AtkObject *accessible, Window *pWindow ) pChild->SetAccessibleRole( AccessibleRole::LABEL ); accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); } + else if (WINDOW_FLOATINGWINDOW == pChild->GetType()) + { + // TODO: This is a hack. Figure out a way to do this a little cleaner. + role = ATK_ROLE_WINDOW; + pChild->SetAccessibleRole( AccessibleRole::WINDOW ); + accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); + } } break; } -- cgit From fd5fd47540a78b8cbe5fc1d3a541642aee09ba6f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 20 Aug 2009 15:09:25 +0000 Subject: #i92516# clean up graphics state at end of page --- vcl/aqua/inc/salgdi.h | 1 + vcl/aqua/source/gdi/salgdiutils.cxx | 6 ++++++ vcl/aqua/source/gdi/salprn.cxx | 5 +++-- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/vcl/aqua/inc/salgdi.h b/vcl/aqua/inc/salgdi.h index 11abd6086ce7..fa8f45b27a68 100644 --- a/vcl/aqua/inc/salgdi.h +++ b/vcl/aqua/inc/salgdi.h @@ -175,6 +175,7 @@ public: void RefreshRect(float lX, float lY, float lWidth, float lHeight); void SetState(); + void UnsetState(); virtual BOOL unionClipRegion( long nX, long nY, long nWidth, long nHeight ); virtual bool unionClipRegion( const ::basegfx::B2DPolyPolygon& ); diff --git a/vcl/aqua/source/gdi/salgdiutils.cxx b/vcl/aqua/source/gdi/salgdiutils.cxx index 066268791b11..338ab9b8cae0 100755 --- a/vcl/aqua/source/gdi/salgdiutils.cxx +++ b/vcl/aqua/source/gdi/salgdiutils.cxx @@ -126,6 +126,12 @@ void AquaSalGraphics::SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContex // ---------------------------------------------------------------------- +void AquaSalGraphics::UnsetState() +{ + if( mrContext ) + CGContextRestoreGState( mrContext ); +} + void AquaSalGraphics::SetState() { CGContextRestoreGState( mrContext ); diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index a9a58799f4db..cdc11162557e 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -138,7 +138,7 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const dY -= aPaperSize.height - aImageRect.size.height - aImageRect.origin.y; CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetX, dY - mnStartPageOffsetY ); // scale to be top/down and reflect our "virtual" DPI - CGContextScaleCTM( i_rContext, 0.1, -0.1 ); + CGContextScaleCTM( i_rContext, 72.0/double(nDPIX), -(72.0/double(nDPIY)) ); } else { @@ -152,7 +152,7 @@ void AquaSalInfoPrinter::SetupPrinterGraphics( CGContextRef i_rContext ) const dY = -aPaperSize.width; CGContextTranslateCTM( i_rContext, dX + mnStartPageOffsetY, dY - mnStartPageOffsetX ); // scale to be top/down and reflect our "virtual" DPI - CGContextScaleCTM( i_rContext, -0.1, 0.1 ); + CGContextScaleCTM( i_rContext, -(72.0/double(nDPIY)), (72.0/double(nDPIX)) ); } mpGraphics->SetPrinterGraphics( i_rContext, nDPIX, nDPIY, 1.0 ); } @@ -705,6 +705,7 @@ SalGraphics* AquaSalInfoPrinter::StartPage( ImplJobSetup* i_pSetupData, BOOL i_b BOOL AquaSalInfoPrinter::EndPage() { + mpGraphics->UnsetState(); return TRUE; } -- cgit From 088db7968bc05f8929da3767d04ee66aa59309da Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Thu, 20 Aug 2009 19:15:44 +0000 Subject: Some code fragment for debugging accessible state set changes. --- vcl/unx/gtk/a11y/atkwrapper.cxx | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/vcl/unx/gtk/a11y/atkwrapper.cxx b/vcl/unx/gtk/a11y/atkwrapper.cxx index 927b8548a77a..27c10f8377b1 100644 --- a/vcl/unx/gtk/a11y/atkwrapper.cxx +++ b/vcl/unx/gtk/a11y/atkwrapper.cxx @@ -514,6 +514,60 @@ wrapper_ref_relation_set( AtkObject *atk_obj ) /*****************************************************************************/ +#if 0 +struct { + sal_Int16 value; + const sal_Char* name; +} aStateTypeTable[] = { + { accessibility::AccessibleStateType::INVALID, "INVALID" }, + { accessibility::AccessibleStateType::ACTIVE, "ACTIVE" }, + { accessibility::AccessibleStateType::ARMED, "ARMED" }, + { accessibility::AccessibleStateType::BUSY, "BUSY" }, + { accessibility::AccessibleStateType::CHECKED, "CHECKED" }, + { accessibility::AccessibleStateType::DEFUNC, "DEFUNC" }, + { accessibility::AccessibleStateType::EDITABLE, "EDITABLE" }, + { accessibility::AccessibleStateType::ENABLED, "ENABLED" }, + { accessibility::AccessibleStateType::EXPANDABLE, "EXPANDABLE" }, + { accessibility::AccessibleStateType::EXPANDED, "EXPANDED" }, + { accessibility::AccessibleStateType::FOCUSABLE, "FOCUSABLE" }, + { accessibility::AccessibleStateType::FOCUSED, "FOCUSED" }, + { accessibility::AccessibleStateType::HORIZONTAL, "HORIZONTAL" }, + { accessibility::AccessibleStateType::ICONIFIED, "ICONIFIED" }, + { accessibility::AccessibleStateType::INDETERMINATE, "INDETERMINATE" }, + { accessibility::AccessibleStateType::MANAGES_DESCENDANTS, "MANAGES_DESCENDANTS" }, + { accessibility::AccessibleStateType::MODAL, "MODAL" }, + { accessibility::AccessibleStateType::MULTI_LINE, "MULTI_LINE" }, + { accessibility::AccessibleStateType::MULTI_SELECTABLE, "MULTI_SELECTABLE" }, + { accessibility::AccessibleStateType::OPAQUE, "OPAQUE" }, + { accessibility::AccessibleStateType::PRESSED, "PRESSED" }, + { accessibility::AccessibleStateType::RESIZABLE, "RESIZABLE" }, + { accessibility::AccessibleStateType::SELECTABLE, "SELECTABLE" }, + { accessibility::AccessibleStateType::SELECTED, "SELECTED" }, + { accessibility::AccessibleStateType::SENSITIVE, "SENSITIVE" }, + { accessibility::AccessibleStateType::SHOWING, "SHOWING" }, + { accessibility::AccessibleStateType::SINGLE_LINE, "SINGLE_LINE" }, + { accessibility::AccessibleStateType::STALE, "STALE" }, + { accessibility::AccessibleStateType::TRANSIENT, "TRANSIENT" }, + { accessibility::AccessibleStateType::VERTICAL, "VERTICAL" }, + { accessibility::AccessibleStateType::VISIBLE, "VISIBLE" } +}; + +static void printStates(const uno::Sequence& rStates) +{ + sal_Int32 n = rStates.getLength(); + size_t nTypes = sizeof(aStateTypeTable)/sizeof(aStateTypeTable[0]); + for (sal_Int32 i = 0; i < n; ++i) + { + for (size_t j = 0; j < nTypes; ++j) + { + if (aStateTypeTable[j].value == rStates[i]) + printf("%s ", aStateTypeTable[j].name); + } + } + printf("\n"); +} +#endif + static AtkStateSet * wrapper_ref_state_set( AtkObject *atk_obj ) { -- cgit From ca67662bc28f7a63906e59d8e7c6d6850883eef4 Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Thu, 20 Aug 2009 19:17:56 +0000 Subject: Add a new data member to FloatingWindow, and use it to see if the window instance is used as a pop-up menu. If yes, and it it's a top-level menu, assign an appropriate accessible role. --- vcl/inc/vcl/floatwin.hxx | 3 +++ vcl/source/window/floatwin.cxx | 14 +++++++++++++- vcl/unx/gtk/a11y/atkwindow.cxx | 14 +++++++++----- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/vcl/inc/vcl/floatwin.hxx b/vcl/inc/vcl/floatwin.hxx index 8dcba41e2a8e..d46fc42f2263 100644 --- a/vcl/inc/vcl/floatwin.hxx +++ b/vcl/inc/vcl/floatwin.hxx @@ -157,6 +157,9 @@ public: const Link& GetPopupModeEndHdl() const { return maPopupModeEndHdl; } BOOL GrabsFocus() const { return mbGrabFocus; } + + sal_uInt16 GetMenuStackLevel() const; + void SetMenuStackLevel( sal_uInt16 nLevel ); }; #endif // _SV_FLOATWIN_HXX diff --git a/vcl/source/window/floatwin.cxx b/vcl/source/window/floatwin.cxx index 7bcb90bbb8fc..45084a763ddd 100644 --- a/vcl/source/window/floatwin.cxx +++ b/vcl/source/window/floatwin.cxx @@ -48,6 +48,7 @@ #include #include +#include // ======================================================================= @@ -59,9 +60,11 @@ public: ToolBox* mpBox; Rectangle maItemEdgeClipRect; // used to clip the common edge between a toolbar item and the border of this window + sal_uInt16 mnMenuStackLevel; // in case it is used as a menu popup, store its stack level. 0 = top-level menu. }; -FloatingWindow::ImplData::ImplData() +FloatingWindow::ImplData::ImplData() : + mnMenuStackLevel( ::std::numeric_limits::max() ) { mpBox = NULL; } @@ -873,3 +876,12 @@ void FloatingWindow::RemovePopupModeWindow( Window* pWindow ) mpFirstPopupModeWin = NULL; } +sal_uInt16 FloatingWindow::GetMenuStackLevel() const +{ + return mpImplData->mnMenuStackLevel; +} + +void FloatingWindow::SetMenuStackLevel( sal_uInt16 nLevel ) +{ + mpImplData->mnMenuStackLevel = nLevel; +} diff --git a/vcl/unx/gtk/a11y/atkwindow.cxx b/vcl/unx/gtk/a11y/atkwindow.cxx index 4d1fa6c016e6..4a64a4959977 100644 --- a/vcl/unx/gtk/a11y/atkwindow.cxx +++ b/vcl/unx/gtk/a11y/atkwindow.cxx @@ -33,6 +33,7 @@ #include #include +#include "vcl/floatwin.hxx" #include "atkwindow.hxx" #include "atkwrapper.hxx" @@ -108,12 +109,15 @@ init_from_window( AtkObject *accessible, Window *pWindow ) pChild->SetAccessibleRole( AccessibleRole::LABEL ); accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); } - else if (WINDOW_FLOATINGWINDOW == pChild->GetType()) + else if ( pWindow->GetType() == WINDOW_BORDERWINDOW && pChild->GetType() == WINDOW_FLOATINGWINDOW ) { - // TODO: This is a hack. Figure out a way to do this a little cleaner. - role = ATK_ROLE_WINDOW; - pChild->SetAccessibleRole( AccessibleRole::WINDOW ); - accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); + sal_uInt16 nStackLevel = static_cast(pChild)->GetMenuStackLevel(); + if (nStackLevel == 0) + { + role = ATK_ROLE_POPUP_MENU; + pChild->SetAccessibleRole( AccessibleRole::POPUP_MENU ); + accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); + } } } break; -- cgit From 87ca2cf990cf2eec07fc11914d63c63668b35d23 Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Thu, 20 Aug 2009 19:55:14 +0000 Subject: Check if the FloatingWindow instance is used as a popup menu, and if yes, instantiate the accessible object from it, instead of its parent border window instance. --- vcl/inc/vcl/floatwin.hxx | 1 + vcl/source/window/floatwin.cxx | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/vcl/inc/vcl/floatwin.hxx b/vcl/inc/vcl/floatwin.hxx index d46fc42f2263..351c31df1c1b 100644 --- a/vcl/inc/vcl/floatwin.hxx +++ b/vcl/inc/vcl/floatwin.hxx @@ -160,6 +160,7 @@ public: sal_uInt16 GetMenuStackLevel() const; void SetMenuStackLevel( sal_uInt16 nLevel ); + bool IsPopupMenu() const; }; #endif // _SV_FLOATWIN_HXX diff --git a/vcl/source/window/floatwin.cxx b/vcl/source/window/floatwin.cxx index 45084a763ddd..b29b74e63f78 100644 --- a/vcl/source/window/floatwin.cxx +++ b/vcl/source/window/floatwin.cxx @@ -885,3 +885,8 @@ void FloatingWindow::SetMenuStackLevel( sal_uInt16 nLevel ) { mpImplData->mnMenuStackLevel = nLevel; } + +bool FloatingWindow::IsPopupMenu() const +{ + return mpImplData->mnMenuStackLevel != ::std::numeric_limits::max(); +} -- cgit From e0b99ef4ddf793db58e34378c748441ee982447f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Fri, 21 Aug 2009 15:30:14 +0000 Subject: resolve conflicts --- vcl/aqua/source/gdi/salprn.cxx | 10 ++++++--- vcl/inc/vcl/gdimtf.hxx | 8 ++++++++ vcl/source/control/lstbox.cxx | 46 +++++++++++++++++++++++++----------------- 3 files changed, 43 insertions(+), 21 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index cdc11162557e..799a620345d7 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -336,11 +336,15 @@ BOOL AquaSalInfoPrinter::SetData( ULONG i_nFlags, ImplJobSetup* io_pSetupData ) if( (i_nFlags & SAL_JOBSET_PAPERSIZE) != 0) { // set paper format - long width = 0, height = 0; + long width = 21000, height = 29700; if( io_pSetupData->mePaperFormat == PAPER_USER ) { - width = io_pSetupData->mnPaperWidth; - height = io_pSetupData->mnPaperHeight; + // #i101108# sanity check + if( io_pSetupData->mnPaperWidth && io_pSetupData->mnPaperHeight ) + { + width = io_pSetupData->mnPaperWidth; + height = io_pSetupData->mnPaperHeight; + } } else { diff --git a/vcl/inc/vcl/gdimtf.hxx b/vcl/inc/vcl/gdimtf.hxx index 48b39d290872..e4acd55439cc 100644 --- a/vcl/inc/vcl/gdimtf.hxx +++ b/vcl/inc/vcl/gdimtf.hxx @@ -165,6 +165,14 @@ public: void Scale( const Fraction& rScaleX, const Fraction& rScaleY ); void Rotate( long nAngle10 ); void Clip( const Rectangle& ); + /* get the bound rect of the contained actions + * caveats: + * - clip actions will limit the contained actions, + * but the current clipregion of the passed OutputDevice will not + * - coordinates of actions will be transformed to preferred mapmode + * - the returned rectangle is relative to the preferred mapmode of the metafile + */ + Rectangle GetBoundRect( OutputDevice& i_rReference ); void Adjust( short nLuminancePercent = 0, short nContrastPercent = 0, short nChannelRPercent = 0, short nChannelGPercent = 0, diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 7c9842c278d1..55a5e8bfd282 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -31,21 +31,21 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#ifndef _SV_RC_H -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "tools/rc.h" + +#include "vcl/svdata.hxx" +#include "vcl/decoview.hxx" +#include "vcl/event.hxx" +#include "vcl/scrbar.hxx" +#include "vcl/button.hxx" +#include "vcl/edit.hxx" +#include "vcl/subedit.hxx" +#include "vcl/ilstbox.hxx" +#include "vcl/lstbox.hxx" +#include "vcl/combobox.hxx" +#include "vcl/controllayout.hxx" + +#include "tools/debug.hxx" @@ -128,9 +128,7 @@ void ListBox::ImplInit( Window* pParent, WinBits nStyle ) GetBorder( nLeft, nTop, nRight, nBottom ); mnDDHeight = (USHORT)(GetTextHeight() + nTop + nBottom + 4); - // FIXME: this is currently only on mac/aqua - if( ImplGetSVData()->maNWFData.mbNoFocusRects && - IsNativeWidgetEnabled() && + if( IsNativeWidgetEnabled() && IsNativeControlSupported( CTRL_LISTBOX, PART_ENTIRE_CONTROL ) ) { ImplControlValue aControlValue; @@ -651,6 +649,7 @@ void ListBox::Resize() long nTop = 0; long nBottom = aOutSz.Height(); + // note: in case of no border, pBorder will actually be this Window *pBorder = GetWindow( WINDOW_BORDER ); ImplControlValue aControlValue; Point aPoint; @@ -679,6 +678,17 @@ void ListBox::Resize() // use the themes drop down size Rectangle aContentRect = aContent.GetBoundRect(); + if( ! (GetStyle() & WB_BORDER) && ImplGetSVData()->maNWFData.mbNoFocusRects ) + { + // no border but focus ring behavior -> we have a problem; the + // native rect relies on the border to draw the focus + // let's do the best we can and center vertically, so it doesn't look + // completely wrong. + Size aSz( GetOutputSizePixel() ); + long nDiff = aContentRect.Top() - (aSz.Height() - aContentRect.GetHeight())/2; + aContentRect.Top() -= nDiff; + aContentRect.Bottom() -= nDiff; + } mpImplWin->SetPosSizePixel( aContentRect.TopLeft(), aContentRect.GetSize() ); } else -- cgit From 4569c69eba08f7cb102d05d72e5cf23bed0eb68b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 24 Aug 2009 15:31:08 +0000 Subject: #i92516# protect against setting the clip region between printed pages --- vcl/aqua/inc/salgdi.h | 2 ++ vcl/aqua/source/gdi/salgdi.cxx | 12 ++++++++---- vcl/aqua/source/gdi/salgdiutils.cxx | 29 ++++++++++++++++++++++++++--- vcl/aqua/source/gdi/salprn.cxx | 2 +- 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/vcl/aqua/inc/salgdi.h b/vcl/aqua/inc/salgdi.h index fa8f45b27a68..c4cca1982215 100644 --- a/vcl/aqua/inc/salgdi.h +++ b/vcl/aqua/inc/salgdi.h @@ -176,6 +176,8 @@ public: void SetState(); void UnsetState(); + // InvalidateContext does an UnsetState and sets mrContext to 0 + void InvalidateContext(); virtual BOOL unionClipRegion( long nX, long nY, long nWidth, long nHeight ); virtual bool unionClipRegion( const ::basegfx::B2DPolyPolygon& ); diff --git a/vcl/aqua/source/gdi/salgdi.cxx b/vcl/aqua/source/gdi/salgdi.cxx index f8410a47dfd6..223aeff0d02f 100644 --- a/vcl/aqua/source/gdi/salgdi.cxx +++ b/vcl/aqua/source/gdi/salgdi.cxx @@ -597,7 +597,8 @@ void AquaSalGraphics::EndSetClipRegion() void AquaSalGraphics::SetLineColor() { maLineColor.SetAlpha( 0.0 ); // transparent - CGContextSetStrokeColor( mrContext, maLineColor.AsArray() ); + if( CheckContext() ) + CGContextSetStrokeColor( mrContext, maLineColor.AsArray() ); } // ----------------------------------------------------------------------- @@ -605,7 +606,8 @@ void AquaSalGraphics::SetLineColor() void AquaSalGraphics::SetLineColor( SalColor nSalColor ) { maLineColor = RGBAColor( nSalColor ); - CGContextSetStrokeColor( mrContext, maLineColor.AsArray() ); + if( CheckContext() ) + CGContextSetStrokeColor( mrContext, maLineColor.AsArray() ); } // ----------------------------------------------------------------------- @@ -613,7 +615,8 @@ void AquaSalGraphics::SetLineColor( SalColor nSalColor ) void AquaSalGraphics::SetFillColor() { maFillColor.SetAlpha( 0.0 ); // transparent - CGContextSetFillColor( mrContext, maFillColor.AsArray() ); + if( CheckContext() ) + CGContextSetFillColor( mrContext, maFillColor.AsArray() ); } // ----------------------------------------------------------------------- @@ -621,7 +624,8 @@ void AquaSalGraphics::SetFillColor() void AquaSalGraphics::SetFillColor( SalColor nSalColor ) { maFillColor = RGBAColor( nSalColor ); - CGContextSetFillColor( mrContext, maFillColor.AsArray() ); + if( CheckContext() ) + CGContextSetFillColor( mrContext, maFillColor.AsArray() ); } // ----------------------------------------------------------------------- diff --git a/vcl/aqua/source/gdi/salgdiutils.cxx b/vcl/aqua/source/gdi/salgdiutils.cxx index b7420cb8f53a..6df50f79e9d0 100755 --- a/vcl/aqua/source/gdi/salgdiutils.cxx +++ b/vcl/aqua/source/gdi/salgdiutils.cxx @@ -68,6 +68,13 @@ void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, lon mnRealDPIX = nDPIX; mnRealDPIY = nDPIY; + // a previously set clip path is now invalid + if( mxClipPath ) + { + CGPathRelease( mxClipPath ); + mxClipPath = NULL; + } + if( mrContext ) { CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace ); @@ -126,10 +133,26 @@ void AquaSalGraphics::SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContex // ---------------------------------------------------------------------- +void AquaSalGraphics::InvalidateContext() +{ + UnsetState(); + mrContext = 0; +} + +// ---------------------------------------------------------------------- + void AquaSalGraphics::UnsetState() { if( mrContext ) + { CGContextRestoreGState( mrContext ); + mrContext = 0; + } + if( mxClipPath ) + { + CGPathRelease( mxClipPath ); + mxClipPath = NULL; + } } void AquaSalGraphics::SetState() @@ -140,9 +163,9 @@ void AquaSalGraphics::SetState() // setup clipping if( mxClipPath ) { - CGContextBeginPath( mrContext ); // discard any existing path + CGContextBeginPath( mrContext ); // discard any existing path CGContextAddPath( mrContext, mxClipPath ); // set the current path to the clipping path - CGContextClip( mrContext ); // use it for clipping + CGContextClip( mrContext ); // use it for clipping } // set RGB colorspace and line and fill colors @@ -211,7 +234,7 @@ bool AquaSalGraphics::CheckContext() CGContextRelease( rReleaseContext ); } - DBG_ASSERT( mrContext, "<<>> AquaSalGraphics::CheckContext() FAILED!!!!\n" ); + DBG_ASSERT( mrContext || mbPrinter, "<<>> AquaSalGraphics::CheckContext() FAILED!!!!\n" ); return (mrContext != NULL); } diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 799a620345d7..079629216df6 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -709,7 +709,7 @@ SalGraphics* AquaSalInfoPrinter::StartPage( ImplJobSetup* i_pSetupData, BOOL i_b BOOL AquaSalInfoPrinter::EndPage() { - mpGraphics->UnsetState(); + mpGraphics->InvalidateContext(); return TRUE; } -- cgit From 5ab7598b54dc41208c5a1d1655daece59c8f6752 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 24 Aug 2009 17:27:29 +0000 Subject: #i92516# HELP_DEBUG for non static controls --- vcl/inc/vcl/window.h | 3 ++- vcl/source/window/printdlg.cxx | 2 ++ vcl/source/window/window.cxx | 21 +++++++++++++++++++++ vcl/source/window/window2.cxx | 1 + 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/vcl/inc/vcl/window.h b/vcl/inc/vcl/window.h index d745f3dcf081..563849873e3b 100644 --- a/vcl/inc/vcl/window.h +++ b/vcl/inc/vcl/window.h @@ -358,7 +358,8 @@ public: mbToolbarFloatingWindow:1, mbCallHandlersDuringInputDisabled:1, mbDisableAccessibleLabelForRelation:1, - mbDisableAccessibleLabeledByRelation:1; + mbDisableAccessibleLabeledByRelation:1, + mbHelpTextDynamic:1; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > mxDNDListenerContainer; }; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index bf1d38678821..4f25a9f296a8 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -471,6 +471,7 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) SMHID1( "JobPage" ); maPrinterFL.SMHID2( "JobPage", "Printer" ); maPrinters.SMHID2( "JobPage", "PrinterList" ); + maDetailsBtn.SMHID2( "JobPage", "DetailsBtn" ); maStatusLabel.SMHID2( "JobPage", "StatusLabel" ); maStatusTxt.SMHID2( "JobPage", "StatusText" ); maLocationLabel.SMHID2( "JobPage", "LocationLabel" ); @@ -837,6 +838,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrmbCallHandlersDuringInputDisabled = FALSE; // TRUE: call event handlers even if input is disabled mpWindowImpl->mbDisableAccessibleLabelForRelation = FALSE; // TRUE: do not set LabelFor relation on accessible objects mpWindowImpl->mbDisableAccessibleLabeledByRelation = FALSE; // TRUE: do not set LabeledBy relation on accessible objects + mpWindowImpl->mbHelpTextDynamic = FALSE; // TRUE: append help id in HELP_DEBUG case mbEnableRTL = Application::GetSettings().GetLayoutRTL(); // TRUE: this outdev will be mirrored if RTL window layout (UI mirroring) is globally active } @@ -1269,7 +1270,10 @@ void Window::ImplLoadRes( const ResId& rResId ) if ( nObjMask & WINDOW_TEXT ) SetText( ReadStringRes() ); if ( nObjMask & WINDOW_HELPTEXT ) + { SetHelpText( ReadStringRes() ); + mpWindowImpl->mbHelpTextDynamic = TRUE; + } if ( nObjMask & WINDOW_QUICKTEXT ) SetQuickHelpText( ReadStringRes() ); if ( nObjMask & WINDOW_EXTRALONG ) @@ -8099,9 +8103,26 @@ const XubString& Window::GetHelpText() const ((Window*)this)->mpWindowImpl->maHelpText = pHelp->GetHelpText( aStrHelpId, this ); else ((Window*)this)->mpWindowImpl->maHelpText = pHelp->GetHelpText( nNumHelpId, this ); + mpWindowImpl->mbHelpTextDynamic = FALSE; } } } + else if( mpWindowImpl->mbHelpTextDynamic && (nNumHelpId || bStrHelpId) ) + { + static const char* pEnv = getenv( "HELP_DEBUG" ); + if( pEnv && *pEnv ) + { + rtl::OUStringBuffer aTxt( 64+mpWindowImpl->maHelpText.Len() ); + aTxt.append( mpWindowImpl->maHelpText ); + aTxt.appendAscii( "\n+++++++++++++++\n" ); + if( bStrHelpId ) + aTxt.append( rtl::OUString( aStrHelpId ) ); + else + aTxt.append( sal_Int32( nNumHelpId ) ); + mpWindowImpl->maHelpText = aTxt.makeStringAndClear(); + } + mpWindowImpl->mbHelpTextDynamic = FALSE; + } return mpWindowImpl->maHelpText; } diff --git a/vcl/source/window/window2.cxx b/vcl/source/window/window2.cxx index af2043fda516..a9bc93863829 100644 --- a/vcl/source/window/window2.cxx +++ b/vcl/source/window/window2.cxx @@ -1999,6 +1999,7 @@ BOOL Window::IsZoom() const void Window::SetHelpText( const XubString& rHelpText ) { mpWindowImpl->maHelpText = rHelpText; + mpWindowImpl->mbHelpTextDynamic = TRUE; } void Window::SetQuickHelpText( const XubString& rHelpText ) -- cgit From c5581dc245fa52b23fe4ab0bfc06501e76c404fe Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 25 Aug 2009 08:52:05 +0000 Subject: #i92516# cosmetics --- vcl/inc/vcl/print.hxx | 2 +- vcl/source/src/print.src | 4 ++-- vcl/source/window/printdlg.cxx | 11 +++++++---- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index fe6d5b7c6f00..2f8a96c690d3 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -423,7 +423,7 @@ public: : nRows( 1 ), nColumns( 1 ), nRepeat( 1 ), aPaperSize( 21000, 29700 ) , nLeftMargin( 0 ), nTopMargin( 0 ) , nRightMargin( 0 ), nBottomMargin( 0 ) - , nHorizontalSpacing( 500 ), nVerticalSpacing( 500 ) + , nHorizontalSpacing( 0 ), nVerticalSpacing( 0 ) , bDrawBorder( false ) , nOrder( LRTB ) { diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 5c04af603c93..5b8ca0447b31 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -32,7 +32,7 @@ ModalDialog SV_DLG_PRINT { - Text [en-US] = "Printing"; + Text [en-US] = "Print"; Closeable = TRUE; Sizeable = TRUE; Moveable = TRUE; @@ -333,7 +333,7 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 100, 10 ); - Text [en-US] = "Location"; + Text [en-US] = "Location:"; }; FixedText SV_PRINT_COMMENT_TXT { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 4f25a9f296a8..d03fd435c191 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -879,13 +879,16 @@ void PrintDialog::setupLayout() // get a row for the preview controls boost::shared_ptr< vcl::RowOrColumn > xPreviewCtrls( new vcl::RowOrColumn( xPreview.get(), false ) ); nIndex = xPreview->addChild( xPreviewCtrls ); - xPreview->setBorders( nIndex, aBorder.Width()*3, 0, aBorder.Width()*3, 0 ); + boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); + xPreviewCtrls->addChild( xSpacer ); xPreviewCtrls->addWindow( &maPageEdit ); xPreviewCtrls->addWindow( &maNumPagesText ); - boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); + xSpacer.reset( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); xPreviewCtrls->addChild( xSpacer ); xPreviewCtrls->addWindow( &maBackwardBtn ); xPreviewCtrls->addWindow( &maForwardBtn ); + xSpacer.reset( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); + xPreviewCtrls->addChild( xSpacer ); // continue with the tab ctrl xPreviewAndTab->addWindow( &maTabCtrl ); @@ -1727,8 +1730,8 @@ void PrintDialog::updateNupFromPages() nRows = nCols = 3; else if( nPages == 16 ) nRows = nCols = 4; - nPageMargin = 500; - nSheetMargin = 500; + nPageMargin = 0; + nSheetMargin = 0; } else bCustom = true; -- cgit From 1d6010c7862a730a67b3a015a3484d07fe96320a Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Wed, 26 Aug 2009 00:41:08 +0000 Subject: added a new vcl event type that carries accessible object so that it can be used from the new menu popup window. --- vcl/inc/vcl/vclevent.hxx | 18 ++++++++++++++++++ vcl/inc/vcl/window.hxx | 2 +- vcl/source/app/vclevent.cxx | 14 ++++++++++++++ vcl/source/window/window.cxx | 5 +++++ vcl/unx/gtk/a11y/atkutil.cxx | 11 ++++++++++- vcl/unx/gtk/a11y/atkwindow.cxx | 26 ++++++++++++++++++++++++-- 6 files changed, 72 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/vclevent.hxx b/vcl/inc/vcl/vclevent.hxx index 88ad880e26ab..c6412d94c852 100644 --- a/vcl/inc/vcl/vclevent.hxx +++ b/vcl/inc/vcl/vclevent.hxx @@ -35,11 +35,19 @@ #include #include +#include + #include class Window; class Menu; +namespace com { namespace sun { namespace star { + namespace accessibility { + class XAccessible; + } +}}} + #define VCLEVENT_OBJECT_DYING 1 // VclWindowEvent: @@ -235,6 +243,16 @@ public: USHORT GetItemPos() const { return mnPos; } }; +class VCL_DLLPUBLIC VclAccessibleEvent: public VclSimpleEvent +{ +public: + VclAccessibleEvent( ULONG n, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& rxAccessible ); + ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetAccessible() const; + +private: + ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > mxAccessible; +}; + class VCL_DLLPUBLIC VclEventListeners : public std::list { public: diff --git a/vcl/inc/vcl/window.hxx b/vcl/inc/vcl/window.hxx index 3f05383d4f80..75ccd5f0acd4 100644 --- a/vcl/inc/vcl/window.hxx +++ b/vcl/inc/vcl/window.hxx @@ -582,7 +582,7 @@ protected: void ImplCallEventListeners( ULONG nEvent, void* pData = NULL ); void CallEventListeners( ULONG nEvent, void* pData = NULL ); - + void FireVclEvent( VclSimpleEvent* pEvent ); // FIXME: this is a hack to workaround missing layout functionality SAL_DLLPRIVATE void ImplAdjustNWFSizes(); diff --git a/vcl/source/app/vclevent.cxx b/vcl/source/app/vclevent.cxx index 8ebc65c8a3f6..721dd9fd0419 100644 --- a/vcl/source/app/vclevent.cxx +++ b/vcl/source/app/vclevent.cxx @@ -34,10 +34,24 @@ #include "vcl/vclevent.hxx" #include "vcl/svdata.hxx" +#include + +using ::com::sun::star::uno::Reference; +using ::com::sun::star::accessibility::XAccessible; + TYPEINIT0(VclSimpleEvent); TYPEINIT1(VclWindowEvent, VclSimpleEvent); TYPEINIT1(VclMenuEvent, VclSimpleEvent); +VclAccessibleEvent::VclAccessibleEvent( ULONG n, const Reference& rxAccessible ) : + VclSimpleEvent(n), + mxAccessible(rxAccessible) {} + +Reference VclAccessibleEvent::GetAccessible() const +{ + return mxAccessible; +} + void VclEventListeners::Call( VclSimpleEvent* pEvent ) const { // Copy the list, because this can be destroyed when calling a Link... diff --git a/vcl/source/window/window.cxx b/vcl/source/window/window.cxx index 279775d712e4..30ba250d2c1a 100644 --- a/vcl/source/window/window.cxx +++ b/vcl/source/window/window.cxx @@ -5367,6 +5367,11 @@ void Window::CallEventListeners( ULONG nEvent, void* pData ) } } +void Window::FireVclEvent( VclSimpleEvent* pEvent ) +{ + ImplGetSVData()->mpApp->ImplCallEventListeners(pEvent); +} + // ----------------------------------------------------------------------- void Window::AddEventListener( const Link& rEventListener ) diff --git a/vcl/unx/gtk/a11y/atkutil.cxx b/vcl/unx/gtk/a11y/atkutil.cxx index 91f4b3280448..1daf1e4ec845 100644 --- a/vcl/unx/gtk/a11y/atkutil.cxx +++ b/vcl/unx/gtk/a11y/atkutil.cxx @@ -628,7 +628,16 @@ long WindowEventHandler(void *, ::VclSimpleEvent const * pEvent) static_cast< ::VclWindowEvent const * >(pEvent)->GetWindow()); */ case VCLEVENT_MENU_HIGHLIGHT: - handle_menu_highlighted(static_cast< ::VclMenuEvent const * >(pEvent)); + if (const VclMenuEvent* pMenuEvent = dynamic_cast(pEvent)) + { + handle_menu_highlighted(pMenuEvent); + } + else if (const VclAccessibleEvent* pAccEvent = dynamic_cast(pEvent)) + { + uno::Reference< accessibility::XAccessible > xAccessible = pAccEvent->GetAccessible(); + if (xAccessible.is()) + atk_wrapper_focus_tracker_notify_when_idle(xAccessible); + } break; case VCLEVENT_TOOLBOX_HIGHLIGHT: diff --git a/vcl/unx/gtk/a11y/atkwindow.cxx b/vcl/unx/gtk/a11y/atkwindow.cxx index 4a64a4959977..83f4c1035916 100644 --- a/vcl/unx/gtk/a11y/atkwindow.cxx +++ b/vcl/unx/gtk/a11y/atkwindow.cxx @@ -114,6 +114,7 @@ init_from_window( AtkObject *accessible, Window *pWindow ) sal_uInt16 nStackLevel = static_cast(pChild)->GetMenuStackLevel(); if (nStackLevel == 0) { + // This is a top-level menu popup. Register it. role = ATK_ROLE_POPUP_MENU; pChild->SetAccessibleRole( AccessibleRole::POPUP_MENU ); accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() ); @@ -147,6 +148,19 @@ ooo_window_wrapper_real_focus_gtk (GtkWidget *, GdkEventFocus *) /*****************************************************************************/ +static bool +isChildPopupMenu(Window* pWindow) +{ + Window* pChild = pWindow->GetAccessibleChildWindow(0); + if (!pChild) + return false; + + if (WINDOW_FLOATINGWINDOW != pChild->GetType()) + return false; + + return static_cast(pChild)->IsPopupMenu(); +} + static void ooo_window_wrapper_real_initialize(AtkObject *obj, gpointer data) { @@ -168,8 +182,16 @@ ooo_window_wrapper_real_initialize(AtkObject *obj, gpointer data) */ if( WINDOW_BORDERWINDOW == pWindow->GetType() ) { - ooo_wrapper_registry_add( xAccessible, obj ); - g_object_set_data( G_OBJECT(obj), "ooo:atk-wrapper-key", xAccessible.get() ); + if ( isChildPopupMenu(pWindow) ) + { + AtkObject *child = atk_object_wrapper_new( xAccessible, obj ); + ooo_wrapper_registry_add( xAccessible, child ); + } + else + { + ooo_wrapper_registry_add( xAccessible, obj ); + g_object_set_data( G_OBJECT(obj), "ooo:atk-wrapper-key", xAccessible.get() ); + } } else { -- cgit From b2cbc1f25f2ea3249b07d7509fbf777886744ee8 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 26 Aug 2009 15:14:10 +0000 Subject: size preview decently --- vcl/source/window/printdlg.cxx | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index d03fd435c191..557a2f478c3c 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -826,7 +826,26 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrsetOptionChangeHdl( LINK( this, PrintDialog, UIOptionsChanged ) ); // set min size pixel to current size - SetMinOutputSizePixel( GetOutputSizePixel() ); + Size aOutSize( GetOutputSizePixel() ); + SetMinOutputSizePixel( aOutSize ); + + // if there is space enough, enlarge the preview so it gets roughly as + // high as the tab control + if( aOutSize.Width() < 768 ) + { + Size aJobPageSize( getJobPageSize() ); + Size aTabSize( maTabCtrl.GetSizePixel() ); + long nOptPreviewWidth = aTabSize.Height() * aJobPageSize.Width() / aJobPageSize.Height(); + // add space for borders + nOptPreviewWidth += 15; + if( aOutSize.Width() - aTabSize.Width() < nOptPreviewWidth ) + { + aOutSize.Width() = aTabSize.Width() + nOptPreviewWidth; + if( aOutSize.Width() > 768 ) // don't enlarge the dialog too much + aOutSize.Width() = 768; + SetOutputSizePixel( aOutSize ); + } + } // restore settings from last run readFromSettings(); -- cgit From 7e43a54274902c7bfc3126034e29c1e88b13b70a Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 26 Aug 2009 15:46:13 +0000 Subject: details with nicer indentation --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/inc/vcl/svids.hrc | 1 + vcl/source/src/print.src | 5 +++++ vcl/source/window/printdlg.cxx | 28 +++++++++++----------------- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 9ea5be6e10b8..0f5288c9d6bd 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -244,6 +244,7 @@ namespace vcl rtl::OUString maPrintToFileText; rtl::OUString maPrintText; + rtl::OUString maDefPrtText; vcl::RowOrColumn maLayout; diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index f21aa6a4cd20..1959a2df3152 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -91,6 +91,7 @@ #define SV_PRINT_PRT_LOCATION 12 #define SV_PRINT_PRT_COMMENT 13 #define SV_PRINT_TOFILE_TXT 14 +#define SV_PRINT_DEFPRT_TXT 15 #define SV_PRINT_TAB_NUP 1 #define SV_PRINT_PRT_NUP_LAYOUT_FL 1 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 5b8ca0447b31..8df7d33e2fed 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -113,6 +113,11 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "Print to file..."; }; + String SV_PRINT_DEFPRT_TXT + { + Text [en-US] = "Default printer"; + }; + TabPage SV_PRINT_TAB_NUP { Text [en-US] = "Page Layout"; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 557a2f478c3c..45c3de5a29be 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -530,22 +530,11 @@ void PrintDialog::JobTabPage::setupLayout() // remember details controls mxDetails = xIndent; // create a column for the details - boost::shared_ptr< vcl::RowOrColumn > xDetCol( new vcl::RowOrColumn( xIndent.get() ) ); - xIndent->setChild( xDetCol ); - // create a row for stati and properties button - boost::shared_ptr< vcl::RowOrColumn > xStateRow( new vcl::RowOrColumn( xDetCol.get(), false ) ); - xDetCol->addChild( xStateRow ); - boost::shared_ptr< vcl::RowOrColumn > xLabelCol( new vcl::RowOrColumn( xStateRow.get(), true, aBorder.Height() ) ); - xStateRow->addChild( xLabelCol ); - xLabelCol->addWindow( &maStatusLabel ); - xLabelCol->addWindow( &maLocationLabel ); - xLabelCol->addWindow( &maCommentLabel ); - - boost::shared_ptr< vcl::RowOrColumn > xStatusCol( new vcl::RowOrColumn( xStateRow.get(), true, aBorder.Height() ) ); - xStateRow->addChild( xStatusCol ); - xStatusCol->addWindow( &maStatusTxt ); - xStatusCol->addWindow( &maLocationTxt ); - xStatusCol->addWindow( &maCommentTxt ); + boost::shared_ptr< vcl::LabelColumn > xLabelCol( new vcl::LabelColumn( xIndent.get(), aBorder.Height() ) ); + xIndent->setChild( xLabelCol ); + xLabelCol->addRow( &maStatusLabel, &maStatusTxt ); + xLabelCol->addRow( &maLocationLabel, &maLocationTxt ); + xLabelCol->addRow( &maCommentLabel, &maCommentTxt ); // add print range and copies columns maLayout.addWindow( &maCopies ); @@ -707,6 +696,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrGetLocation() ); maJobPage.maCommentTxt.SetText( pInfo->GetComment() ); // FIXME: status text - maJobPage.maStatusTxt.SetText( String() ); + rtl::OUString aStatus; + if( aDefPrt == pInfo->GetPrinterName() ) + aStatus = maDefPrtText; + maJobPage.maStatusTxt.SetText( aStatus ); } else { -- cgit From b5022546b067c67611075b81ced67a3a0d45ca08 Mon Sep 17 00:00:00 2001 From: Thomas Lange Date: Wed, 26 Aug 2009 16:28:12 +0000 Subject: #i92516# user paper override not functional in all cases --- vcl/source/gdi/print3.cxx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 479095d94265..926f44f13692 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -189,6 +189,7 @@ public: return maMultiPage.aPaperSize; return i_rPageSize; } + PrinterController::PageSize modifyJobSetup( const Sequence< PropertyValue >& i_rProps ); }; PrinterController::PrinterController() @@ -588,10 +589,10 @@ bool PrinterController::setupPrinter( Window* i_pParent ) return bRet; } -static PrinterController::PageSize modifyJobSetup( Printer* pPrinter, const Sequence< PropertyValue >& i_rProps ) +PrinterController::PageSize vcl::ImplPrinterControllerData::modifyJobSetup( const Sequence< PropertyValue >& i_rProps ) { PrinterController::PageSize aPageSize; - aPageSize.aSize = pPrinter->GetPaperSize(); + aPageSize.aSize = mpPrinter->GetPaperSize(); for( sal_Int32 nProperty = 0, nPropertyCount = i_rProps.getLength(); nProperty < nPropertyCount; ++nProperty ) { if( i_rProps[ nProperty ].Name.equalsAscii( "PageSize" ) ) @@ -601,9 +602,10 @@ static PrinterController::PageSize modifyJobSetup( Printer* pPrinter, const Sequ aPageSize.aSize.Width() = aSize.Width; aPageSize.aSize.Height() = aSize.Height; - Size aCurSize( pPrinter->GetPaperSize() ); - if( aPageSize.aSize != aCurSize ) - pPrinter->SetPaperSizeUser( aPageSize.aSize ); + Size aCurSize( mpPrinter->GetPaperSize() ); + Size aRealPaperSize( getRealPaperSize( aPageSize.aSize ) ); + if( aRealPaperSize != aCurSize ) + mpPrinter->SetPaperSizeUser( aRealPaperSize ); } if( i_rProps[ nProperty ].Name.equalsAscii( "PageIncludesNonprintableArea" ) ) { @@ -670,7 +672,7 @@ PrinterController::PageSize PrinterController::getPageFile( int i_nUnfilteredPag mpImplData->mpPrinter->SetMapMode( aMapMode ); // modify job setup if necessary - PrinterController::PageSize aPageSize = modifyJobSetup( mpImplData->mpPrinter.get(), aPageParm ); + PrinterController::PageSize aPageSize = mpImplData->modifyJobSetup( aPageParm ); o_rMtf.SetPrefSize( aPageSize.aSize ); o_rMtf.SetPrefMapMode( aMapMode ); -- cgit From 5a6ece62b1df0c10a4997e3432756c632901ca75 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Wed, 26 Aug 2009 17:16:32 +0000 Subject: more cosmetics --- vcl/source/window/arrange.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/arrange.cxx b/vcl/source/window/arrange.cxx index 7e019dc7e5ac..0199af7ed50d 100644 --- a/vcl/source/window/arrange.cxx +++ b/vcl/source/window/arrange.cxx @@ -661,7 +661,7 @@ void LabelColumn::resize() size_t LabelColumn::addRow( Window* i_pLabel, boost::shared_ptr const& i_rElement, long i_nIndent ) { - boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 2 ) ); + boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 1 ) ); xLabel->setLabel( i_pLabel ); xLabel->setBorders( 0, i_nIndent, 0, 0, 0 ); xLabel->setElement( i_rElement ); @@ -672,7 +672,7 @@ size_t LabelColumn::addRow( Window* i_pLabel, boost::shared_ptr size_t LabelColumn::addRow( Window* i_pLabel, Window* i_pElement, long i_nIndent ) { - boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 2 ) ); + boost::shared_ptr< LabeledElement > xLabel( new LabeledElement( this, 1 ) ); xLabel->setLabel( i_pLabel ); xLabel->setBorders( 0, i_nIndent, 0, 0, 0 ); xLabel->setElement( i_pElement ); -- cgit From 22aa57f666acce83cf8227eb54ee386ae3be8445 Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Wed, 26 Aug 2009 22:54:20 +0000 Subject: added the concept of "fake focus" to simulate focus inside floating windows. I need this because floating windows don't get system focus, but focus handling is needed for tab stops. --- vcl/inc/vcl/window.h | 3 ++- vcl/inc/vcl/window.hxx | 7 +++++++ vcl/source/window/window.cxx | 24 +++++++++++++++++++++--- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/window.h b/vcl/inc/vcl/window.h index d745f3dcf081..e18bc42b4b27 100644 --- a/vcl/inc/vcl/window.h +++ b/vcl/inc/vcl/window.h @@ -358,7 +358,8 @@ public: mbToolbarFloatingWindow:1, mbCallHandlersDuringInputDisabled:1, mbDisableAccessibleLabelForRelation:1, - mbDisableAccessibleLabeledByRelation:1; + mbDisableAccessibleLabeledByRelation:1, + mbFakeFocusSet:1; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > mxDNDListenerContainer; }; diff --git a/vcl/inc/vcl/window.hxx b/vcl/inc/vcl/window.hxx index 75ccd5f0acd4..8c42ebd5dd21 100644 --- a/vcl/inc/vcl/window.hxx +++ b/vcl/inc/vcl/window.hxx @@ -899,6 +899,13 @@ public: USHORT GetGetFocusFlags() const; void GrabFocusToDocument(); + /** + * Set this when you need to act as if the window has focus even if it + * doesn't. This is necessary for implementing tab stops inside floating + * windows, but floating windows don't get focus from the system. + */ + void SetFakeFocus( bool bFocus ); + BOOL IsCompoundControl() const; BOOL HasCompoundControlFocus() const; diff --git a/vcl/source/window/window.cxx b/vcl/source/window/window.cxx index 30ba250d2c1a..e4285482e3b7 100644 --- a/vcl/source/window/window.cxx +++ b/vcl/source/window/window.cxx @@ -690,6 +690,7 @@ void Window::ImplInitWindowData( WindowType nType ) mpWindowImpl->mbCallHandlersDuringInputDisabled = FALSE; // TRUE: call event handlers even if input is disabled mpWindowImpl->mbDisableAccessibleLabelForRelation = FALSE; // TRUE: do not set LabelFor relation on accessible objects mpWindowImpl->mbDisableAccessibleLabeledByRelation = FALSE; // TRUE: do not set LabeledBy relation on accessible objects + mpWindowImpl->mbFakeFocusSet = FALSE; // TRUE: pretend as if the window has focus. mbEnableRTL = Application::GetSettings().GetLayoutRTL(); // TRUE: this outdev will be mirrored if RTL window layout (UI mirroring) is globally active } @@ -3901,6 +3902,20 @@ void Window::ImplCallFocusChangeActivate( Window* pNewOverlapWindow, } } +static bool IsWindowFocused(const WindowImpl& rWinImpl) +{ + if (rWinImpl.mpSysObj) + return true; + + if (rWinImpl.mpFrameData->mbHasFocus) + return true; + + if (rWinImpl.mbFakeFocusSet) + return true; + + return false; +} + // ----------------------------------------------------------------------- void Window::ImplGrabFocus( USHORT nFlags ) { @@ -3972,9 +3987,7 @@ void Window::ImplGrabFocus( USHORT nFlags ) pFrame = pFrame->mpWindowImpl->mpFrameData->mpNextFrame; } - BOOL bHasFocus = TRUE; - if ( !mpWindowImpl->mpSysObj && !mpWindowImpl->mpFrameData->mbHasFocus ) - bHasFocus = FALSE; + bool bHasFocus = IsWindowFocused(*mpWindowImpl); BOOL bMustNotGrabFocus = FALSE; // #100242#, check parent hierarchy if some floater prohibits grab focus @@ -7738,6 +7751,11 @@ void Window::GrabFocusToDocument() } } +void Window::SetFakeFocus( bool bFocus ) +{ + ImplGetWindowImpl()->mbFakeFocusSet = bFocus; +} + // ----------------------------------------------------------------------- BOOL Window::HasChildPathFocus( BOOL bSystemWindow ) const -- cgit From 2e77984f087afde2ba0ca0edc5987a6f52d1095e Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Thu, 27 Aug 2009 02:35:27 +0000 Subject: Added a new child class of FloatingWindow to separate popup menu specific stuff to it. Let's leave the existing FloatingWindow alone. --- vcl/inc/vcl/floatwin.hxx | 4 -- vcl/inc/vcl/popupmenuwindow.hxx | 50 +++++++++++++++++++++ vcl/prj/d.lst | 1 + vcl/source/window/floatwin.cxx | 19 +------- vcl/source/window/makefile.mk | 1 + vcl/source/window/popupmenuwindow.cxx | 82 +++++++++++++++++++++++++++++++++++ vcl/unx/gtk/a11y/atkwindow.cxx | 12 +++-- 7 files changed, 143 insertions(+), 26 deletions(-) create mode 100644 vcl/inc/vcl/popupmenuwindow.hxx create mode 100644 vcl/source/window/popupmenuwindow.cxx diff --git a/vcl/inc/vcl/floatwin.hxx b/vcl/inc/vcl/floatwin.hxx index 351c31df1c1b..8dcba41e2a8e 100644 --- a/vcl/inc/vcl/floatwin.hxx +++ b/vcl/inc/vcl/floatwin.hxx @@ -157,10 +157,6 @@ public: const Link& GetPopupModeEndHdl() const { return maPopupModeEndHdl; } BOOL GrabsFocus() const { return mbGrabFocus; } - - sal_uInt16 GetMenuStackLevel() const; - void SetMenuStackLevel( sal_uInt16 nLevel ); - bool IsPopupMenu() const; }; #endif // _SV_FLOATWIN_HXX diff --git a/vcl/inc/vcl/popupmenuwindow.hxx b/vcl/inc/vcl/popupmenuwindow.hxx new file mode 100644 index 000000000000..af8d1f804598 --- /dev/null +++ b/vcl/inc/vcl/popupmenuwindow.hxx @@ -0,0 +1,50 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: floatwin.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef __POPUPMENUWINDOW_HXX__ +#define __POPUPMENUWINDOW_HXX__ + +#include "vcl/floatwin.hxx" + +class VCL_DLLPUBLIC PopupMenuFloatingWindow : public FloatingWindow +{ +private: + struct ImplData; + ImplData* mpImplData; +public: + PopupMenuFloatingWindow( Window* pParent, WinBits nStyle = (WB_SYSTEMFLOATWIN|WB_SYSTEMWINDOW|WB_NOBORDER) ); + ~PopupMenuFloatingWindow(); + + sal_uInt16 GetMenuStackLevel() const; + void SetMenuStackLevel( sal_uInt16 nLevel ); + bool IsPopupMenu() const; +}; + +#endif diff --git a/vcl/prj/d.lst b/vcl/prj/d.lst index d9c14f46b8d1..7ac2c74c96e8 100644 --- a/vcl/prj/d.lst +++ b/vcl/prj/d.lst @@ -84,6 +84,7 @@ mkdir: %_DEST%\inc%_EXT%\vcl\plug\vcl ..\inc\vcl\octree.hxx %_DEST%\inc%_EXT%\vcl\octree.hxx ..\inc\vcl\outdev.hxx %_DEST%\inc%_EXT%\vcl\outdev.hxx ..\inc\vcl\pointr.hxx %_DEST%\inc%_EXT%\vcl\pointr.hxx +..\inc\vcl\popupmenuwindow.hxx %_DEST%\inc%_EXT%\vcl\popupmenuwindow.hxx ..\inc\vcl\print.hxx %_DEST%\inc%_EXT%\vcl\print.hxx ..\inc\vcl\prndlg.hxx %_DEST%\inc%_EXT%\vcl\prndlg.hxx ..\inc\vcl\prntypes.hxx %_DEST%\inc%_EXT%\vcl\prntypes.hxx diff --git a/vcl/source/window/floatwin.cxx b/vcl/source/window/floatwin.cxx index b29b74e63f78..7bcb90bbb8fc 100644 --- a/vcl/source/window/floatwin.cxx +++ b/vcl/source/window/floatwin.cxx @@ -48,7 +48,6 @@ #include #include -#include // ======================================================================= @@ -60,11 +59,9 @@ public: ToolBox* mpBox; Rectangle maItemEdgeClipRect; // used to clip the common edge between a toolbar item and the border of this window - sal_uInt16 mnMenuStackLevel; // in case it is used as a menu popup, store its stack level. 0 = top-level menu. }; -FloatingWindow::ImplData::ImplData() : - mnMenuStackLevel( ::std::numeric_limits::max() ) +FloatingWindow::ImplData::ImplData() { mpBox = NULL; } @@ -876,17 +873,3 @@ void FloatingWindow::RemovePopupModeWindow( Window* pWindow ) mpFirstPopupModeWin = NULL; } -sal_uInt16 FloatingWindow::GetMenuStackLevel() const -{ - return mpImplData->mnMenuStackLevel; -} - -void FloatingWindow::SetMenuStackLevel( sal_uInt16 nLevel ) -{ - mpImplData->mnMenuStackLevel = nLevel; -} - -bool FloatingWindow::IsPopupMenu() const -{ - return mpImplData->mnMenuStackLevel != ::std::numeric_limits::max(); -} diff --git a/vcl/source/window/makefile.mk b/vcl/source/window/makefile.mk index cdd4aef73bb0..a518ce124b74 100644 --- a/vcl/source/window/makefile.mk +++ b/vcl/source/window/makefile.mk @@ -69,6 +69,7 @@ SLOFILES= \ $(SLO)$/mnemonic.obj \ $(SLO)$/mnemonicengine.obj \ $(SLO)$/msgbox.obj \ + $(SLO)$/popupmenuwindow.obj \ $(SLO)$/scrwnd.obj \ $(SLO)$/seleng.obj \ $(SLO)$/split.obj \ diff --git a/vcl/source/window/popupmenuwindow.cxx b/vcl/source/window/popupmenuwindow.cxx new file mode 100644 index 000000000000..29d60a7cc02d --- /dev/null +++ b/vcl/source/window/popupmenuwindow.cxx @@ -0,0 +1,82 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: floatwin.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_vcl.hxx" + +#include "vcl/popupmenuwindow.hxx" + +#include + +struct PopupMenuFloatingWindow::ImplData +{ + sal_uInt16 mnMenuStackLevel; // Store the stack level of a popup menu. 0 = top-level menu. + + ImplData(); + ~ImplData(); +}; + +PopupMenuFloatingWindow::ImplData::ImplData() : + mnMenuStackLevel( ::std::numeric_limits::max() ) +{ +} + +PopupMenuFloatingWindow::ImplData::~ImplData() +{ +} + +// ============================================================================ + +PopupMenuFloatingWindow::PopupMenuFloatingWindow( Window* pParent, WinBits nStyle ) : + FloatingWindow(pParent, nStyle), + mpImplData(new ImplData) +{ +} + +PopupMenuFloatingWindow::~PopupMenuFloatingWindow() +{ + delete mpImplData; +} + +sal_uInt16 PopupMenuFloatingWindow::GetMenuStackLevel() const +{ + return mpImplData->mnMenuStackLevel; +} + +void PopupMenuFloatingWindow::SetMenuStackLevel( sal_uInt16 nLevel ) +{ + mpImplData->mnMenuStackLevel = nLevel; +} + +bool PopupMenuFloatingWindow::IsPopupMenu() const +{ + return mpImplData->mnMenuStackLevel != ::std::numeric_limits::max(); +} + diff --git a/vcl/unx/gtk/a11y/atkwindow.cxx b/vcl/unx/gtk/a11y/atkwindow.cxx index 83f4c1035916..1bda4eea774e 100644 --- a/vcl/unx/gtk/a11y/atkwindow.cxx +++ b/vcl/unx/gtk/a11y/atkwindow.cxx @@ -33,7 +33,7 @@ #include #include -#include "vcl/floatwin.hxx" +#include "vcl/popupmenuwindow.hxx" #include "atkwindow.hxx" #include "atkwrapper.hxx" @@ -111,8 +111,8 @@ init_from_window( AtkObject *accessible, Window *pWindow ) } else if ( pWindow->GetType() == WINDOW_BORDERWINDOW && pChild->GetType() == WINDOW_FLOATINGWINDOW ) { - sal_uInt16 nStackLevel = static_cast(pChild)->GetMenuStackLevel(); - if (nStackLevel == 0) + PopupMenuFloatingWindow* p = dynamic_cast(pChild); + if (p && p->IsPopupMenu() && p->GetMenuStackLevel() == 0) { // This is a top-level menu popup. Register it. role = ATK_ROLE_POPUP_MENU; @@ -158,7 +158,11 @@ isChildPopupMenu(Window* pWindow) if (WINDOW_FLOATINGWINDOW != pChild->GetType()) return false; - return static_cast(pChild)->IsPopupMenu(); + PopupMenuFloatingWindow* p = dynamic_cast(pChild); + if (!p) + return false; + + return p->IsPopupMenu(); } static void -- cgit From 4e0267c10be60f4e938e3f32b39ea1181496fd89 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 13:41:02 +0000 Subject: #i92516# IsFirstPage property --- vcl/source/gdi/print3.cxx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 926f44f13692..f4a718abc3b9 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -159,6 +159,7 @@ public: PropertyToIndexMap maPropertyToIndex; Link maOptionChangeHdl; ControlDependencyMap maControlDependencies; + sal_Bool mbFirstPage; sal_Bool mbLastPage; sal_Bool mbReversePageOrder; view::PrintableState meJobState; @@ -174,6 +175,7 @@ public: Size maFixedPageSize; ImplPrinterControllerData() : + mbFirstPage( sal_True ), mbLastPage( sal_False ), mbReversePageOrder( sal_False ), meJobState( view::PrintableState_JOB_STARTED ), @@ -690,6 +692,9 @@ PrinterController::PageSize PrinterController::getPageFile( int i_nUnfilteredPag if( i_bMayUseCache ) mpImplData->maPageCache.insert( i_nUnfilteredPage, o_rMtf, aPageSize ); + // reset "FirstPage" property to false now we've gotten at least our first one + mpImplData->mbFirstPage = sal_False; + return aPageSize; } @@ -987,6 +992,14 @@ Sequence< PropertyValue > PrinterController::getJobProperties( const Sequence< P if( aMergeSet.find( mpImplData->maUIProperties[i].Name ) == aMergeSet.end() ) aResult[nCur++] = mpImplData->maUIProperties[i]; } + // append IsFirstPage + if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFirstPage" ) ) ) == aMergeSet.end() ) + { + PropertyValue aVal; + aVal.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFirstPage" ) ); + aVal.Value <<= mpImplData->mbFirstPage; + aResult[nCur++] = aVal; + } // append IsLastPage if( aMergeSet.find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsLastPage" ) ) ) == aMergeSet.end() ) { -- cgit From 0b66a79a38b3f6fb1790307f6459a62efec35442 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 13:48:47 +0000 Subject: #i92516# no progress on api print --- vcl/source/gdi/print3.cxx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index f4a718abc3b9..2056df3a7d3d 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1218,6 +1218,16 @@ void PrinterController::createProgressDialog() beans::PropertyValue* pMonitor = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MonitorVisible" ) ) ); if( pMonitor ) pMonitor->Value >>= bShow; + else + { + const com::sun::star::beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsApi" ) ) ); + if( pVal ) + { + sal_Bool bApi = sal_False; + pVal->Value >>= bApi; + bShow = ! bApi; + } + } if( bShow && ! Application::IsHeadlessModeEnabled() ) { -- cgit From c9bf01e4958f7d9dd7876c10a6476bc0d84c7ea0 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 16:08:23 +0000 Subject: #i92516# imporve CalcMinimumSize --- vcl/source/control/edit.cxx | 3 +++ vcl/source/control/lstbox.cxx | 1 + 2 files changed, 4 insertions(+) diff --git a/vcl/source/control/edit.cxx b/vcl/source/control/edit.cxx index 2b6f20977689..7c02b9aadbbd 100644 --- a/vcl/source/control/edit.cxx +++ b/vcl/source/control/edit.cxx @@ -2836,6 +2836,9 @@ Size Edit::CalcMinimumSize() const Size aMinSize ( CalcSize( 3 ) ); if( aSize.Width() < aMinSize.Width() ) aSize.Width() = aMinSize.Width(); + // add some space between text entry an border + aSize.Height() += 4; + aSize = CalcWindowSize( aSize ); // ask NWF what if it has an opinion, too diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index 55a5e8bfd282..ce1f4f5ce22a 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -1284,6 +1284,7 @@ Size ListBox::CalcMinimumSize() const else { aSz.Height() = mpImplLB->CalcSize( 1 ).Height(); + aSz.Height() += 4; // add a space between entry and border // size to maxmimum entry width and add a little breathing space aSz.Width() = mpImplLB->GetMaxEntryWidth() + 4; // do not create ultrathin ListBoxes, it doesn't look good -- cgit From 2fbe64f3eca3bb4f2d881ae764d9362a2d3c8b5f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 16:14:43 +0000 Subject: #i92516# set page marging to 0 in 1 page case --- vcl/source/window/printdlg.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 45c3de5a29be..032343f10020 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1718,6 +1718,7 @@ void PrintDialog::updateNupFromPages() { nRows = nCols = 1; nSheetMargin = 0; + nPageMargin = 0; } else if( nPages == 2 || nPages == 4 || nPages == 6 || nPages == 9 || nPages == 16 ) { -- cgit From b380b1cb316a12e1ee8cce2749686c0f4fd99425 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 17:19:25 +0000 Subject: #i92516# margin logic in dialog --- vcl/source/gdi/print3.cxx | 18 +++++++----------- vcl/source/window/printdlg.cxx | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 2056df3a7d3d..b56016a3cfbd 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -707,26 +707,22 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD // save gstate o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION | PUSH_MAPMODE ) ); + // clip to page rect + o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); + + // append the subpage + io_rSubPage.WindStart(); + io_rSubPage.Play( o_rMtf ); + // draw a border if( i_bDrawBorder ) { Rectangle aBorderRect( i_rClipRect ); - aBorderRect.Left() -= 100; - aBorderRect.Top() -= 100; - aBorderRect.Right() += 100; - aBorderRect.Bottom() += 100; o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); o_rMtf.AddAction( new MetaRectAction( aBorderRect ) ); } - // clip to page rect - // o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); - - // append the subpage - io_rSubPage.WindStart(); - io_rSubPage.Play( o_rMtf ); - // restore gstate o_rMtf.AddAction( new MetaPopAction() ); } diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 032343f10020..5fb63275f5d8 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1750,6 +1750,41 @@ void PrintDialog::updateNupFromPages() else bCustom = true; + if( nPages > 1 ) + { + // set upper limits for margins based on job page size and rows/columns + Size aSize( getJobPageSize() ); + + // maximum sheet distance: 1/2 sheet + long nHorzMax = aSize.Width()/2; + long nVertMax = aSize.Height()/2; + if( nSheetMargin > nHorzMax ) + nSheetMargin = nHorzMax; + if( nSheetMargin > nVertMax ) + nSheetMargin = nVertMax; + + maNUpPage.maSheetMarginEdt.SetMax( + maNUpPage.maSheetMarginEdt.Normalize( + nHorzMax > nVertMax ? nVertMax : nHorzMax ), FUNIT_100TH_MM ); + + // maximum page distance + nHorzMax = (aSize.Width() - 2*nSheetMargin); + if( nCols > 1 ) + nHorzMax /= (nCols-1); + nVertMax = (aSize.Height() - 2*nSheetMargin); + if( nRows > 1 ) + nHorzMax /= (nRows-1); + + if( nPageMargin > nHorzMax ) + nPageMargin = nHorzMax; + if( nPageMargin > nVertMax ) + nPageMargin = nVertMax; + + maNUpPage.maPageMarginEdt.SetMax( + maNUpPage.maSheetMarginEdt.Normalize( + nHorzMax > nVertMax ? nVertMax : nHorzMax ), FUNIT_100TH_MM ); + } + maNUpPage.maNupRowsEdt.SetValue( nRows ); maNUpPage.maNupColEdt.SetValue( nCols ); maNUpPage.maPageMarginEdt.SetValue( maNUpPage.maPageMarginEdt.Normalize( nPageMargin ), FUNIT_100TH_MM ); @@ -1956,7 +1991,7 @@ IMPL_LINK( PrintDialog, ModifyHdl, Edit*, pEdit ) pEdit == &maNUpPage.maSheetMarginEdt || pEdit == &maNUpPage.maPageMarginEdt ) { - updateNup(); + updateNupFromPages(); } else if( pEdit == &maPageEdit ) { -- cgit From a2df349f777528b652637415364e7a97d25603ca Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 31 Aug 2009 17:28:02 +0000 Subject: #i92516# make formula editor look a little better --- vcl/source/window/printdlg.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 5fb63275f5d8..2d1bbf43e607 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -550,11 +550,11 @@ void PrintDialog::JobTabPage::setupLayout() xRangeRow->addChild( xCopyCollateCol ); // add copies row to copy/collate column - boost::shared_ptr< vcl::LabeledElement > xCopiesRow( new vcl::LabeledElement( xCopyCollateCol.get() ) ); + boost::shared_ptr< vcl::LabeledElement > xCopiesRow( new vcl::LabeledElement( xCopyCollateCol.get(), 2 ) ); xCopyCollateCol->addChild( xCopiesRow ); xCopiesRow->setLabel( &maCopyCount ); xCopiesRow->setElement( &maCopyCountField ); - boost::shared_ptr< vcl::LabeledElement > xCollateRow( new vcl::LabeledElement( xCopyCollateCol.get() ) ); + boost::shared_ptr< vcl::LabeledElement > xCollateRow( new vcl::LabeledElement( xCopyCollateCol.get(), 2 ) ); xCopyCollateCol->addChild( xCollateRow ); xCollateRow->setLabel( &maCollateBox ); xCollateRow->setElement( &maCollateImage ); -- cgit From 29572d6eebbd0a72cc7f244b613ed029e2b1ac54 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 1 Sep 2009 18:17:36 +0000 Subject: #i104668# fix IsLasPage handling --- vcl/source/gdi/print3.cxx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index b56016a3cfbd..7a85091c052f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -762,6 +762,11 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte return aPageSize; } + // set last page property really only on the very last page to be rendered + // that is on the last subpage of a NUp run + sal_Bool bIsLastPage = mpImplData->mbLastPage; + mpImplData->mbLastPage = sal_False; + Size aPaperSize( mpImplData->getRealPaperSize( mpImplData->maMultiPage.aPaperSize ) ); // multi page area: paper size minus margins + one time spacing right and down // the added spacing is so each subpage can be calculated including its spacing @@ -789,7 +794,16 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte // map current sub page to real page int nPage = (i_nFilteredPage * nSubPages + nSubPage) / rMPS.nRepeat; if( mpImplData->mbReversePageOrder ) + { nPage = nDocPages - 1 - nPage; + if( nPage == 0 ) + mpImplData->mbLastPage = bIsLastPage; + } + else + { + if( nPage == nDocPages-1 ) + mpImplData->mbLastPage = bIsLastPage; + } if( nPage >= 0 && nPage < nDocPages ) { GDIMetaFile aPageFile; -- cgit From eb7e3a297515f8f603c8372b4276d6a14c09ef40 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 13:44:16 +0000 Subject: #i104763# inform app about need to reformat --- vcl/source/gdi/print3.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 7a85091c052f..88006a845936 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -585,6 +585,11 @@ bool PrinterController::setupPrinter( Window* i_pParent ) { mpImplData->maFixedPageSize = aNewPaperSize; mpImplData->maPageCache.invalidate(); + awt::Size aOverrideSize; + aOverrideSize.Width = aNewPaperSize.Width(); + aOverrideSize.Height = aNewPaperSize.Height(); + setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OverridePageSize" ) ), + makeAny( aOverrideSize ) ); } } } -- cgit From da62b0feb684b34ab191fb0f03ed5432c14cba97 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 15:20:56 +0000 Subject: #i104693# nearest paper matching --- vcl/inc/vcl/print.hxx | 3 ++- vcl/source/gdi/print.cxx | 51 +++++++++++++++++++++++++++++++++++++++--- vcl/source/gdi/print3.cxx | 8 ++++--- vcl/source/window/printdlg.cxx | 9 ++++++++ 4 files changed, 64 insertions(+), 7 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 2f8a96c690d3..fe906988de2c 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -261,7 +261,7 @@ private: const XubString* pDriver ); SAL_DLLPRIVATE void ImplUpdatePageData(); SAL_DLLPRIVATE void ImplUpdateFontList(); - SAL_DLLPRIVATE void ImplFindPaperFormatForUserSize( JobSetup& ); + SAL_DLLPRIVATE void ImplFindPaperFormatForUserSize( JobSetup&, bool bMatchNearest ); DECL_DLLPRIVATE_LINK( ImplDestroyPrinterAsync, void* ); SAL_DLLPRIVATE bool StartJob( const rtl::OUString& rJobName, boost::shared_ptr& ); @@ -331,6 +331,7 @@ public: USHORT GetPaperBin() const; BOOL SetPaper( Paper ePaper ); BOOL SetPaperSizeUser( const Size& rSize ); + BOOL SetPaperSizeUser( const Size& rSize, bool bMatchNearest ); Paper GetPaper() const; // returns number of available paper formats diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index f7db0b56f4ca..c70835de47e7 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -974,12 +974,13 @@ USHORT Printer::GetPaperBin() const // ----------------------------------------------------------------------- // Map user paper format to a available printer paper formats -void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup ) +void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup, bool bMatchNearest ) { ImplJobSetup* pSetupData = aJobSetup.ImplGetData(); int nLandscapeAngle = GetLandscapeAngle(); int nPaperCount = GetPaperInfoCount(); + bool bFound = false; PaperInfo aInfo(pSetupData->mnPaperWidth, pSetupData->mnPaperHeight); @@ -993,6 +994,7 @@ void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup ) pSetupData->mePaperFormat = ImplGetPaperFormat( rPaperInfo.getWidth(), rPaperInfo.getHeight() ); pSetupData->meOrientation = ORIENTATION_PORTRAIT; + bFound = true; break; } } @@ -1016,10 +1018,48 @@ void Printer::ImplFindPaperFormatForUserSize( JobSetup& aJobSetup ) pSetupData->mePaperFormat = ImplGetPaperFormat( rPaperInfo.getWidth(), rPaperInfo.getHeight() ); pSetupData->meOrientation = ORIENTATION_LANDSCAPE; + bFound = true; break; } } } + + if( ! bFound && bMatchNearest ) + { + sal_Int64 nBestMatch = SAL_MAX_INT64; + int nBestIndex = 0; + Orientation eBestOrientation = ORIENTATION_PORTRAIT; + for( int i = 0; i < nPaperCount; i++ ) + { + const PaperInfo& rPaperInfo = GetPaperInfo( i ); + + // check protrait match + sal_Int64 nDX = pSetupData->mnPaperWidth - rPaperInfo.getWidth(); + sal_Int64 nDY = pSetupData->mnPaperHeight - rPaperInfo.getHeight(); + sal_Int64 nMatch = nDX*nDX + nDY*nDY; + if( nMatch < nBestMatch ) + { + nBestMatch = nMatch; + nBestIndex = i; + eBestOrientation = ORIENTATION_PORTRAIT; + } + + // check landscape match + nDX = pSetupData->mnPaperWidth - rPaperInfo.getHeight(); + nDY = pSetupData->mnPaperHeight - rPaperInfo.getWidth(); + nMatch = nDX*nDX + nDY*nDY; + if( nMatch < nBestMatch ) + { + nBestMatch = nMatch; + nBestIndex = i; + eBestOrientation = ORIENTATION_LANDSCAPE; + } + } + const PaperInfo& rBestInfo = GetPaperInfo( nBestIndex ); + pSetupData->mePaperFormat = ImplGetPaperFormat( rBestInfo.getWidth(), + rBestInfo.getHeight() ); + pSetupData->meOrientation = eBestOrientation; + } } // ----------------------------------------------------------------------- @@ -1050,7 +1090,7 @@ BOOL Printer::SetPaper( Paper ePaper ) ImplReleaseGraphics(); if ( ePaper == PAPER_USER ) - ImplFindPaperFormatForUserSize( aJobSetup ); + ImplFindPaperFormatForUserSize( aJobSetup, false ); if ( mpInfoPrinter->SetData( SAL_JOBSET_PAPERSIZE|SAL_JOBSET_ORIENTATION, pSetupData ) ) { ImplUpdateJobSetupPaper( aJobSetup ); @@ -1070,6 +1110,11 @@ BOOL Printer::SetPaper( Paper ePaper ) // ----------------------------------------------------------------------- BOOL Printer::SetPaperSizeUser( const Size& rSize ) +{ + return SetPaperSizeUser( rSize, false ); +} + +BOOL Printer::SetPaperSizeUser( const Size& rSize, bool bMatchNearest ) { if ( mbInPrintPage ) return FALSE; @@ -1094,7 +1139,7 @@ BOOL Printer::SetPaperSizeUser( const Size& rSize ) } ImplReleaseGraphics(); - ImplFindPaperFormatForUserSize( aJobSetup ); + ImplFindPaperFormatForUserSize( aJobSetup, bMatchNearest ); // Changing the paper size can also change the orientation! if ( mpInfoPrinter->SetData( SAL_JOBSET_PAPERSIZE|SAL_JOBSET_ORIENTATION, pSetupData ) ) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 88006a845936..f8bf4aa6df80 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -191,6 +191,8 @@ public: return maMultiPage.aPaperSize; return i_rPageSize; } + bool isFixedPageSize() const + { return maFixedPageSize.Width() != 0 && maFixedPageSize.Height() != 0; } PrinterController::PageSize modifyJobSetup( const Sequence< PropertyValue >& i_rProps ); }; @@ -612,7 +614,7 @@ PrinterController::PageSize vcl::ImplPrinterControllerData::modifyJobSetup( cons Size aCurSize( mpPrinter->GetPaperSize() ); Size aRealPaperSize( getRealPaperSize( aPageSize.aSize ) ); if( aRealPaperSize != aCurSize ) - mpPrinter->SetPaperSizeUser( aRealPaperSize ); + mpPrinter->SetPaperSizeUser( aRealPaperSize, ! isFixedPageSize() ); } if( i_rProps[ nProperty ].Name.equalsAscii( "PageIncludesNonprintableArea" ) ) { @@ -854,7 +856,7 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte o_rMtf.WindStart(); mpImplData->mpPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); - mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize ); + mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize, ! mpImplData->isFixedPageSize() ); return PrinterController::PageSize( aPaperSize ); } @@ -941,7 +943,7 @@ void PrinterController::printFilteredPage( int i_nPage ) // in N-Up printing set the correct page size mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); // aPageSize was filtered through mpImplData->getRealPaperSize already by getFilteredPageFile() - mpImplData->mpPrinter->SetPaperSizeUser( aPageSize.aSize ); + mpImplData->mpPrinter->SetPaperSizeUser( aPageSize.aSize, ! mpImplData->isFixedPageSize() ); // if full paper are is meant, move the output to accomodate for pageoffset if( aPageSize.bFullPaper ) { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 2d1bbf43e607..f98dcdf0da2d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -174,6 +174,15 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi sal_Int32 i_nDPIY ) { + #if OSL_DEBUG_LEVEL > 0 + rtl::OUStringBuffer aBuf( 256 ); + aBuf.appendAscii( "PageSize: " ); + aBuf.append( sal_Int32( i_rOrigSize.Width()/100) ); + aBuf.appendAscii( "mm x " ); + aBuf.append( sal_Int32( i_rOrigSize.Height()/100) ); + aBuf.appendAscii( "mm" ); + SetQuickHelpText( aBuf.makeStringAndClear() ); + #endif maMtf = i_rNewPreview; maOrigSize = i_rOrigSize; maReplacementString = i_rReplacement; -- cgit From ea4051a25356bdb6ad9501cf1d17a6f726382fab Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 16:05:37 +0000 Subject: #i104664# resize on collpsing details --- vcl/inc/vcl/prndlg.hxx | 3 +++ vcl/source/window/printdlg.cxx | 29 +++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 0f5288c9d6bd..3164de82fbeb 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -248,6 +248,9 @@ namespace vcl vcl::RowOrColumn maLayout; + Size maDetailsCollapsedSize; + Size maDetailsExpandedSize; + Size getJobPageSize(); void updateNup(); void updateNupFromPages(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index f98dcdf0da2d..99b36e2b942a 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1953,14 +1953,31 @@ IMPL_LINK( PrintDialog, ClickHdl, Button*, pButton ) bool bShow = ! maJobPage.maStatusTxt.IsVisible(); maJobPage.maDetailsBtn.SetSymbol( bShow ? SYMBOL_SPIN_UP : SYMBOL_SPIN_DOWN ); maJobPage.mxDetails->show( bShow ); - // enlarge dialog if necessary - Size aMinSize( maJobPage.maLayout.getOptimalSize( WINDOWSIZE_MINIMUM ) ); - Size aCurSize( maJobPage.GetSizePixel() ); - if( aCurSize.Height() < aMinSize.Height() ) + if( bShow ) { + maDetailsCollapsedSize = GetOutputSizePixel(); + // enlarge dialog if necessary + Size aMinSize( maJobPage.maLayout.getOptimalSize( WINDOWSIZE_MINIMUM ) ); + Size aCurSize( maJobPage.GetSizePixel() ); + if( aCurSize.Height() < aMinSize.Height() ) + { + Size aDlgSize( GetOutputSizePixel() ); + aDlgSize.Height() += aMinSize.Height() - aCurSize.Height(); + SetOutputSizePixel( aDlgSize ); + } + maDetailsExpandedSize = GetOutputSizePixel(); + } + else if( maDetailsCollapsedSize.Width() > 0 && + maDetailsCollapsedSize.Height() > 0 ) + { + // if the user did not resize the dialog + // make it smaller again on collapsing the details Size aDlgSize( GetOutputSizePixel() ); - aDlgSize.Height() += aMinSize.Height() - aCurSize.Height(); - SetOutputSizePixel( aDlgSize ); + if( aDlgSize == maDetailsExpandedSize && + aDlgSize.Height() > maDetailsCollapsedSize.Height() ) + { + SetOutputSizePixel( maDetailsCollapsedSize ); + } } } else if( pButton == &maJobPage.maCollateBox ) -- cgit From 38287624c6dbe3d622a4e73e69db78a6412a6abd Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 16:36:29 +0000 Subject: #i104662# reverse page order affects sheets now instead of doc pages --- vcl/source/gdi/print3.cxx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index f8bf4aa6df80..2d8cb6f96f19 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -741,6 +741,13 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte if( nSubPages < 1 ) nSubPages = 1; + // reverse sheet order + if( mpImplData->mbReversePageOrder ) + { + int nDocPages = getFilteredPageCount(); + i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; + } + // there is no filtering to be done (and possibly the page size of the // original page is to be set), when N-Up is "neutral" that is there is // only one subpage and the margins are 0 @@ -748,11 +755,6 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte rMPS.nLeftMargin == 0 && rMPS.nRightMargin == 0 && rMPS.nTopMargin == 0 && rMPS.nBottomMargin == 0 ) { - if( mpImplData->mbReversePageOrder ) - { - int nDocPages = getPageCountProtected(); - i_nFilteredPage = nDocPages - 1 - i_nFilteredPage; - } PrinterController::PageSize aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); Size aPaperSize = mpImplData->getRealPaperSize( aPageSize.aSize ); if( aPaperSize != aPageSize.aSize ) @@ -802,9 +804,11 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte int nPage = (i_nFilteredPage * nSubPages + nSubPage) / rMPS.nRepeat; if( mpImplData->mbReversePageOrder ) { - nPage = nDocPages - 1 - nPage; - if( nPage == 0 ) + if( nSubPage == nSubPages-1 || + nPage == nDocPages-1 ) + { mpImplData->mbLastPage = bIsLastPage; + } } else { -- cgit From 27786389d04a4cbf24afc0abe9ed583cdd09d52f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 16:53:57 +0000 Subject: catch wrong page number in sfx --- vcl/aqua/source/gdi/salprn.cxx | 15 ++++++--------- vcl/source/gdi/print3.cxx | 3 +-- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 079629216df6..3bf229d1927f 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -651,17 +651,14 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, mnCurPageRangeCount = 1; } while( aAccViewState.bNeedRestart || mnCurPageRangeStart + mnCurPageRangeCount < nAllPages ); - // inform applictation that it can release its data + // inform application that it can release its data // this is awkward, but the XRenderable interface has no method for this, // so we need to call XRenderadble::render one last time with IsLastPage = TRUE - if( nAllPages > 0 ) - { - i_rController.setLastPage( sal_True ); - GDIMetaFile aPageFile; - if( mrContext ) - SetupPrinterGraphics( mrContext ); - i_rController.getFilteredPageFile( 0, aPageFile ); - } + i_rController.setLastPage( sal_True ); + GDIMetaFile aPageFile; + if( mrContext ) + SetupPrinterGraphics( mrContext ); + i_rController.getFilteredPageFile( 0, aPageFile ); i_rController.setJobState( bWasAborted ? view::PrintableState_JOB_ABORTED diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 2d8cb6f96f19..56da675f0030 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -365,8 +365,7 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr { GDIMetaFile aPageFile; i_pController->setLastPage( sal_True ); - if( i_pController->getPageCountProtected() > 0 ) - i_pController->getFilteredPageFile( 0, aPageFile ); + i_pController->getFilteredPageFile( 0, aPageFile ); return; } if( aDlg.isPrintToFile() ) -- cgit From 468bcdbd0b5fc182580dc30467f2d38df1c9b09f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 17:04:07 +0000 Subject: merge strings from string review --- vcl/source/src/print.src | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 8df7d33e2fed..f53d055c4dbe 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -110,7 +110,7 @@ ModalDialog SV_DLG_PRINT String SV_PRINT_TOFILE_TXT { - Text [en-US] = "Print to file..."; + Text [en-US] = "Print to File..."; }; String SV_PRINT_DEFPRT_TXT @@ -326,7 +326,7 @@ ModalDialog SV_DLG_PRINT { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 10, 10 ); - Text [en-US] = "Printer details"; + Text [en-US] = "Details"; }; FixedText SV_PRINT_STATUS_TXT { -- cgit From 3100b1dbb85dd3a5f1d41be0d03214592ad4fb7f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 19:48:08 +0000 Subject: themed disclosure button --- vcl/inc/vcl/button.hxx | 13 ++++++-- vcl/inc/vcl/prndlg.hxx | 3 +- vcl/inc/vcl/svdata.hxx | 5 +++ vcl/inc/vcl/svids.hrc | 6 +++- vcl/source/app/svmain.cxx | 20 ++++++++++++ vcl/source/control/button.cxx | 73 ++++++++++++++++++++++++++++++++++++++++++ vcl/source/src/images.src | 20 ++++++++++++ vcl/source/src/print.src | 9 ++---- vcl/source/window/printdlg.cxx | 15 +++------ 9 files changed, 141 insertions(+), 23 deletions(-) diff --git a/vcl/inc/vcl/button.hxx b/vcl/inc/vcl/button.hxx index 94df24a9cea7..05f21192e4c8 100644 --- a/vcl/inc/vcl/button.hxx +++ b/vcl/inc/vcl/button.hxx @@ -416,7 +416,6 @@ private: SAL_DLLPRIVATE void ImplInitCheckBoxData(); SAL_DLLPRIVATE WinBits ImplInitStyle( const Window* pPrevWindow, WinBits nStyle ); SAL_DLLPRIVATE void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground ); - SAL_DLLPRIVATE void ImplDrawCheckBoxState(); SAL_DLLPRIVATE void ImplInvalidateOrDrawCheckBoxState(); SAL_DLLPRIVATE void ImplDraw( OutputDevice* pDev, ULONG nDrawFlags, const Point& rPos, const Size& rSize, @@ -436,10 +435,11 @@ protected: SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId ); SAL_DLLPRIVATE virtual void FillLayoutData() const; + SAL_DLLPRIVATE virtual void ImplDrawCheckBoxState(); + SAL_DLLPRIVATE const Rectangle& GetStateRect() const { return maStateRect; } public: SAL_DLLPRIVATE void ImplCheck(); SAL_DLLPRIVATE void ImplSetMinimumNWFSize(); - public: CheckBox( Window* pParent, WinBits nStyle = 0 ); CheckBox( Window* pParent, const ResId& rResId ); @@ -538,4 +538,13 @@ public: ~TriStateBox(); }; +class VCL_DLLPUBLIC DisclosureButton : public CheckBox +{ +protected: + SAL_DLLPRIVATE virtual void ImplDrawCheckBoxState(); +public: + DisclosureButton( Window* pParent, WinBits nStyle = 0 ); + DisclosureButton( Window* pParent, const ResId& rResId ); +}; + #endif // _SV_BUTTON_HXX diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 3164de82fbeb..e905c0ecfe37 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -146,8 +146,7 @@ namespace vcl public: FixedLine maPrinterFL; ListBox maPrinters; - PushButton maDetailsBtn; - FixedText maDetailsTxt; + DisclosureButton maDetailsBtn; FixedText maStatusLabel; FixedText maStatusTxt; FixedText maLocationLabel; diff --git a/vcl/inc/vcl/svdata.hxx b/vcl/inc/vcl/svdata.hxx index bde902c3fbcd..de2ae32a71b2 100644 --- a/vcl/inc/vcl/svdata.hxx +++ b/vcl/inc/vcl/svdata.hxx @@ -86,6 +86,7 @@ class Timer; class AutoTimer; class Help; class ImageList; +class Image; class PopupMenu; class Application; class OutputDevice; @@ -247,6 +248,10 @@ struct ImplSVCtrlData ImageList* mpSplitVPinImgList; // ImageList for Vertikale SplitWindows (PIN's) ImageList* mpSplitHArwImgList; // ImageList for Horizontale SplitWindows (Arrows) ImageList* mpSplitVArwImgList; // ImageList for Vertikale SplitWindows (Arrows) + Image* mpDisclosurePlus; + Image* mpDisclosurePlusHC; + Image* mpDisclosureMinus; + Image* mpDisclosureMinusHC; ImplTBDragMgr* mpTBDragMgr; // DragMgr for ToolBox USHORT mnCheckStyle; // CheckBox-Style for ImageList-Update USHORT mnRadioStyle; // Radio-Style for ImageList-Update diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 1959a2df3152..c54dfb70c3ed 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -60,6 +60,11 @@ #define SV_RESID_BITMAP_CLOSEDOC 1052 #define SV_RESID_BITMAP_CLOSEDOCHC 1053 +#define SV_DISCLOSURE_PLUS 1060 +#define SV_DISCLOSURE_MINUS 1061 +#define SV_DISCLOSURE_PLUS_HC 1062 +#define SV_DISCLOSURE_MINUS_HC 1063 + #define SV_RESID_MENU_EDIT 2000 #define SV_MENU_EDIT_UNDO 1 #define SV_MENU_EDIT_CUT 2 @@ -146,7 +151,6 @@ #define SV_PRINT_LOCATION_TXT 21 #define SV_PRINT_COMMENT_TXT 22 #define SV_PRINT_DETAILS_BTN 23 -#define SV_PRINT_DETAILS_TXT 24 #define SV_PRINT_TAB_OPT 3 #define SV_PRINT_OPT_PRINT_FL 1 diff --git a/vcl/source/app/svmain.cxx b/vcl/source/app/svmain.cxx index 6c09978e37b1..b08198fb3acd 100644 --- a/vcl/source/app/svmain.cxx +++ b/vcl/source/app/svmain.cxx @@ -444,6 +444,26 @@ void DeInitVCL() delete pSVData->maCtrlData.mpSplitVArwImgList; pSVData->maCtrlData.mpSplitVArwImgList = NULL; } + if ( pSVData->maCtrlData.mpDisclosurePlus ) + { + delete pSVData->maCtrlData.mpDisclosurePlus; + pSVData->maCtrlData.mpDisclosurePlus = NULL; + } + if ( pSVData->maCtrlData.mpDisclosurePlusHC ) + { + delete pSVData->maCtrlData.mpDisclosurePlusHC; + pSVData->maCtrlData.mpDisclosurePlusHC = NULL; + } + if ( pSVData->maCtrlData.mpDisclosureMinus ) + { + delete pSVData->maCtrlData.mpDisclosureMinus; + pSVData->maCtrlData.mpDisclosureMinus = NULL; + } + if ( pSVData->maCtrlData.mpDisclosureMinusHC ) + { + delete pSVData->maCtrlData.mpDisclosureMinusHC; + pSVData->maCtrlData.mpDisclosureMinusHC = NULL; + } if ( pSVData->mpDefaultWin ) { delete pSVData->mpDefaultWin; diff --git a/vcl/source/control/button.cxx b/vcl/source/control/button.cxx index 852e7983ac06..605c84a11820 100644 --- a/vcl/source/control/button.cxx +++ b/vcl/source/control/button.cxx @@ -4389,3 +4389,76 @@ TriStateBox::TriStateBox( Window* pParent, const ResId& rResId ) : TriStateBox::~TriStateBox() { } + +// ======================================================================= + +DisclosureButton::DisclosureButton( Window* pParent, WinBits nStyle ) : + CheckBox( pParent, WB_NOBORDER ) +{ +} + +// ----------------------------------------------------------------------- + +DisclosureButton::DisclosureButton( Window* pParent, const ResId& rResId ) : + CheckBox( pParent, rResId.SetRT( RSC_CHECKBOX ) ) +{ +} + +// ----------------------------------------------------------------------- + +void DisclosureButton::ImplDrawCheckBoxState() +{ + /* HACK: DisclosureButton is currently assuming, that the disclosure sign + will fit into the rectangle occupied by a normal checkbox on all themes. + If this does not hold true for some theme, ImplGetCheckImageSize + would have to be overloaded for DisclosureButton; also GetNativeControlRegion + for CTRL_LISTNODE would have to be implemented and taken into account + */ + + Rectangle aStateRect( GetStateRect() ); + + ImplControlValue aControlValue( GetState() == STATE_CHECK ? BUTTONVALUE_ON : BUTTONVALUE_OFF, rtl::OUString(), 0 ); + Region aCtrlRegion( aStateRect ); + ControlState nState = 0; + + if ( HasFocus() ) nState |= CTRL_STATE_FOCUSED; + if ( ImplGetButtonState() & BUTTON_DRAW_DEFAULT ) nState |= CTRL_STATE_DEFAULT; + if ( Window::IsEnabled() ) nState |= CTRL_STATE_ENABLED; + if ( IsMouseOver() && aStateRect.IsInside( GetPointerPosPixel() ) ) + nState |= CTRL_STATE_ROLLOVER; + + if( ! DrawNativeControl( CTRL_LISTNODE, PART_ENTIRE_CONTROL, aCtrlRegion, nState, + aControlValue, rtl::OUString() ) ) + { + ImplSVCtrlData& rCtrlData( ImplGetSVData()->maCtrlData ); + if( ! rCtrlData.mpDisclosurePlus ) + rCtrlData.mpDisclosurePlus = new Image( BitmapEx( VclResId( SV_DISCLOSURE_PLUS ) ) ); + if( ! rCtrlData.mpDisclosurePlusHC ) + rCtrlData.mpDisclosurePlusHC = new Image( BitmapEx( VclResId( SV_DISCLOSURE_PLUS_HC ) ) ); + if( ! rCtrlData.mpDisclosureMinus ) + rCtrlData.mpDisclosureMinus = new Image( BitmapEx( VclResId( SV_DISCLOSURE_MINUS ) ) ); + if( ! rCtrlData.mpDisclosureMinusHC ) + rCtrlData.mpDisclosureMinusHC = new Image( BitmapEx( VclResId( SV_DISCLOSURE_MINUS_HC ) ) ); + + Image* pImg = NULL; + if( GetSettings().GetStyleSettings().GetHighContrastMode() ) + pImg = IsChecked() ? rCtrlData.mpDisclosureMinusHC : rCtrlData.mpDisclosurePlusHC; + else + pImg = IsChecked() ? rCtrlData.mpDisclosureMinus : rCtrlData.mpDisclosurePlus; + + DBG_ASSERT( pImg, "no disclosure image" ); + if( ! pImg ) + return; + + USHORT nStyle = 0; + if( ! IsEnabled() ) + nStyle |= IMAGE_DRAW_DISABLE; + + Size aSize( aStateRect.GetSize() ); + Size aImgSize( pImg->GetSizePixel() ); + Point aOff( (aSize.Width() - aImgSize.Width())/2, + (aSize.Height() - aImgSize.Height())/2 ); + aOff += aStateRect.TopLeft(); + DrawImage( aOff, *pImg, nStyle ); + } +} diff --git a/vcl/source/src/images.src b/vcl/source/src/images.src index a2b057c8d234..5a0e7b412a58 100644 --- a/vcl/source/src/images.src +++ b/vcl/source/src/images.src @@ -833,3 +833,23 @@ Bitmap (SV_ICON_SMALL_HC_START + SV_ICON_ID_PRINTERADMIN) File = "printeradmin_16_h.png" ; }; +Bitmap SV_DISCLOSURE_PLUS +{ + File = "plus.png"; +}; + +Bitmap SV_DISCLOSURE_PLUS_HC +{ + File = "plus_sch.png"; +}; + +Bitmap SV_DISCLOSURE_MINUS +{ + File = "minus.png"; +}; + +Bitmap SV_DISCLOSURE_MINUS_HC +{ + File = "minus_sch.png"; +}; + diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index f53d055c4dbe..24c49bd6c80a 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -316,17 +316,12 @@ ModalDialog SV_DLG_PRINT Border = TRUE; HelpText [en-US] = "Select the printer to print on."; }; - PushButton SV_PRINT_DETAILS_BTN + CheckBox SV_PRINT_DETAILS_BTN { Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 5, 5 ); - HelpText [en-US] = "Show/Hide detailed information of the selected printer."; - }; - FixedText SV_PRINT_DETAILS_TXT - { - Pos = MAP_APPFONT( 5, 5 ); - Size = MAP_APPFONT( 10, 10 ); Text [en-US] = "Details"; + HelpText [en-US] = "Show/Hide detailed information of the selected printer."; }; FixedText SV_PRINT_STATUS_TXT { diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 99b36e2b942a..708ee35a5755 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -454,7 +454,6 @@ PrintDialog::JobTabPage::JobTabPage( Window* i_pParent, const ResId& rResId ) , maPrinterFL( this, VclResId( SV_PRINT_PRINTERS_FL ) ) , maPrinters( this, VclResId( SV_PRINT_PRINTERS ) ) , maDetailsBtn( this, VclResId( SV_PRINT_DETAILS_BTN ) ) - , maDetailsTxt( this, VclResId( SV_PRINT_DETAILS_TXT ) ) , maStatusLabel( this, VclResId( SV_PRINT_STATUS_TXT ) ) , maStatusTxt( this, 0 ) , maLocationLabel( this, VclResId( SV_PRINT_LOCATION_TXT ) ) @@ -526,10 +525,7 @@ void PrintDialog::JobTabPage::setupLayout() // create a row for details button/text and properties button boost::shared_ptr< vcl::RowOrColumn > xDetRow( new vcl::RowOrColumn( &maLayout, false ) ); maLayout.addChild( xDetRow ); - boost::shared_ptr< vcl::LabeledElement > xDetLbl( new vcl::LabeledElement( xDetRow.get() ) ); - xDetRow->addChild( xDetLbl ); - xDetLbl->setLabel( &maDetailsBtn ); - xDetLbl->setElement( &maDetailsTxt ); + xDetRow->addWindow( &maDetailsBtn ); xDetRow->addChild( new vcl::Spacer( xDetRow.get(), 2 ) ); xDetRow->addWindow( &maSetupButton ); @@ -568,9 +564,7 @@ void PrintDialog::JobTabPage::setupLayout() xCollateRow->setLabel( &maCollateBox ); xCollateRow->setElement( &maCollateImage ); - maDetailsBtn.SetSymbol( SYMBOL_SPIN_DOWN ); - maDetailsBtn.SetSmallSymbol(); - maDetailsBtn.SetStyle( maDetailsBtn.GetStyle() | (WB_SMALLSTYLE | WB_BEVELBUTTON) ); + // maDetailsBtn.SetStyle( maDetailsBtn.GetStyle() | (WB_SMALLSTYLE | WB_BEVELBUTTON) ); mxDetails->show( false, false ); } @@ -796,7 +790,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptrshow( bShow ); if( bShow ) { -- cgit From a2224ea9eb1e05f1317f6ea3529f1653d00bd2b9 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 8 Sep 2009 20:01:56 +0000 Subject: fix warning --- vcl/source/control/button.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/source/control/button.cxx b/vcl/source/control/button.cxx index 605c84a11820..23235e14f448 100644 --- a/vcl/source/control/button.cxx +++ b/vcl/source/control/button.cxx @@ -4392,7 +4392,7 @@ TriStateBox::~TriStateBox() // ======================================================================= -DisclosureButton::DisclosureButton( Window* pParent, WinBits nStyle ) : +DisclosureButton::DisclosureButton( Window* pParent, WinBits ) : CheckBox( pParent, WB_NOBORDER ) { } -- cgit From 25f26445ab686fbbb064e620ebee39950a7fdc43 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 10 Sep 2009 14:34:56 +0000 Subject: #i104932# take page offset into account in N-Up printing --- vcl/source/gdi/print3.cxx | 6 ++++-- vcl/source/window/printdlg.cxx | 12 ++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 56da675f0030..c08abea15c7f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -776,7 +776,8 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte mpImplData->mbLastPage = sal_False; Size aPaperSize( mpImplData->getRealPaperSize( mpImplData->maMultiPage.aPaperSize ) ); - // multi page area: paper size minus margins + one time spacing right and down + + // multi page area: page size minus margins + one time spacing right and down // the added spacing is so each subpage can be calculated including its spacing Size aMPArea( aPaperSize ); aMPArea.Width() -= rMPS.nLeftMargin + rMPS.nRightMargin; @@ -858,10 +859,11 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte } o_rMtf.WindStart(); + // subsequent getPageFile calls have changed the paper, reset it to current value mpImplData->mpPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize, ! mpImplData->isFixedPageSize() ); - return PrinterController::PageSize( aPaperSize ); + return PrinterController::PageSize( aPaperSize, true ); } int PrinterController::getFilteredPageCount() diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 708ee35a5755..c6ac00eba9e5 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -1678,10 +1678,18 @@ void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) { const MapMode aMapMode( MAP_100TH_MM ); GDIMetaFile aMtf; + boost::shared_ptr aPrt( maPController->getPrinter() ); if( nPages > 0 ) - maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); + { + PrinterController::PageSize aPageSize = + maPController->getFilteredPageFile( mnCurPage, aMtf, i_bMayUseCache ); + if( ! aPageSize.bFullPaper ) + { + Point aOff( aPrt->PixelToLogic( aPrt->GetPageOffsetPixel(), aMapMode ) ); + aMtf.Move( aOff.X(), aOff.Y() ); + } + } - boost::shared_ptr aPrt( maPController->getPrinter() ); Size aCurPageSize = aPrt->PixelToLogic( aPrt->GetPaperSizePixel(), MapMode( MAP_100TH_MM ) ); maPreviewWindow.setPreview( aMtf, aCurPageSize, nPages > 0 ? rtl::OUString() : maNoPageStr, aPrt->ImplGetDPIX(), aPrt->ImplGetDPIY() -- cgit From 3aeb0fc95cf16c28c75095cfe5e720afb786e781 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Sat, 12 Sep 2009 11:22:22 +0000 Subject: solve problems with transparency and N-Up --- vcl/inc/vcl/outdev.hxx | 2 ++ vcl/inc/vcl/print.hxx | 2 ++ vcl/source/gdi/print2.cxx | 13 +++++++++--- vcl/source/gdi/print3.cxx | 50 ++++++++++++++++++++++++++--------------------- 4 files changed, 42 insertions(+), 25 deletions(-) diff --git a/vcl/inc/vcl/outdev.hxx b/vcl/inc/vcl/outdev.hxx index f4e42846dd5e..6791afc5cff9 100644 --- a/vcl/inc/vcl/outdev.hxx +++ b/vcl/inc/vcl/outdev.hxx @@ -1136,6 +1136,8 @@ public: false: output metafile is unchanged input metafile @attention this is a member method, so current state can influence the result ! + @attention the output metafile is prepared in pixel mode for the currentOutputDevice + state. It can not be moved or rotated reliably anymore. */ bool RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, GDIMetaFile& rOutMtf, long nMaxBmpDPIX, long nMaxBmpDPIY, diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index fe906988de2c..563a603f1917 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -518,6 +518,8 @@ public: SAL_DLLPRIVATE int getPageCountProtected() const; SAL_DLLPRIVATE com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getPageParametersProtected( int i_nPage ) const; + + SAL_DLLPRIVATE ULONG removeTransparencies( GDIMetaFile& i_rIn, GDIMetaFile& o_rOut ); }; class VCL_DLLPUBLIC PrinterOptionsHelper diff --git a/vcl/source/gdi/print2.cxx b/vcl/source/gdi/print2.cxx index 21c6b59f53a4..4e2e78efe9e2 100644 --- a/vcl/source/gdi/print2.cxx +++ b/vcl/source/gdi/print2.cxx @@ -1108,7 +1108,7 @@ bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, // ==================================================== // - Point aTmpPoint; + Point aPageOffset; Size aTmpSize( GetOutputSizePixel() ); if( mpPDFWriter ) { @@ -1118,7 +1118,14 @@ bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, // also add error code to PDFWriter mpPDFWriter->insertError( vcl::PDFWriter::Warning_Transparency_Converted ); } - const Rectangle aOutputRect( aTmpPoint, aTmpSize ); + else if( meOutDevType == OUTDEV_PRINTER ) + { + Printer* pThis = dynamic_cast(this); + aPageOffset = pThis->GetPageOffsetPixel(); + aPageOffset = Point( 0, 0 ) - aPageOffset; + aTmpSize = pThis->GetPaperSizePixel(); + } + const Rectangle aOutputRect( aPageOffset, aTmpSize ); bool bTiling = dynamic_cast(this) != NULL; // iterate over all aCCList members and generate bitmaps for the special ones @@ -1226,7 +1233,7 @@ bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, pCurrAct->Execute( &aPaintVDev ); } - if( !( nActionNum % 4 ) ) + if( !( nActionNum % 8 ) ) Application::Reschedule(); } diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index c08abea15c7f..23b2f04272a4 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -874,24 +874,8 @@ int PrinterController::getFilteredPageCount() return (getPageCountProtected() * mpImplData->maMultiPage.nRepeat + (nDiv-1)) / nDiv; } -void PrinterController::printFilteredPage( int i_nPage ) +ULONG PrinterController::removeTransparencies( GDIMetaFile& i_rIn, GDIMetaFile& o_rOut ) { - if( mpImplData->meJobState != view::PrintableState_JOB_STARTED ) - return; - - GDIMetaFile aPageFile; - PrinterController::PageSize aPageSize = getFilteredPageFile( i_nPage, aPageFile ); - - if( mpImplData->mpProgress ) - { - // do nothing if printing is canceled - if( mpImplData->mpProgress->isCanceled() ) - { - setJobState( view::PrintableState_JOB_ABORTED ); - return; - } - } - ULONG nRestoreDrawMode = mpImplData->mpPrinter->GetDrawMode(); sal_Int32 nMaxBmpDPIX = mpImplData->mpPrinter->ImplGetDPIX(); sal_Int32 nMaxBmpDPIY = mpImplData->mpPrinter->ImplGetDPIY(); @@ -936,14 +920,31 @@ void PrinterController::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->SetDrawMode( mpImplData->mpPrinter->GetDrawMode() | DRAWMODE_NOTRANSPARENCY ); } - GDIMetaFile aCleanedFile; - mpImplData->mpPrinter->RemoveTransparenciesFromMetaFile( aPageFile, aCleanedFile, nMaxBmpDPIX, nMaxBmpDPIY, + mpImplData->mpPrinter->RemoveTransparenciesFromMetaFile( i_rIn, o_rOut, nMaxBmpDPIX, nMaxBmpDPIY, rPrinterOptions.IsReduceTransparency(), rPrinterOptions.GetReducedTransparencyMode() == PRINTER_TRANSPARENCY_AUTO, rPrinterOptions.IsReduceBitmaps() && rPrinterOptions.IsReducedBitmapIncludesTransparency() ); + return nRestoreDrawMode; +} - mpImplData->mpPrinter->EnableOutput( TRUE ); +void PrinterController::printFilteredPage( int i_nPage ) +{ + if( mpImplData->meJobState != view::PrintableState_JOB_STARTED ) + return; + + GDIMetaFile aPageFile; + PrinterController::PageSize aPageSize = getFilteredPageFile( i_nPage, aPageFile ); + + if( mpImplData->mpProgress ) + { + // do nothing if printing is canceled + if( mpImplData->mpProgress->isCanceled() ) + { + setJobState( view::PrintableState_JOB_ABORTED ); + return; + } + } // in N-Up printing set the correct page size mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); @@ -953,10 +954,15 @@ void PrinterController::printFilteredPage( int i_nPage ) if( aPageSize.bFullPaper ) { Point aPageOffset( mpImplData->mpPrinter->GetPageOffset() ); - aCleanedFile.WindStart(); - aCleanedFile.Move( -aPageOffset.X(), -aPageOffset.Y() ); + aPageFile.WindStart(); + aPageFile.Move( -aPageOffset.X(), -aPageOffset.Y() ); } + GDIMetaFile aCleanedFile; + ULONG nRestoreDrawMode = removeTransparencies( aPageFile, aCleanedFile ); + + mpImplData->mpPrinter->EnableOutput( TRUE ); + // actually print the page mpImplData->mpPrinter->ImplStartPage(); -- cgit From 8a793295f4eb6530ac55654353de1ac1a33dd170 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 14 Sep 2009 16:02:43 +0000 Subject: #i104933# enhance RemoveTransparenciesFromMetafile for N-Up printing --- vcl/inc/vcl/outdev.hxx | 3 ++- vcl/source/gdi/print2.cxx | 20 ++++++++++++++++++-- vcl/source/gdi/print3.cxx | 12 +++++++++++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/outdev.hxx b/vcl/inc/vcl/outdev.hxx index 6791afc5cff9..2d4b52c5ee7e 100644 --- a/vcl/inc/vcl/outdev.hxx +++ b/vcl/inc/vcl/outdev.hxx @@ -1143,7 +1143,8 @@ public: long nMaxBmpDPIX, long nMaxBmpDPIY, bool bReduceTransparency, bool bTransparencyAutoMode, - bool bDownsampleBitmaps + bool bDownsampleBitmaps, + const Color& rBackground = Color( COL_TRANSPARENT ) ); /** Retrieve downsampled and cropped bitmap diff --git a/vcl/source/gdi/print2.cxx b/vcl/source/gdi/print2.cxx index 4e2e78efe9e2..9d435af5f4b1 100644 --- a/vcl/source/gdi/print2.cxx +++ b/vcl/source/gdi/print2.cxx @@ -646,7 +646,9 @@ static bool ImplIsActionHandlingTransparency( const MetaAction& rAct ) bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, GDIMetaFile& rOutMtf, long nMaxBmpDPIX, long nMaxBmpDPIY, bool bReduceTransparency, bool bTransparencyAutoMode, - bool bDownsampleBitmaps ) + bool bDownsampleBitmaps, + const Color& rBackground + ) { MetaAction* pCurrAct; bool bTransparent( false ); @@ -735,6 +737,20 @@ bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, bool bStillBackground=true; // true until first non-bg action nActionNum=0; nLastBgAction=-1; pCurrAct=const_cast(rInMtf).FirstAction(); + if( rBackground != Color( COL_TRANSPARENT ) ) + { + aBackgroundComponent.aBgColor = rBackground; + if( meOutDevType == OUTDEV_PRINTER ) + { + Printer* pThis = dynamic_cast(this); + Point aPageOffset = pThis->GetPageOffsetPixel(); + aPageOffset = Point( 0, 0 ) - aPageOffset; + Size aSize = pThis->GetPaperSizePixel(); + aBackgroundComponent.aBounds = Rectangle( aPageOffset, aSize ); + } + else + aBackgroundComponent.aBounds = Rectangle( Point( 0, 0 ), GetOutputSizePixel() ); + } while( pCurrAct && bStillBackground ) { switch( pCurrAct->GetType() ) @@ -878,7 +894,7 @@ bool OutputDevice::RemoveTransparenciesFromMetaFile( const GDIMetaFile& rInMtf, // // if aBBCurrAct is empty, it will intersect with no - // aCCList member. Thus, we can safe us the check. + // aCCList member. Thus, we can save the check. // Furthermore, this ensures that non-output-generating // actions get their own aCCList entry, which is necessary // when copying them to the output metafile (see stage 4 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 23b2f04272a4..5aab3fe87acf 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -920,10 +920,19 @@ ULONG PrinterController::removeTransparencies( GDIMetaFile& i_rIn, GDIMetaFile& mpImplData->mpPrinter->SetDrawMode( mpImplData->mpPrinter->GetDrawMode() | DRAWMODE_NOTRANSPARENCY ); } + Color aBg( COL_TRANSPARENT ); // default: let RemoveTransparenciesFromMetaFile do its own background logic + if( mpImplData->maMultiPage.nRows * mpImplData->maMultiPage.nColumns > 1 ) + { + // in N-Up printing we have no "page" background operation + // we also have no way to determine the paper color + // so let's go for white, which will kill 99.9% of the real cases + aBg = Color( COL_WHITE ); + } mpImplData->mpPrinter->RemoveTransparenciesFromMetaFile( i_rIn, o_rOut, nMaxBmpDPIX, nMaxBmpDPIY, rPrinterOptions.IsReduceTransparency(), rPrinterOptions.GetReducedTransparencyMode() == PRINTER_TRANSPARENCY_AUTO, - rPrinterOptions.IsReduceBitmaps() && rPrinterOptions.IsReducedBitmapIncludesTransparency() + rPrinterOptions.IsReduceBitmaps() && rPrinterOptions.IsReducedBitmapIncludesTransparency(), + aBg ); return nRestoreDrawMode; } @@ -950,6 +959,7 @@ void PrinterController::printFilteredPage( int i_nPage ) mpImplData->mpPrinter->SetMapMode( MAP_100TH_MM ); // aPageSize was filtered through mpImplData->getRealPaperSize already by getFilteredPageFile() mpImplData->mpPrinter->SetPaperSizeUser( aPageSize.aSize, ! mpImplData->isFixedPageSize() ); + // if full paper are is meant, move the output to accomodate for pageoffset if( aPageSize.bFullPaper ) { -- cgit From 2589f7adbf0066980b8da68355c2d48369465764 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 14 Sep 2009 17:23:44 +0000 Subject: #i104662# fix IsLastPage handling --- vcl/source/gdi/print3.cxx | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 5aab3fe87acf..98f6530d5b49 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -802,18 +802,10 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte { // map current sub page to real page int nPage = (i_nFilteredPage * nSubPages + nSubPage) / rMPS.nRepeat; - if( mpImplData->mbReversePageOrder ) + if( nSubPage == nSubPages-1 || + nPage == nDocPages-1 ) { - if( nSubPage == nSubPages-1 || - nPage == nDocPages-1 ) - { - mpImplData->mbLastPage = bIsLastPage; - } - } - else - { - if( nPage == nDocPages-1 ) - mpImplData->mbLastPage = bIsLastPage; + mpImplData->mbLastPage = bIsLastPage; } if( nPage >= 0 && nPage < nDocPages ) { -- cgit From 489990ac09074893be132200c181e0ac1cbe2817 Mon Sep 17 00:00:00 2001 From: Daniel Rentz Date: Tue, 13 Oct 2009 08:37:49 +0000 Subject: missing virtual dtor --- vcl/inc/vcl/vclevent.hxx | 1 + vcl/source/app/vclevent.cxx | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/vcl/inc/vcl/vclevent.hxx b/vcl/inc/vcl/vclevent.hxx index e519d194c2fa..40e840a3b14c 100644 --- a/vcl/inc/vcl/vclevent.hxx +++ b/vcl/inc/vcl/vclevent.hxx @@ -201,6 +201,7 @@ private: public: VclSimpleEvent( ULONG n ) { nId = n; } + virtual ~VclSimpleEvent(); TYPEINFO(); ULONG GetId() const { return nId; } diff --git a/vcl/source/app/vclevent.cxx b/vcl/source/app/vclevent.cxx index 721dd9fd0419..4c098752c259 100644 --- a/vcl/source/app/vclevent.cxx +++ b/vcl/source/app/vclevent.cxx @@ -43,6 +43,10 @@ TYPEINIT0(VclSimpleEvent); TYPEINIT1(VclWindowEvent, VclSimpleEvent); TYPEINIT1(VclMenuEvent, VclSimpleEvent); +VclSimpleEvent::~VclSimpleEvent() +{ +} + VclAccessibleEvent::VclAccessibleEvent( ULONG n, const Reference& rxAccessible ) : VclSimpleEvent(n), mxAccessible(rxAccessible) {} -- cgit From fd5ee55b7b9ca4ce23c88b66c75d04b178a21891 Mon Sep 17 00:00:00 2001 From: Daniel Rentz Date: Tue, 13 Oct 2009 09:38:17 +0000 Subject: missing virtual dtor --- vcl/inc/vcl/vclevent.hxx | 2 +- vcl/source/app/vclevent.cxx | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/vcl/inc/vcl/vclevent.hxx b/vcl/inc/vcl/vclevent.hxx index 40e840a3b14c..10c73dc37dda 100644 --- a/vcl/inc/vcl/vclevent.hxx +++ b/vcl/inc/vcl/vclevent.hxx @@ -201,7 +201,6 @@ private: public: VclSimpleEvent( ULONG n ) { nId = n; } - virtual ~VclSimpleEvent(); TYPEINFO(); ULONG GetId() const { return nId; } @@ -253,6 +252,7 @@ class VCL_DLLPUBLIC VclAccessibleEvent: public VclSimpleEvent { public: VclAccessibleEvent( ULONG n, const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& rxAccessible ); + virtual ~VclAccessibleEvent(); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetAccessible() const; private: diff --git a/vcl/source/app/vclevent.cxx b/vcl/source/app/vclevent.cxx index 4c098752c259..d8e7f37caf6a 100644 --- a/vcl/source/app/vclevent.cxx +++ b/vcl/source/app/vclevent.cxx @@ -43,13 +43,15 @@ TYPEINIT0(VclSimpleEvent); TYPEINIT1(VclWindowEvent, VclSimpleEvent); TYPEINIT1(VclMenuEvent, VclSimpleEvent); -VclSimpleEvent::~VclSimpleEvent() +VclAccessibleEvent::VclAccessibleEvent( ULONG n, const Reference& rxAccessible ) : + VclSimpleEvent(n), + mxAccessible(rxAccessible) { } -VclAccessibleEvent::VclAccessibleEvent( ULONG n, const Reference& rxAccessible ) : - VclSimpleEvent(n), - mxAccessible(rxAccessible) {} +VclAccessibleEvent::~VclAccessibleEvent() +{ +} Reference VclAccessibleEvent::GetAccessible() const { -- cgit From da090fbc35805969d00cef772108fa5be756d331 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 13 Oct 2009 12:39:07 +0200 Subject: #i65491# move first page features to document setup --- vcl/inc/vcl/printerjob.hxx | 2 +- vcl/unx/source/printergfx/printerjob.cxx | 45 ++++++++++++++++---------------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/vcl/inc/vcl/printerjob.hxx b/vcl/inc/vcl/printerjob.hxx index 9880700d4008..e445a81d54c8 100644 --- a/vcl/inc/vcl/printerjob.hxx +++ b/vcl/inc/vcl/printerjob.hxx @@ -91,7 +91,7 @@ private: // private methods bool writeFeatureList( osl::File* pFile, const JobData&, bool bDocumentSetup ); bool writeSetup( osl::File* pFile, const JobData& ); - bool writePageSetup( osl::File* pFile, const JobData& ); + bool writePageSetup( osl::File* pFile, const JobData&, bool bWriteFeatures = true ); void writeJobPatch( osl::File* File, const JobData& ); bool writeProlog (osl::File* pFile, const JobData& ); diff --git a/vcl/unx/source/printergfx/printerjob.cxx b/vcl/unx/source/printergfx/printerjob.cxx index 783dd5ff2b47..1c42cafa4cb9 100644 --- a/vcl/unx/source/printergfx/printerjob.cxx +++ b/vcl/unx/source/printergfx/printerjob.cxx @@ -681,14 +681,6 @@ PrinterJob::StartPage (const JobData& rJobSetup) if( ! (pPageHeader && pPageBody) ) return sal_False; - /* #i7262# write setup only before first page - * don't do this in StartJob since the jobsetup there may be - * different. - */ - bool bSuccess = true; - if( 1 == maPageList.size() ) - m_aDocumentJobData = rJobSetup; - // write page header according to Document Structuring Conventions (DSC) WritePS (pPageHeader, "%%Page: "); WritePS (pPageHeader, aPageNo); @@ -722,13 +714,25 @@ PrinterJob::StartPage (const JobData& rJobSetup) WritePS (pPageHeader, pBBox); - if (bSuccess) - bSuccess = writePageSetup ( pPageHeader, rJobSetup ); - if(bSuccess) - m_aLastJobData = rJobSetup; + /* #i7262# #i65491# write setup only before first page + * (to %%Begin(End)Setup, instead of %%Begin(End)PageSetup) + * don't do this in StartJob since the jobsetup there may be + * different. + */ + bool bWriteFeatures = true; + if( 1 == maPageList.size() ) + { + m_aDocumentJobData = rJobSetup; + bWriteFeatures = false; + } + if ( writePageSetup( pPageHeader, rJobSetup, bWriteFeatures ) ) + { + m_aLastJobData = rJobSetup; + return true; + } - return bSuccess; + return false; } sal_Bool @@ -828,12 +832,9 @@ bool PrinterJob::writeFeatureList( osl::File* pFile, const JobData& rJob, bool b if( pKey->getSetupType() == PPDKey::DocumentSetup ) bEmit = true; } - else - { - if( pKey->getSetupType() == PPDKey::PageSetup || - pKey->getSetupType() == PPDKey::AnySetup ) - bEmit = true; - } + if( pKey->getSetupType() == PPDKey::PageSetup || + pKey->getSetupType() == PPDKey::AnySetup ) + bEmit = true; if( bEmit ) { const PPDValue* pValue = rJob.m_aContext.getValue( pKey ); @@ -866,13 +867,13 @@ bool PrinterJob::writeFeatureList( osl::File* pFile, const JobData& rJob, bool b return bSuccess; } -bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob ) +bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob, bool bWriteFeatures ) { bool bSuccess = true; WritePS (pFile, "%%BeginPageSetup\n%\n"); - - bSuccess = writeFeatureList( pFile, rJob, false ); + if ( bWriteFeatures ) + bSuccess = writeFeatureList( pFile, rJob, false ); WritePS (pFile, "%%EndPageSetup\n"); sal_Char pTranslate [128]; -- cgit From 04ee83054bd6b805262d7e0feba400da13b0c303 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 13 Oct 2009 13:40:45 +0200 Subject: #i105822# leave printer in correct state in both cached and uncached case of getFilteredPageFile --- vcl/source/gdi/print3.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 98f6530d5b49..09728a5f5a14 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -756,6 +756,8 @@ PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilte { PrinterController::PageSize aPageSize = getPageFile( i_nFilteredPage, o_rMtf, i_bMayUseCache ); Size aPaperSize = mpImplData->getRealPaperSize( aPageSize.aSize ); + mpImplData->mpPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); + mpImplData->mpPrinter->SetPaperSizeUser( aPaperSize, ! mpImplData->isFixedPageSize() ); if( aPaperSize != aPageSize.aSize ) { // user overridden page size, center Metafile -- cgit From 8ec2ce18b769ea980fede28ef899a25f770c2f4d Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 15 Oct 2009 18:35:07 +0200 Subject: #i105731# sort printerlist --- vcl/source/src/print.src | 1 + 1 file changed, 1 insertion(+) diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 24c49bd6c80a..856ba88525fa 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -314,6 +314,7 @@ ModalDialog SV_DLG_PRINT Pos = MAP_APPFONT( 5, 5 ); Size = MAP_APPFONT( 100, 80 ); Border = TRUE; + Sort = TRUE; HelpText [en-US] = "Select the printer to print on."; }; CheckBox SV_PRINT_DETAILS_BTN -- cgit From a06a509c4d7e03ec4bddbd1595c4e135a3355a9b Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Mon, 19 Oct 2009 14:46:44 +0200 Subject: #i105729# for convenience allow to modify disabled dependencies thereby automatically changing the dependent value appropriately --- vcl/inc/vcl/print.hxx | 12 +++++ vcl/inc/vcl/prndlg.hxx | 6 ++- vcl/source/gdi/print3.cxx | 52 ++++++++++++++++++ vcl/source/window/printdlg.cxx | 119 ++++++++++++++++++++++++++++++++++++----- 4 files changed, 174 insertions(+), 15 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 563a603f1917..25ace16aea52 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -477,6 +477,18 @@ public: */ void enableUIOption( const rtl::OUString& rPropName, bool bEnable ); bool isUIOptionEnabled( const rtl::OUString& rPropName ) const; + /* returns the property name rPropName depends on or an empty string + if no dependency exists. + */ + rtl::OUString getDependency( const rtl::OUString& rPropName ) const; + /* makeEnabled will chage the property rPropName depends on to the value + that makes rPropName enabled. If the dependency itself is also disabled, + no action will be performed. + + returns the property name rPropName depends on or an empty string + if no change was made. + */ + rtl::OUString makeEnabled( const rtl::OUString& rPropName ); virtual int getPageCount() const = 0; // must be overloaded by the app /* get the page parameters, namely the jobsetup that should be active for the page diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index e905c0ecfe37..95dfef827b90 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -232,8 +232,10 @@ namespace vcl std::list< Window* > maControls; std::map< Window*, rtl::OUString > maControlToPropertyMap; - std::multimap< rtl::OUString, Window* > maPropertyToWindowMap; + std::map< rtl::OUString, std::vector< Window* > > + maPropertyToWindowMap; std::map< Window*, sal_Int32 > maControlToNumValMap; + std::set< rtl::OUString > maReverseDependencySet; Size maNupPortraitSize; Size maNupLandscapeSize; @@ -258,6 +260,8 @@ namespace vcl void updatePrinterText(); void checkControlDependencies(); void checkOptionalControlDependencies(); + void makeEnabled( Window* ); + void updateWindowFromProperty( const rtl::OUString& ); void setupOptionalUI(); void readFromSettings(); void storeToSettings(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 09728a5f5a14..6c56bba090ab 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1237,6 +1237,58 @@ bool PrinterController::isUIOptionEnabled( const rtl::OUString& i_rProperty ) co return bEnabled; } +rtl::OUString PrinterController::getDependency( const rtl::OUString& i_rProperty ) const +{ + rtl::OUString aDependency; + + vcl::ImplPrinterControllerData::ControlDependencyMap::const_iterator it = + mpImplData->maControlDependencies.find( i_rProperty ); + if( it != mpImplData->maControlDependencies.end() ) + aDependency = it->second.maDependsOnName; + + return aDependency; +} + +rtl::OUString PrinterController::makeEnabled( const rtl::OUString& i_rProperty ) +{ + rtl::OUString aDependency; + + vcl::ImplPrinterControllerData::ControlDependencyMap::const_iterator it = + mpImplData->maControlDependencies.find( i_rProperty ); + if( it != mpImplData->maControlDependencies.end() ) + { + if( isUIOptionEnabled( it->second.maDependsOnName ) ) + { + aDependency = it->second.maDependsOnName; + const com::sun::star::beans::PropertyValue* pVal = getValue( aDependency ); + OSL_ENSURE( pVal, "unknown property in dependency" ); + if( pVal ) + { + sal_Int32 nDepVal = 0; + sal_Bool bDepVal = sal_False; + if( pVal->Value >>= nDepVal ) + { + if( it->second.mnDependsOnEntry != -1 ) + { + setValue( aDependency, makeAny( sal_Int32( it->second.mnDependsOnEntry ) ) ); + } + } + else if( pVal->Value >>= bDepVal ) + { + setValue( aDependency, makeAny( sal_Bool( it->second.mnDependsOnEntry != 0 ) ) ); + } + else + { + // if the type does not match something is awry + OSL_ENSURE( 0, "strange type in control dependency" ); + } + } + } + } + + return aDependency; +} + void PrinterController::setOptionChangeHdl( const Link& i_rHdl ) { mpImplData->maOptionChangeHdl = i_rHdl; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index c6ac00eba9e5..d4fe42ce3edb 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -334,7 +334,7 @@ PrintDialog::NUpTabPage::~NUpTabPage() void PrintDialog::NUpTabPage::enableNupControls( bool bEnable ) { - maNupPagesBox.Enable( bEnable ); + maNupPagesBox.Enable( TRUE ); maNupNumPagesTxt.Enable( bEnable ); maNupColEdt.Enable( bEnable ); maNupTimesTxt.Enable( bEnable ); @@ -1114,6 +1114,9 @@ void PrintDialog::setupOptionalUI() } } + // bUseDependencyRow should only be true if a dependency exists + bUseDependencyRow = bUseDependencyRow && (aDependsOnName.getLength() != 0); + // is it necessary to switch between static and dynamic pages ? bool bSwitchPage = false; if( aGroupingHint.getLength() ) @@ -1236,7 +1239,7 @@ void PrintDialog::setupOptionalUI() maNUpPage.maBrochureBtn.Enable( maPController->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); maNUpPage.maBrochureBtn.SetToggleHdl( LINK( this, PrintDialog, ClickHdl ) ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, &maNUpPage.maBrochureBtn ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( &maNUpPage.maBrochureBtn ); maControlToPropertyMap[&maNUpPage.maBrochureBtn] = aPropertyName; aPropertyToDependencyRowMap.insert( std::pair< rtl::OUString, vcl::RowOrColumn* >( aPropertyName, maNUpPage.mxBrochureDep.get() ) ); @@ -1245,7 +1248,7 @@ void PrintDialog::setupOptionalUI() { vcl::RowOrColumn* pSaveCurColumn = pCurColumn; - if( bUseDependencyRow && aDependsOnName.getLength() ) + if( bUseDependencyRow ) { // find the correct dependency row (if any) std::pair< std::multimap< rtl::OUString, vcl::RowOrColumn* >::iterator, @@ -1261,6 +1264,7 @@ void PrintDialog::setupOptionalUI() if( aDepRange.first != aPropertyToDependencyRowMap.end() ) { pCurColumn = aDepRange.first->second; + maReverseDependencySet.insert( aPropertyName ); } } } @@ -1277,10 +1281,9 @@ void PrintDialog::setupOptionalUI() if( pVal ) pVal->Value >>= bVal; pNewBox->Check( bVal ); - pNewBox->Enable( maPController->isUIOptionEnabled( aPropertyName ) && pVal != NULL ); pNewBox->SetToggleHdl( LINK( this, PrintDialog, UIOption_CheckHdl ) ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pNewBox ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( pNewBox ); maControlToPropertyMap[pNewBox] = aPropertyName; // set help id @@ -1336,10 +1339,9 @@ void PrintDialog::setupOptionalUI() maControls.push_front( pBtn ); pBtn->SetText( aChoices[m] ); pBtn->Check( m == nSelectVal ); - pBtn->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pBtn->SetToggleHdl( LINK( this, PrintDialog, UIOption_RadioHdl ) ); pBtn->Show(); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pBtn ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( pBtn ); maControlToPropertyMap[pBtn] = aPropertyName; maControlToNumValMap[pBtn] = m; @@ -1394,7 +1396,6 @@ void PrintDialog::setupOptionalUI() if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nSelectVal; pList->SelectEntryPos( static_cast(nSelectVal) ); - pList->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pList->SetSelectHdl( LINK( this, PrintDialog, UIOption_SelectHdl ) ); pList->SetDropDownLineCount( static_cast(aChoices.getLength()) ); pList->Show(); @@ -1404,7 +1405,7 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pList, aHelpTexts, 0 ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pList ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( pList ); maControlToPropertyMap[pList] = aPropertyName; // finish the pair @@ -1429,8 +1430,6 @@ void PrintDialog::setupOptionalUI() if( pVal && pVal->Value.hasValue() ) pVal->Value >>= nCurVal; pField->SetValue( nCurVal ); - - pField->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -1439,7 +1438,7 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pField, aHelpTexts, 0 ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( pField ); maControlToPropertyMap[pField] = aPropertyName; // add to row @@ -1458,7 +1457,6 @@ void PrintDialog::setupOptionalUI() if( pVal && pVal->Value.hasValue() ) pVal->Value >>= aCurVal; pField->SetText( aCurVal ); - pField->Enable( maPController->isUIOptionEnabled( aPropertyName ) ); pField->SetModifyHdl( LINK( this, PrintDialog, UIOption_ModifyHdl ) ); pField->Show(); @@ -1467,7 +1465,7 @@ void PrintDialog::setupOptionalUI() // set help text setHelpText( pField, aHelpTexts, 0 ); - maPropertyToWindowMap.insert( std::pair< rtl::OUString, Window* >( aPropertyName, pField ) ); + maPropertyToWindowMap[ aPropertyName ].push_back( pField ); maControlToPropertyMap[pField] = aPropertyName; // add to row @@ -1486,6 +1484,9 @@ void PrintDialog::setupOptionalUI() } } + // update enable states + checkOptionalControlDependencies(); + // print range empty (currently math only) -> hide print range and spacer line if( maJobPage.mxPrintRange->countElements() == 0 ) { @@ -1608,6 +1609,24 @@ void PrintDialog::checkOptionalControlDependencies() it != maControlToPropertyMap.end(); ++it ) { bool bShouldbeEnabled = maPController->isUIOptionEnabled( it->second ); + if( ! bShouldbeEnabled ) + { + // enable controls that are directly attached to a dependency anyway + // if the normally disabled controls get modified, change the dependency + // so the control would be enabled + // example: in print range "Print All" is selected, "Page Range" is then of course + // not selected and the Edit for the Page Range would be disabled + // as a convenience we should enable the Edit anyway and automatically select + // "Page Range" instead of "Print All" if the Edit gets modified + if( maReverseDependencySet.find( it->second ) != maReverseDependencySet.end() ) + { + rtl::OUString aDep( maPController->getDependency( it->second ) ); + // if the dependency is at least enabled, then enable this control anyway + if( aDep.getLength() && maPController->isUIOptionEnabled( aDep ) ) + bShouldbeEnabled = true; + } + } + bool bIsEnabled = it->first->IsEnabled(); // Enable does not do a change check first, so can be less cheap than expected if( bShouldbeEnabled != bIsEnabled ) @@ -1888,6 +1907,8 @@ IMPL_LINK( PrintDialog, SelectHdl, ListBox*, pBox ) } else if( pBox == &maNUpPage.maNupPagesBox ) { + if( !maNUpPage.maPagesBtn.IsChecked() ) + maNUpPage.maPagesBtn.Check(); updateNupFromPages(); } @@ -2057,11 +2078,76 @@ PropertyValue* PrintDialog::getValueForWindow( Window* i_pWindow ) const return pVal; } +void PrintDialog::updateWindowFromProperty( const rtl::OUString& i_rProperty ) +{ + beans::PropertyValue* pValue = maPController->getValue( i_rProperty ); + std::map< rtl::OUString, std::vector< Window* > >::const_iterator it = maPropertyToWindowMap.find( i_rProperty ); + if( pValue && it != maPropertyToWindowMap.end() ) + { + const std::vector< Window* >& rWindows( it->second ); + if( ! rWindows.empty() ) + { + sal_Bool bVal = sal_False; + sal_Int32 nVal = -1; + if( pValue->Value >>= bVal ) + { + // we should have a CheckBox for this one + CheckBox* pBox = dynamic_cast< CheckBox* >( rWindows.front() ); + if( pBox ) + { + pBox->Check( bVal ); + } + else if( i_rProperty.equalsAscii( "PrintProspect" ) ) + { + // EVIL special case + if( bVal ) + maNUpPage.maBrochureBtn.Check(); + else + maNUpPage.maPagesBtn.Check(); + } + else + { + DBG_ASSERT( 0, "missing a checkbox" ); + } + } + else if( pValue->Value >>= nVal ) + { + // this could be a ListBox or a RadioButtonGroup + ListBox* pList = dynamic_cast< ListBox* >( rWindows.front() ); + if( pList ) + { + pList->SelectEntryPos( static_cast< USHORT >(nVal) ); + } + else if( nVal >= 0 && nVal < sal_Int32(rWindows.size() ) ) + { + RadioButton* pBtn = dynamic_cast< RadioButton* >( rWindows[nVal] ); + DBG_ASSERT( pBtn, "unexpected control for property" ); + if( pBtn ) + pBtn->Check(); + } + } + } + } +} + +void PrintDialog::makeEnabled( Window* i_pWindow ) +{ + std::map< Window*, rtl::OUString >::const_iterator it = maControlToPropertyMap.find( i_pWindow ); + if( it != maControlToPropertyMap.end() ) + { + rtl::OUString aDependency( maPController->makeEnabled( it->second ) ); + if( aDependency.getLength() ) + updateWindowFromProperty( aDependency ); + } +} + IMPL_LINK( PrintDialog, UIOption_CheckHdl, CheckBox*, i_pBox ) { PropertyValue* pVal = getValueForWindow( i_pBox ); if( pVal ) { + makeEnabled( i_pBox ); + sal_Bool bVal = i_pBox->IsChecked(); pVal->Value <<= bVal; @@ -2084,6 +2170,7 @@ IMPL_LINK( PrintDialog, UIOption_RadioHdl, RadioButton*, i_pBtn ) std::map< Window*, sal_Int32 >::const_iterator it = maControlToNumValMap.find( i_pBtn ); if( pVal && it != maControlToNumValMap.end() ) { + makeEnabled( i_pBtn ); sal_Int32 nVal = it->second; pVal->Value <<= nVal; @@ -2102,6 +2189,8 @@ IMPL_LINK( PrintDialog, UIOption_SelectHdl, ListBox*, i_pBox ) PropertyValue* pVal = getValueForWindow( i_pBox ); if( pVal ) { + makeEnabled( i_pBox ); + sal_Int32 nVal( i_pBox->GetSelectEntryPos() ); pVal->Value <<= nVal; @@ -2118,6 +2207,8 @@ IMPL_LINK( PrintDialog, UIOption_ModifyHdl, Edit*, i_pBox ) PropertyValue* pVal = getValueForWindow( i_pBox ); if( pVal ) { + makeEnabled( i_pBox ); + NumericField* pNum = dynamic_cast(i_pBox); MetricField* pMetric = dynamic_cast(i_pBox); if( pNum ) -- cgit From b14f33317528b0d3b44f5d24fbfb15a26cebb531 Mon Sep 17 00:00:00 2001 From: Frank Schönheit Date: Fri, 23 Oct 2009 12:10:07 +0200 Subject: #i106184# introduce a 'VerticalAlign' property for edit-like form controls --- svtools/source/control/filectrl.cxx | 3 ++ svtools/source/uno/unoiface.cxx | 80 ---------------------------- toolkit/source/awt/vclxwindows.cxx | 6 +++ toolkit/source/controls/formattedcontrol.cxx | 1 + toolkit/source/controls/unocontrols.cxx | 2 + vcl/inc/vcl/edit.hxx | 1 + vcl/source/control/edit.cxx | 21 +++++--- 7 files changed, 28 insertions(+), 86 deletions(-) diff --git a/svtools/source/control/filectrl.cxx b/svtools/source/control/filectrl.cxx index d820dce097ed..f00cf45be0e6 100644 --- a/svtools/source/control/filectrl.cxx +++ b/svtools/source/control/filectrl.cxx @@ -78,6 +78,9 @@ WinBits FileControl::ImplInitStyle( WinBits nStyle ) maButton.SetStyle( (maButton.GetStyle()|WB_NOTABSTOP)&(~WB_TABSTOP) ); } + const WinBits nAlignmentStyle = ( WB_TOP | WB_VCENTER | WB_BOTTOM ); + maEdit.SetStyle( ( maEdit.GetStyle() & ~nAlignmentStyle ) | ( nStyle & nAlignmentStyle ) ); + if ( !(nStyle & WB_NOGROUP) ) nStyle |= WB_GROUP; diff --git a/svtools/source/uno/unoiface.cxx b/svtools/source/uno/unoiface.cxx index 54cc448ff89e..b4772f755452 100644 --- a/svtools/source/uno/unoiface.cxx +++ b/svtools/source/uno/unoiface.cxx @@ -551,86 +551,6 @@ void VCLXMultiLineEdit::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) VCLXWindow::ImplGetPropertyIds( rIds, true ); } -// ---------------------------------------------------- -// class VCLXFileDialog -// ---------------------------------------------------- -/* -VCLXFileDialog::VCLXFileDialog() -{ -} - -VCLXFileDialog::~VCLXFileDialog() -{ -} - -::com::sun::star::uno::Any VCLXFileDialog::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) -{ - ::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType, - SAL_STATIC_CAST( ::com::sun::star::awt::XXX*, this ) ); - return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); -} - -// ::com::sun::star::lang::XTypeProvider -IMPL_XTYPEPROVIDER_START( VCLXFileDialog ) - getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XXX>* ) NULL ) -IMPL_XTYPEPROVIDER_END - -void VCLXFileDialog::setPath( const ::rtl::OUString& rPath ) -{ - ::vos::OGuard aGuard( GetMutex() ); - - FileDialog* pDlg = (FileDialog*)GetWindow(); - if ( pDlg ) - pDlg->SetPath( ::rtl::OUStringToOString( rPath, CHARSET_SYSTEM ) ); -} - -::rtl::OUString VCLXFileDialog::getPath() -{ - ::vos::OGuard aGuard( GetMutex() ); - - ::rtl::OUString aPath; - FileDialog* pDlg = (FileDialog*)GetWindow(); - if ( pDlg ) - aPath = StringToOUString( pDlg->GetPath(), CHARSET_SYSTEM ); - return aPath; -} - -void VCLXFileDialog::setFilters( const ::com::sun::star::uno::Sequence< ::rtl::OUString>& rFilterNames, const ::com::sun::star::uno::Sequence< ::rtl::OUString>& rMasks ) -{ - ::vos::OGuard aGuard( GetMutex() ); - - FileDialog* pDlg = (FileDialog*)GetWindow(); - if ( pDlg ) - { - sal_uInt32 nFlts = rFilterNames.getLength(); - for ( sal_uInt32 n = 0; n < nFlts; n++ ) - pDlg->AddFilter( - ::rtl::OUStringToOString( rFilterNames.getConstArray()[n], CHARSET_SYSTEM ), - ::rtl::OUStringToOString( rMasks.getConstArray()[n], CHARSET_SYSTEM ) ); - } -} - -void VCLXFileDialog::setCurrentFilter( const ::rtl::OUString& rFilterName ) -{ - ::vos::OGuard aGuard( GetMutex() ); - - FileDialog* pDlg = (FileDialog*)GetWindow(); - if ( pDlg ) - pDlg->SetCurFilter( ::rtl::OUStringToOString( rFilterName, CHARSET_SYSTEM ) ); -} - -::rtl::OUString VCLXFileDialog::getCurrentFilter() -{ - ::vos::OGuard aGuard( GetMutex() ); - - ::rtl::OUString aFilter; - FileDialog* pDlg = (FileDialog*)GetWindow(); - if ( pDlg ) - aFilter = StringToOUString( pDlg->GetCurFilter(), CHARSET_SYSTEM ); - return aFilter; -} -*/ - // ---------------------------------------------------- // class VCLXFileControl // ---------------------------------------------------- diff --git a/toolkit/source/awt/vclxwindows.cxx b/toolkit/source/awt/vclxwindows.cxx index b49fa1a621d6..c44745c4c2de 100644 --- a/toolkit/source/awt/vclxwindows.cxx +++ b/toolkit/source/awt/vclxwindows.cxx @@ -3388,6 +3388,7 @@ void VCLXEdit::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_PAINTTRANSPARENT, BASEPROPERTY_AUTOHSCROLL, BASEPROPERTY_AUTOVSCROLL, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, 0); @@ -4280,6 +4281,7 @@ void VCLXDateField::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_ENFORCE_FORMAT, BASEPROPERTY_TEXT, BASEPROPERTY_HIDEINACTIVESELECTION, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR, @@ -4621,6 +4623,7 @@ void VCLXTimeField::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_ENFORCE_FORMAT, BASEPROPERTY_TEXT, BASEPROPERTY_HIDEINACTIVESELECTION, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR, @@ -4924,6 +4927,7 @@ void VCLXNumericField::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_VALUE_DOUBLE, BASEPROPERTY_ENFORCE_FORMAT, BASEPROPERTY_HIDEINACTIVESELECTION, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR, @@ -5518,6 +5522,7 @@ void VCLXCurrencyField::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_VALUE_DOUBLE, BASEPROPERTY_ENFORCE_FORMAT, BASEPROPERTY_HIDEINACTIVESELECTION, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR, @@ -5865,6 +5870,7 @@ void VCLXPatternField::ImplGetPropertyIds( std::list< sal_uInt16 > &rIds ) BASEPROPERTY_TABSTOP, BASEPROPERTY_TEXT, BASEPROPERTY_HIDEINACTIVESELECTION, + BASEPROPERTY_VERTICALALIGN, BASEPROPERTY_WRITING_MODE, BASEPROPERTY_CONTEXT_WRITING_MODE, BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR, diff --git a/toolkit/source/controls/formattedcontrol.cxx b/toolkit/source/controls/formattedcontrol.cxx index 6171067f1185..5ac7a0237479 100644 --- a/toolkit/source/controls/formattedcontrol.cxx +++ b/toolkit/source/controls/formattedcontrol.cxx @@ -160,6 +160,7 @@ namespace toolkit ImplRegisterProperty( BASEPROPERTY_TEXTCOLOR ); ImplRegisterProperty( BASEPROPERTY_HIDEINACTIVESELECTION ); ImplRegisterProperty( BASEPROPERTY_ENFORCE_FORMAT ); + ImplRegisterProperty( BASEPROPERTY_VERTICALALIGN ); ImplRegisterProperty( BASEPROPERTY_WRITING_MODE ); ImplRegisterProperty( BASEPROPERTY_CONTEXT_WRITING_MODE ); ImplRegisterProperty( BASEPROPERTY_MOUSE_WHEEL_BEHAVIOUR ); diff --git a/toolkit/source/controls/unocontrols.cxx b/toolkit/source/controls/unocontrols.cxx index 3abacef7b67f..9e508c884f59 100644 --- a/toolkit/source/controls/unocontrols.cxx +++ b/toolkit/source/controls/unocontrols.cxx @@ -476,6 +476,7 @@ void UnoEditControl::getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines ) t // ---------------------------------------------------- UnoControlFileControlModel::UnoControlFileControlModel() { + ImplRegisterProperty( BASEPROPERTY_ALIGN ); ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR ); ImplRegisterProperty( BASEPROPERTY_BORDER ); ImplRegisterProperty( BASEPROPERTY_BORDERCOLOR ); @@ -489,6 +490,7 @@ UnoControlFileControlModel::UnoControlFileControlModel() ImplRegisterProperty( BASEPROPERTY_READONLY ); ImplRegisterProperty( BASEPROPERTY_TABSTOP ); ImplRegisterProperty( BASEPROPERTY_TEXT ); + ImplRegisterProperty( BASEPROPERTY_VERTICALALIGN ); ImplRegisterProperty( BASEPROPERTY_WRITING_MODE ); ImplRegisterProperty( BASEPROPERTY_CONTEXT_WRITING_MODE ); ImplRegisterProperty( BASEPROPERTY_HIDEINACTIVESELECTION ); diff --git a/vcl/inc/vcl/edit.hxx b/vcl/inc/vcl/edit.hxx index 534d63b3427c..bb7d965503d2 100644 --- a/vcl/inc/vcl/edit.hxx +++ b/vcl/inc/vcl/edit.hxx @@ -120,6 +120,7 @@ private: SAL_DLLPRIVATE void ImplCopy( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); SAL_DLLPRIVATE void ImplPaste( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); SAL_DLLPRIVATE long ImplGetExtraOffset() const; + SAL_DLLPRIVATE long ImplGetTextYPosition() const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XExtendedInputSequenceChecker > ImplGetInputSequenceChecker() const; SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > ImplGetBreakIterator() const; diff --git a/vcl/source/control/edit.cxx b/vcl/source/control/edit.cxx index 5f41a441c6a1..3a5f9014e27a 100644 --- a/vcl/source/control/edit.cxx +++ b/vcl/source/control/edit.cxx @@ -492,6 +492,17 @@ void Edit::ImplInvalidateOrRepaint( xub_StrLen nStart, xub_StrLen nEnd ) // ----------------------------------------------------------------------- +long Edit::ImplGetTextYPosition() const +{ + if ( GetStyle() & WB_TOP ) + return ImplGetExtraOffset(); + else if ( GetStyle() & WB_BOTTOM ) + return GetOutputSizePixel().Height() - GetTextHeight() - ImplGetExtraOffset(); + return ( GetOutputSizePixel().Height() - GetTextHeight() ) / 2; +} + +// ----------------------------------------------------------------------- + void Edit::ImplRepaint( xub_StrLen nStart, xub_StrLen nEnd, bool bLayout ) { if ( !IsReallyVisible() ) @@ -516,10 +527,8 @@ void Edit::ImplRepaint( xub_StrLen nStart, xub_StrLen nEnd, bool bLayout ) GetCaretPositions( aText, pDX, nStart, nEnd ); } - // center vertically - long nH = GetOutputSize().Height(); long nTH = GetTextHeight(); - Point aPos( mnXOffset, (nH-nTH)/2 ); + Point aPos( mnXOffset, ImplGetTextYPosition() ); if( bLayout ) { @@ -1193,7 +1202,7 @@ void Edit::ImplShowCursor( BOOL bOnlyIfVisible ) long nCursorPosX = nTextPos + mnXOffset + ImplGetExtraOffset(); // Cursor muss im sichtbaren Bereich landen: - Size aOutSize = GetOutputSizePixel(); + const Size aOutSize = GetOutputSizePixel(); if ( (nCursorPosX < 0) || (nCursorPosX >= aOutSize.Width()) ) { long nOldXOffset = mnXOffset; @@ -1227,8 +1236,8 @@ void Edit::ImplShowCursor( BOOL bOnlyIfVisible ) ImplInvalidateOrRepaint(); } - long nTextHeight = GetTextHeight(); - long nCursorPosY = (aOutSize.Height()-nTextHeight) / 2; + const long nTextHeight = GetTextHeight(); + const long nCursorPosY = ImplGetTextYPosition(); pCursor->SetPos( Point( nCursorPosX, nCursorPosY ) ); pCursor->SetSize( Size( nCursorWidth, nTextHeight ) ); pCursor->Show(); -- cgit From ba9a8c89c5ad8e9f9cafd1ebccb87c010a0949b2 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 29 Oct 2009 12:50:25 +0100 Subject: #i106427# fill in page range --- vcl/source/gdi/print3.cxx | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 6c56bba090ab..609fe5ad339b 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -322,6 +322,21 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr // reset last page property i_pController->setLastPage( sal_False ); + // update "PageRange" property inferring from other properties: + // case 1: "Pages" set from UNO API -> + // setup "Print Selection" and insert "PageRange" attribute + // case 2: "All pages" is selected + // update "Page range" attribute to have a sensible default, + // but leave "All" as selected + + // "Pages" attribute from API is now equivalent to "PageRange" + // AND "PrintContent" = 1 except calc where it is "PrintRange" = 1 + // Argh ! That sure needs cleaning up + beans::PropertyValue* pContentVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); + if( ! pContentVal ) + pContentVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintContent" ) ) ); + + // case 1: UNO API has set "Pages" beans::PropertyValue* pPagesVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pages" ) ) ); if( pPagesVal ) { @@ -332,16 +347,36 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr // "Pages" attribute from API is now equivalent to "PageRange" // AND "PrintContent" = 1 except calc where it is "PrintRange" = 1 // Argh ! That sure needs cleaning up - beans::PropertyValue* pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintRange" ) ) ); - if( ! pVal ) - pVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintContent" ) ) ); - if( pVal ) + if( pContentVal ) { - pVal->Value = makeAny( sal_Int32( 1 ) ); + pContentVal->Value = makeAny( sal_Int32( 1 ) ); i_pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PageRange" ) ), pPagesVal->Value ); } } } + // case 2: is "All" selected ? + else if( pContentVal ) + { + sal_Int32 nContent = -1; + if( pContentVal->Value >>= nContent ) + { + if( nContent == 0 ) + { + sal_Int32 nPages = i_pController->getPageCount(); + if( nPages > 0 ) + { + rtl::OUStringBuffer aBuf( 32 ); + aBuf.appendAscii( "1" ); + if( nPages > 1 ) + { + aBuf.appendAscii( "-" ); + aBuf.append( nPages ); + } + i_pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PageRange" ) ), makeAny( aBuf.makeStringAndClear() ) ); + } + } + } + } beans::PropertyValue* pReverseVal = i_pController->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintReverse" ) ) ); if( pReverseVal ) -- cgit From 069ce0d6e5cc9994af9b6470c2cf02057db84d0f Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 29 Oct 2009 12:57:50 +0100 Subject: #i106402# tab order of preview cycle buttons --- vcl/inc/vcl/prndlg.hxx | 2 +- vcl/source/window/printdlg.cxx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 95dfef827b90..c792b35c5cd9 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -213,8 +213,8 @@ namespace vcl PrintPreviewWindow maPreviewWindow; NumericField maPageEdit; FixedText maNumPagesText; - PushButton maForwardBtn; PushButton maBackwardBtn; + PushButton maForwardBtn; TabControl maTabCtrl; NUpTabPage maNUpPage; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index d4fe42ce3edb..66cac6f83a5d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -687,8 +687,8 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Thu, 29 Oct 2009 14:01:21 +0100 Subject: #i106341# catch division by zero in exotic case --- vcl/source/window/printdlg.cxx | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 66cac6f83a5d..1e1a9006c405 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -83,15 +83,22 @@ void PrintDialog::PrintPreviewWindow::Resize() aNewSize.Height() -= 2; Size aScaledSize; double fScale = 1.0; - if( maOrigSize.Width() > maOrigSize.Height() ) + + // #i106435# catch corner case of Size(0,0) + Size aOrigSize( maOrigSize ); + if( aOrigSize.Width() < 1 ) + aOrigSize.Width() = aNewSize.Width(); + if( aOrigSize.Height() < 1 ) + aOrigSize.Height() = aNewSize.Height(); + if( aOrigSize.Width() > aOrigSize.Height() ) { - aScaledSize = Size( aNewSize.Width(), aNewSize.Width() * maOrigSize.Height() / maOrigSize.Width() ); + aScaledSize = Size( aNewSize.Width(), aNewSize.Width() * aOrigSize.Height() / aOrigSize.Width() ); if( aScaledSize.Height() > aNewSize.Height() ) fScale = double(aNewSize.Height())/double(aScaledSize.Height()); } else { - aScaledSize = Size( aNewSize.Height() * maOrigSize.Width() / maOrigSize.Height(), aNewSize.Height() ); + aScaledSize = Size( aNewSize.Height() * aOrigSize.Width() / aOrigSize.Height(), aNewSize.Height() ); if( aScaledSize.Width() > aNewSize.Width() ) fScale = double(aNewSize.Width())/double(aScaledSize.Width()); } @@ -125,7 +132,12 @@ void PrintDialog::PrintPreviewWindow::Paint( const Rectangle& ) (aSize.Height() - aPreviewSize.Height()) / 2 ); const Size aLogicSize( maPageVDev.PixelToLogic( aPreviewSize, MapMode( MAP_100TH_MM ) ) ); - double fScale = double(aLogicSize.Width())/double(maOrigSize.Width()); + Size aOrigSize( maOrigSize ); + if( aOrigSize.Width() < 1 ) + aOrigSize.Width() = aLogicSize.Width(); + if( aOrigSize.Height() < 1 ) + aOrigSize.Height() = aLogicSize.Height(); + double fScale = double(aLogicSize.Width())/double(aOrigSize.Width()); maPageVDev.Erase(); -- cgit From 19b01b2cbe8df5c53a65b967c5da9e1eb1ff86ae Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Thu, 29 Oct 2009 14:22:34 +0100 Subject: #i106400# DisclosureButton should react on +/- keys --- vcl/inc/vcl/button.hxx | 2 ++ vcl/source/control/button.cxx | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/vcl/inc/vcl/button.hxx b/vcl/inc/vcl/button.hxx index 05f21192e4c8..e9e515681fe9 100644 --- a/vcl/inc/vcl/button.hxx +++ b/vcl/inc/vcl/button.hxx @@ -545,6 +545,8 @@ protected: public: DisclosureButton( Window* pParent, WinBits nStyle = 0 ); DisclosureButton( Window* pParent, const ResId& rResId ); + + virtual void KeyInput( const KeyEvent& rKEvt ); }; #endif // _SV_BUTTON_HXX diff --git a/vcl/source/control/button.cxx b/vcl/source/control/button.cxx index 71af9b3142c9..08992c903040 100644 --- a/vcl/source/control/button.cxx +++ b/vcl/source/control/button.cxx @@ -4457,3 +4457,22 @@ void DisclosureButton::ImplDrawCheckBoxState() DrawImage( aOff, *pImg, nStyle ); } } + +// ----------------------------------------------------------------------- + +void DisclosureButton::KeyInput( const KeyEvent& rKEvt ) +{ + KeyCode aKeyCode = rKEvt.GetKeyCode(); + + if( !aKeyCode.GetModifier() && + ( ( aKeyCode.GetCode() == KEY_ADD ) || + ( aKeyCode.GetCode() == KEY_SUBTRACT ) ) + ) + { + Check( aKeyCode.GetCode() == KEY_ADD ); + } + else + Button::KeyInput( rKEvt ); +} + + -- cgit From f67254410da8c2aa533c70ef05352d07b3746462 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 29 Oct 2009 20:50:43 +0100 Subject: printerpullpages: #i106398# fix HC mode --- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/window/printdlg.cxx | 35 +++++++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index c792b35c5cd9..162061984707 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -67,6 +67,7 @@ namespace vcl virtual void Paint( const Rectangle& rRect ); virtual void Command( const CommandEvent& ); virtual void Resize(); + virtual void DataChanged( const DataChangedEvent& ); void setPreview( const GDIMetaFile&, const Size&, const rtl::OUString&, sal_Int32 i_nDPIX, sal_Int32 i_nDPIY @@ -269,6 +270,7 @@ namespace vcl virtual void Resize(); virtual void Command( const CommandEvent& ); + virtual void DataChanged( const DataChangedEvent& ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( ClickHdl, Button* ); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1e1a9006c405..ecb52a7ee85d 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -75,6 +75,16 @@ PrintDialog::PrintPreviewWindow::~PrintPreviewWindow() { } +void PrintDialog::PrintPreviewWindow::DataChanged( const DataChangedEvent& i_rDCEvt ) +{ + // react on settings changed + if( i_rDCEvt.GetType() == DATACHANGED_SETTINGS ) + { + maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); + } + Window::DataChanged( i_rDCEvt ); +} + void PrintDialog::PrintPreviewWindow::Resize() { Size aNewSize( GetSizePixel() ); @@ -1568,6 +1578,14 @@ void PrintDialog::setupOptionalUI() SetOutputSizePixel( aSz ); } +void PrintDialog::DataChanged( const DataChangedEvent& i_rDCEvt ) +{ + // react on settings changed + if( i_rDCEvt.GetType() == DATACHANGED_SETTINGS ) + checkControlDependencies(); + ModalDialog::DataChanged( i_rDCEvt ); +} + void PrintDialog::checkControlDependencies() { if( maJobPage.maCopyCountField.GetValue() > 1 ) @@ -1576,12 +1594,21 @@ void PrintDialog::checkControlDependencies() maJobPage.maCollateBox.Enable( FALSE ); Image aImg( maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateImg : maJobPage.maNoCollateImg ); - if( GetSettings().GetStyleSettings().GetFieldColor().IsDark() ) - aImg = maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateHCImg : maJobPage.maNoCollateHCImg; + Image aHCImg( maJobPage.maCollateBox.IsChecked() ? maJobPage.maCollateHCImg : maJobPage.maNoCollateHCImg ); + bool bHC = GetSettings().GetStyleSettings().GetHighContrastMode(); + + Size aImgSize( aImg.GetSizePixel() ); + Size aHCImgSize( aHCImg.GetSizePixel() ); + + if( aHCImgSize.Width() > aImgSize.Width() ) + aImgSize.Width() = aHCImgSize.Width(); + if( aHCImgSize.Height() > aImgSize.Height() ) + aImgSize.Height() = aHCImgSize.Height(); // adjust size of image - maJobPage.maCollateImage.SetSizePixel( aImg.GetSizePixel() ); - maJobPage.maCollateImage.SetImage( aImg ); + maJobPage.maCollateImage.SetSizePixel( aImgSize ); + maJobPage.maCollateImage.SetImage( bHC ? aHCImg : aImg ); + maJobPage.maCollateImage.SetModeImage( aHCImg, BMP_COLOR_HIGHCONTRAST ); // enable setup button only for printers that can be setup bool bHaveSetup = maPController->getPrinter()->HasSupport( SUPPORT_SETUPDIALOG ); -- cgit From 7556065aa7584df351c86ef801592347557aa5ef Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 29 Oct 2009 21:28:35 +0100 Subject: printerpullpages: #i106363# fix mouse over on disclosure button --- vcl/inc/vcl/button.hxx | 1 + vcl/source/control/button.cxx | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/vcl/inc/vcl/button.hxx b/vcl/inc/vcl/button.hxx index e9e515681fe9..2073ecff524d 100644 --- a/vcl/inc/vcl/button.hxx +++ b/vcl/inc/vcl/button.hxx @@ -437,6 +437,7 @@ protected: SAL_DLLPRIVATE virtual void ImplDrawCheckBoxState(); SAL_DLLPRIVATE const Rectangle& GetStateRect() const { return maStateRect; } + SAL_DLLPRIVATE const Rectangle& GetMouseRect() const { return maMouseRect; } public: SAL_DLLPRIVATE void ImplCheck(); SAL_DLLPRIVATE void ImplSetMinimumNWFSize(); diff --git a/vcl/source/control/button.cxx b/vcl/source/control/button.cxx index 08992c903040..aa121049ffe8 100644 --- a/vcl/source/control/button.cxx +++ b/vcl/source/control/button.cxx @@ -4419,7 +4419,7 @@ void DisclosureButton::ImplDrawCheckBoxState() if ( HasFocus() ) nState |= CTRL_STATE_FOCUSED; if ( ImplGetButtonState() & BUTTON_DRAW_DEFAULT ) nState |= CTRL_STATE_DEFAULT; if ( Window::IsEnabled() ) nState |= CTRL_STATE_ENABLED; - if ( IsMouseOver() && aStateRect.IsInside( GetPointerPosPixel() ) ) + if ( IsMouseOver() && GetMouseRect().IsInside( GetPointerPosPixel() ) ) nState |= CTRL_STATE_ROLLOVER; if( ! DrawNativeControl( CTRL_LISTNODE, PART_ENTIRE_CONTROL, aCtrlRegion, nState, -- cgit From 561697e7bafe9c4b31340e4c507907f16b03e1fc Mon Sep 17 00:00:00 2001 From: Michael Stahl Date: Fri, 30 Oct 2009 17:33:01 +0100 Subject: #i93514#: really fix locking for PropertyBag::setModified() --- comphelper/source/property/opropertybag.cxx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/comphelper/source/property/opropertybag.cxx b/comphelper/source/property/opropertybag.cxx index 8b816e8c1ce9..caa895021103 100644 --- a/comphelper/source/property/opropertybag.cxx +++ b/comphelper/source/property/opropertybag.cxx @@ -240,7 +240,7 @@ namespace comphelper if ( !( _element >>= aProperty ) ) throw IllegalArgumentException( ::rtl::OUString(), *this, 1 ); - ::osl::MutexGuard aGuard( m_aMutex ); + ::osl::ClearableMutexGuard g( m_aMutex ); // check whether the type is allowed, everything else will be checked // by m_aDynamicProperties @@ -254,6 +254,7 @@ namespace comphelper // our property info is dirty m_pArrayHelper.reset(); + g.clear(); setModified(sal_True); } @@ -346,7 +347,7 @@ namespace comphelper //-------------------------------------------------------------------- void SAL_CALL OPropertyBag::addProperty( const ::rtl::OUString& _rName, ::sal_Int16 _nAttributes, const Any& _rInitialValue ) throw (PropertyExistException, IllegalTypeException, IllegalArgumentException, RuntimeException) { - ::osl::MutexGuard aGuard( m_aMutex ); + ::osl::ClearableMutexGuard g( m_aMutex ); // check whether the type is allowed, everything else will be checked // by m_aDynamicProperties @@ -362,19 +363,21 @@ namespace comphelper // our property info is dirty m_pArrayHelper.reset(); + g.clear(); setModified(sal_True); } //-------------------------------------------------------------------- void SAL_CALL OPropertyBag::removeProperty( const ::rtl::OUString& _rName ) throw (UnknownPropertyException, NotRemoveableException, RuntimeException) { - ::osl::MutexGuard aGuard( m_aMutex ); + ::osl::ClearableMutexGuard g( m_aMutex ); m_aDynamicProperties.removeProperty( _rName ); // our property info is dirty m_pArrayHelper.reset(); + g.clear(); setModified(sal_True); } -- cgit From ff9f90cf28852703366e853ab7e4f9d5218c8f35 Mon Sep 17 00:00:00 2001 From: Michael Stahl Date: Fri, 30 Oct 2009 17:36:02 +0100 Subject: #i105295#: fix various uninitialized variables reported by valgrind in: IMapObject::IMapObject() [incompatible interface change!] --- svtools/inc/svtools/imapobj.hxx | 2 +- svtools/source/misc/imap.cxx | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/svtools/inc/svtools/imapobj.hxx b/svtools/inc/svtools/imapobj.hxx index 3671bf50878c..8f95c41d1c54 100644 --- a/svtools/inc/svtools/imapobj.hxx +++ b/svtools/inc/svtools/imapobj.hxx @@ -96,7 +96,7 @@ public: static rtl_TextEncoding nActualTextEncoding; - IMapObject() {}; + IMapObject(); IMapObject( const String& rURL, const String& rAltText, const String& rDesc, diff --git a/svtools/source/misc/imap.cxx b/svtools/source/misc/imap.cxx index 9fb60111094e..965292803e43 100644 --- a/svtools/source/misc/imap.cxx +++ b/svtools/source/misc/imap.cxx @@ -64,6 +64,12 @@ UINT16 IMapObject::nActualTextEncoding = (UINT16) RTL_TEXTENCODING_DONTKNOW; #pragma optimize ( "", off ) #endif +IMapObject::IMapObject() + : bActive( false ) + , nReadVersion( 0 ) +{ +} + IMapObject::IMapObject( const String& rURL, const String& rAltText, const String& rDesc, const String& rTarget, const String& rName, BOOL bURLActive ) : aURL( rURL ) @@ -72,6 +78,7 @@ IMapObject::IMapObject( const String& rURL, const String& rAltText, const String , aTarget( rTarget ) , aName( rName ) , bActive( bURLActive ) +, nReadVersion( 0 ) { } -- cgit From d2b148f667115467247e985816595fd951f9bd7b Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 2 Nov 2009 11:46:52 +0100 Subject: printerpullpages: #i106435# fix a division by zero error --- vcl/source/window/printdlg.cxx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index ecb52a7ee85d..801d7999f692 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -850,6 +850,10 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Mon, 2 Nov 2009 12:38:16 +0100 Subject: add the implementation name to the assertion text if copying a property fails --- comphelper/source/property/property.cxx | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/comphelper/source/property/property.cxx b/comphelper/source/property/property.cxx index fe6cbaa9d767..14b3b8f9169d 100644 --- a/comphelper/source/property/property.cxx +++ b/comphelper/source/property/property.cxx @@ -38,15 +38,11 @@ #include #if OSL_DEBUG_LEVEL > 0 - #ifndef _RTL_STRBUF_HXX_ #include - #endif - #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include - #endif - #ifndef _OSL_THREAD_H_ #include - #endif + #include + #include #endif #include #include @@ -71,6 +67,8 @@ namespace comphelper using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; + using ::com::sun::star::lang::XServiceInfo; + using ::com::sun::star::uno::UNO_QUERY; /** === end UNO using === **/ namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; @@ -110,7 +108,18 @@ void copyProperties(const Reference& _rxSource, ::rtl::OStringBuffer aBuffer; aBuffer.append( "::comphelper::copyProperties: could not copy property '" ); aBuffer.append( ::rtl::OString( pSourceProps->Name.getStr(), pSourceProps->Name.getLength(), RTL_TEXTENCODING_ASCII_US ) ); - aBuffer.append( "' to the destination set.\n" ); + aBuffer.append( "' to the destination set (a '" ); + + Reference< XServiceInfo > xSI( _rxDest, UNO_QUERY ); + if ( xSI.is() ) + { + aBuffer.append( ::rtl::OUStringToOString( xSI->getImplementationName(), osl_getThreadTextEncoding() ) ); + } + else + { + aBuffer.append( typeid( *_rxDest.get() ).name() ); + } + aBuffer.append( "' implementation).\n" ); Any aException( ::cppu::getCaughtException() ); aBuffer.append( "Caught an exception of type '" ); -- cgit From b7362dfa446a3876529d7223306675f3b7d371c8 Mon Sep 17 00:00:00 2001 From: Michael Stahl Date: Mon, 2 Nov 2009 19:08:00 +0100 Subject: #i105745#: tools/stream.hxx: API change: make SvMemoryStream::GetSize() private introduce new public SvMemoryStream::GetEndOfData() --- sot/source/sdstor/stgstrms.cxx | 2 +- sot/source/sdstor/stgstrms.hxx | 3 +-- svtools/source/filter.vcl/filter/filter2.cxx | 3 ++- svtools/source/numbers/numhead.cxx | 2 +- tools/inc/tools/stream.hxx | 5 ++++- vcl/source/gdi/bmpconv.cxx | 3 ++- 6 files changed, 11 insertions(+), 7 deletions(-) diff --git a/sot/source/sdstor/stgstrms.cxx b/sot/source/sdstor/stgstrms.cxx index 46ae3529439c..0e20af6118af 100644 --- a/sot/source/sdstor/stgstrms.cxx +++ b/sot/source/sdstor/stgstrms.cxx @@ -1104,7 +1104,7 @@ StgTmpStrm::~StgTmpStrm() } } -ULONG StgTmpStrm::GetSize() +ULONG StgTmpStrm::GetSize() const { ULONG n; if( pStrm ) diff --git a/sot/source/sdstor/stgstrms.hxx b/sot/source/sdstor/stgstrms.hxx index 806d562af6d0..fd7971da3aba 100644 --- a/sot/source/sdstor/stgstrms.hxx +++ b/sot/source/sdstor/stgstrms.hxx @@ -167,8 +167,7 @@ public: ~StgTmpStrm(); BOOL Copy( StgTmpStrm& ); void SetSize( ULONG ); - using SvMemoryStream::GetSize; - ULONG GetSize(); + ULONG GetSize() const; }; #endif diff --git a/svtools/source/filter.vcl/filter/filter2.cxx b/svtools/source/filter.vcl/filter/filter2.cxx index d570dd34e50f..9e0e3ba43d54 100644 --- a/svtools/source/filter.vcl/filter/filter2.cxx +++ b/svtools/source/filter.vcl/filter/filter2.cxx @@ -471,7 +471,8 @@ BOOL GraphicDescriptor::ImpDetectJPG( SvStream& rStm, BOOL bExtendedInfo ) // Groesse des verbleibenden Puffers ermitteln if ( bLinked ) - nMax = ( (SvMemoryStream&) rStm ).GetSize() - 16; + nMax = static_cast< SvMemoryStream& >(rStm).GetEndOfData() + - 16; else nMax = DATA_SIZE - 16; diff --git a/svtools/source/numbers/numhead.cxx b/svtools/source/numbers/numhead.cxx index 7e79aad624f3..921442de1b66 100644 --- a/svtools/source/numbers/numhead.cxx +++ b/svtools/source/numbers/numhead.cxx @@ -139,7 +139,7 @@ ImpSvNumMultipleReadHeader::ImpSvNumMultipleReadHeader(SvStream& rNewStream) : ImpSvNumMultipleReadHeader::~ImpSvNumMultipleReadHeader() { - DBG_ASSERT( pMemStream->Tell() == pMemStream->GetSize(), + DBG_ASSERT( pMemStream->Tell() == pMemStream->GetEndOfData(), "Sizes nicht vollstaendig gelesen" ); delete pMemStream; delete [] pBuf; diff --git a/tools/inc/tools/stream.hxx b/tools/inc/tools/stream.hxx index bacaac89fe44..23496322fa4c 100644 --- a/tools/inc/tools/stream.hxx +++ b/tools/inc/tools/stream.hxx @@ -776,6 +776,9 @@ class TOOLS_DLLPUBLIC SvMemoryStream : public SvStream SvMemoryStream (const SvMemoryStream&); SvMemoryStream & operator= (const SvMemoryStream&); + friend class SvCacheStream; + sal_Size GetSize() const { return nSize; } + protected: sal_Size nSize; sal_Size nResize; @@ -817,7 +820,7 @@ public: virtual void ResetError(); - sal_Size GetSize() const { return nSize; } + sal_Size GetEndOfData() const { return nEndOfData; } const void* GetData() { Flush(); return pBuf; } operator const void*() { Flush(); return pBuf; } virtual sal_uInt16 IsA() const; diff --git a/vcl/source/gdi/bmpconv.cxx b/vcl/source/gdi/bmpconv.cxx index 9d9b81ba50d4..03d85acb0159 100644 --- a/vcl/source/gdi/bmpconv.cxx +++ b/vcl/source/gdi/bmpconv.cxx @@ -192,7 +192,8 @@ BmpTransporter::BmpTransporter( const Bitmap& rBM ) m_aSize.Height = rBM.GetSizePixel().Height(); SvMemoryStream aStream; rBM.Write( aStream, FALSE, TRUE ); - m_aBM = Sequence((const sal_Int8*)aStream.GetData(), aStream.GetSize() ); + m_aBM = Sequence(static_cast(aStream.GetData()), + aStream.GetEndOfData()); } BmpTransporter::~BmpTransporter() -- cgit From 4d4bfb28a75c7887a46fec3c0f71260781ae0471 Mon Sep 17 00:00:00 2001 From: "Frank Schoenheit [fs]" Date: Mon, 16 Nov 2009 14:59:17 +0100 Subject: #i84012# +getLocalName --- unotools/inc/unotools/confignode.hxx | 3 +++ unotools/source/config/confignode.cxx | 23 ++++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/unotools/inc/unotools/confignode.hxx b/unotools/inc/unotools/confignode.hxx index 580274004e1a..2e305030fa2b 100644 --- a/unotools/inc/unotools/confignode.hxx +++ b/unotools/inc/unotools/confignode.hxx @@ -88,6 +88,9 @@ namespace utl /// dtor ~OConfigurationNode() {} + /// returns the local name of the node + ::rtl::OUString getLocalName() const; + /** open a sub node @param _rPath access path of the to-be-opened sub node. May be a hierarchical path. */ diff --git a/unotools/source/config/confignode.cxx b/unotools/source/config/confignode.cxx index 4b1b9fe272db..56d258461e95 100644 --- a/unotools/source/config/confignode.cxx +++ b/unotools/source/config/confignode.cxx @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #if OSL_DEBUG_LEVEL > 0 @@ -138,6 +139,22 @@ namespace utl clear(); } + //------------------------------------------------------------------------ + ::rtl::OUString OConfigurationNode::getLocalName() const + { + ::rtl::OUString sLocalName; + try + { + Reference< XNamed > xNamed( m_xDirectAccess, UNO_QUERY_THROW ); + sLocalName = xNamed->getName(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sLocalName; + } + //------------------------------------------------------------------------ ::rtl::OUString OConfigurationNode::normalizeName(const ::rtl::OUString& _rName, NAMEORIGIN _eOrigin) const { @@ -155,13 +172,9 @@ namespace utl else sName = xEscaper->unescapeString(sName); } - catch(IllegalArgumentException&) - { - OSL_ENSURE(sal_False, "OConfigurationNode::normalizeName: illegal argument (caught an exception saying so)!"); - } catch(Exception&) { - OSL_ENSURE(sal_False, "OConfigurationNode::normalizeName: caught an exception!"); + DBG_UNHANDLED_EXCEPTION(); } } } -- cgit From 77f0f65166af5d0c899136a0f91a5b49e19fcae7 Mon Sep 17 00:00:00 2001 From: "Frank Schoenheit [fs]" Date: Tue, 17 Nov 2009 12:37:36 +0100 Subject: #i10000# --- comphelper/source/property/property.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/comphelper/source/property/property.cxx b/comphelper/source/property/property.cxx index 14b3b8f9169d..17949b9889dd 100644 --- a/comphelper/source/property/property.cxx +++ b/comphelper/source/property/property.cxx @@ -67,7 +67,9 @@ namespace comphelper using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; +#if OSL_DEBUG_LEVEL > 0 using ::com::sun::star::lang::XServiceInfo; +#endif using ::com::sun::star::uno::UNO_QUERY; /** === end UNO using === **/ namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; -- cgit From d04edead2cc8bcb9f2bfef829f1a25ec75070fc3 Mon Sep 17 00:00:00 2001 From: npower Developer Date: Wed, 18 Nov 2009 11:25:15 +0000 Subject: menuincustomtoolbar: #i105626#: implement menu for custom toolbar ( and some item style override capability ) --- vcl/inc/vcl/menu.hxx | 2 ++ vcl/inc/vcl/toolbox.hxx | 3 +++ vcl/source/window/toolbox.cxx | 26 ++++++++++++++++++++++---- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/menu.hxx b/vcl/inc/vcl/menu.hxx index 8d3ac4e8b505..66f35823b06a 100644 --- a/vcl/inc/vcl/menu.hxx +++ b/vcl/inc/vcl/menu.hxx @@ -93,6 +93,8 @@ typedef USHORT MenuItemBits; #define MIB_POPUPSELECT ((MenuItemBits)0x0020) // not in rsc/vclsrc.hxx because only a prelimitary solution #define MIB_NOSELECT ((MenuItemBits)0x0040) +#define MIB_ICON ((MenuItemBits)0x0080) +#define MIB_TEXT ((MenuItemBits)0x0100) #define MENU_FLAG_NOAUTOMNEMONICS 0x0001 #define MENU_FLAG_HIDEDISABLEDENTRIES 0x0002 diff --git a/vcl/inc/vcl/toolbox.hxx b/vcl/inc/vcl/toolbox.hxx index 6e4c300ccc40..c2547e4b01ba 100644 --- a/vcl/inc/vcl/toolbox.hxx +++ b/vcl/inc/vcl/toolbox.hxx @@ -124,6 +124,9 @@ typedef USHORT ToolBoxItemBits; #define TIB_DROPDOWN ((ToolBoxItemBits)0x0020) #define TIB_REPEAT ((ToolBoxItemBits)0x0040) #define TIB_DROPDOWNONLY ((ToolBoxItemBits)0x0080 | TIB_DROPDOWN) // this button has only drop down functionality +#define TIB_TEXT_ONLY ((ToolBoxItemBits)0x0100) +#define TIB_ICON_ONLY ((ToolBoxItemBits)0x0200) +#define TIB_TEXTICON ((ToolBoxItemBits) TIB_TEXT_ONLY | TIB_ICON_ONLY ) // ----------------- // - ToolBox-Types - diff --git a/vcl/source/window/toolbox.cxx b/vcl/source/window/toolbox.cxx index 8aa4926f5e1a..ef58ea9e6bc6 100644 --- a/vcl/source/window/toolbox.cxx +++ b/vcl/source/window/toolbox.cxx @@ -229,6 +229,22 @@ int ToolBox::ImplGetDragWidth( ToolBox* pThis ) } return width; } + +ButtonType determineButtonType( ImplToolItem* pItem, ButtonType defaultType ) +{ + ButtonType tmpButtonType = defaultType; + ToolBoxItemBits nBits( pItem->mnBits & 0x300 ); + if ( nBits & TIB_TEXTICON ) // item has custom setting + { + tmpButtonType = BUTTON_SYMBOLTEXT; + if ( nBits == TIB_TEXT_ONLY ) + tmpButtonType = BUTTON_TEXT; + else if ( nBits == TIB_ICON_ONLY ) + tmpButtonType = BUTTON_SYMBOL; + } + return tmpButtonType; +} + // ----------------------------------------------------------------------- void ToolBox::ImplUpdateDragArea( ToolBox *pThis ) @@ -1992,12 +2008,13 @@ BOOL ToolBox::ImplCalcItem() bText = FALSE; else bText = TRUE; - + ButtonType tmpButtonType = determineButtonType( &(*it), meButtonType ); // default to toolbox setting if ( bImage || bText ) { + it->mbEmptyBtn = FALSE; - if ( meButtonType == BUTTON_SYMBOL ) + if ( tmpButtonType == BUTTON_SYMBOL ) { // we're drawing images only if ( bImage || !bText ) @@ -2011,7 +2028,7 @@ BOOL ToolBox::ImplCalcItem() it->mbVisibleText = TRUE; } } - else if ( meButtonType == BUTTON_TEXT ) + else if ( tmpButtonType == BUTTON_TEXT ) { // we're drawing text only if ( bText || !bImage ) @@ -3625,7 +3642,8 @@ void ToolBox::ImplDrawItem( USHORT nPos, BOOL bHighlight, BOOL bPaint, BOOL bLay // determine what has to be drawn on the button: image, text or both BOOL bImage; BOOL bText; - pItem->DetermineButtonDrawStyle( meButtonType, bImage, bText ); + ButtonType tmpButtonType = determineButtonType( pItem, meButtonType ); // default to toolbox setting + pItem->DetermineButtonDrawStyle( tmpButtonType, bImage, bText ); // compute output values long nBtnWidth = aBtnSize.Width()-SMALLBUTTON_HSIZE; -- cgit From 6320fb69ac76730cc148af0cc907036889c925eb Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 14:54:20 +0100 Subject: printerpullpages: #i94718# fix brochure printing, better paper match --- vcl/aqua/source/gdi/salprn.cxx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/vcl/aqua/source/gdi/salprn.cxx b/vcl/aqua/source/gdi/salprn.cxx index 3bf229d1927f..47c027a033aa 100644 --- a/vcl/aqua/source/gdi/salprn.cxx +++ b/vcl/aqua/source/gdi/salprn.cxx @@ -594,7 +594,14 @@ BOOL AquaSalInfoPrinter::StartJob( const String* i_pFileName, // now for the current run mnStartPageOffsetX = mnStartPageOffsetY = 0; // setup the paper size and orientation - setPaperSize( aCurSize.Width(), aCurSize.Height(), ORIENTATION_PORTRAIT ); + // do this on our associated Printer object, since that is + // out interface to the applications which occasionally rely on the paper + // information (e.g. brochure printing scales to the found paper size) + // also SetPaperSizeUser has the advantage that we can share a + // platform independent paper matching algorithm + boost::shared_ptr pPrinter( i_rController.getPrinter() ); + pPrinter->SetMapMode( MapMode( MAP_100TH_MM ) ); + pPrinter->SetPaperSizeUser( aCurSize, true ); // create view NSView* pPrintView = [[AquaPrintView alloc] initWithController: &i_rController withInfoPrinter: this]; -- cgit From ced811f0109198d81bbc09e610dd82fb716307b4 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 15:11:29 +0100 Subject: printerpullpages: #i106762# hide properties button instead of disabling it when no printer setup dialog is available --- svtools/source/dialogs/prnsetup.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/svtools/source/dialogs/prnsetup.cxx b/svtools/source/dialogs/prnsetup.cxx index dedb5b2d7143..74cfe7b1286a 100644 --- a/svtools/source/dialogs/prnsetup.cxx +++ b/svtools/source/dialogs/prnsetup.cxx @@ -59,7 +59,7 @@ void ImplFillPrnDlgListBox( const Printer* pPrinter, } pBox->Enable( nCount != 0 ); - pPropBtn->Enable( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); + pPropBtn->Show( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) ); } // ----------------------------------------------------------------------- -- cgit From 5e9fc7a71efaf83fde0766a78c72ee6b7b781ea8 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 15:39:55 +0100 Subject: printerpullpages: #i106555# layout preview control row if pages text changes to accomodat new text length --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/source/window/printdlg.cxx | 29 +++++++++++++++++------------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 162061984707..deebb1f11254 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -249,6 +249,7 @@ namespace vcl rtl::OUString maDefPrtText; vcl::RowOrColumn maLayout; + boost::shared_ptr mxPreviewCtrls; Size maDetailsCollapsedSize; Size maDetailsExpandedSize; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 801d7999f692..a3badf32887f 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -915,18 +915,18 @@ void PrintDialog::setupLayout() xPreviewAndTab->addChild( xPreview, 5 ); xPreview->addWindow( &maPreviewWindow, 5 ); // get a row for the preview controls - boost::shared_ptr< vcl::RowOrColumn > xPreviewCtrls( new vcl::RowOrColumn( xPreview.get(), false ) ); - nIndex = xPreview->addChild( xPreviewCtrls ); - boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); - xPreviewCtrls->addChild( xSpacer ); - xPreviewCtrls->addWindow( &maPageEdit ); - xPreviewCtrls->addWindow( &maNumPagesText ); - xSpacer.reset( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); - xPreviewCtrls->addChild( xSpacer ); - xPreviewCtrls->addWindow( &maBackwardBtn ); - xPreviewCtrls->addWindow( &maForwardBtn ); - xSpacer.reset( new vcl::Spacer( xPreviewCtrls.get(), 2 ) ); - xPreviewCtrls->addChild( xSpacer ); + mxPreviewCtrls.reset( new vcl::RowOrColumn( xPreview.get(), false ) ); + nIndex = xPreview->addChild( mxPreviewCtrls ); + boost::shared_ptr< vcl::Spacer > xSpacer( new vcl::Spacer( mxPreviewCtrls.get(), 2 ) ); + mxPreviewCtrls->addChild( xSpacer ); + mxPreviewCtrls->addWindow( &maPageEdit ); + mxPreviewCtrls->addWindow( &maNumPagesText ); + xSpacer.reset( new vcl::Spacer( mxPreviewCtrls.get(), 2 ) ); + mxPreviewCtrls->addChild( xSpacer ); + mxPreviewCtrls->addWindow( &maBackwardBtn ); + mxPreviewCtrls->addWindow( &maForwardBtn ); + xSpacer.reset( new vcl::Spacer( mxPreviewCtrls.get(), 2 ) ); + mxPreviewCtrls->addChild( xSpacer ); // continue with the tab ctrl xPreviewAndTab->addWindow( &maTabCtrl ); @@ -1718,6 +1718,11 @@ void PrintDialog::setPreviewText( sal_Int32 ) { rtl::OUString aNewText( searchAndReplace( maPageStr, "%n", 2, rtl::OUString::valueOf( mnCachedPages ) ) ); maNumPagesText.SetText( aNewText ); + + // if layout is already established the refresh layout of + // preview controls since text length may have changes + if( mxPreviewCtrls.get() ) + mxPreviewCtrls->setManagedArea( mxPreviewCtrls->getManagedArea() ); } void PrintDialog::preparePreview( bool i_bNewPage, bool i_bMayUseCache ) -- cgit From c0879d0fd9c440e690ca24b4b4085b2863b46694 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 17:23:09 +0100 Subject: printerpullpages: #i106559# warn about missing default printer --- vcl/inc/vcl/svids.hrc | 1 + vcl/source/gdi/print.cxx | 13 ++++++++++--- vcl/source/gdi/print3.cxx | 19 ++++++++++++++++++- vcl/source/src/print.src | 6 ++++++ 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index c54dfb70c3ed..b3fcf9c70dd3 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -163,6 +163,7 @@ #define SV_PRINT_PROGRESS_TEXT 2 #define SV_PRINT_NATIVE_STRINGS 2050 +#define SV_PRINT_NOPRINTERWARNING 2051 #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 diff --git a/vcl/source/gdi/print.cxx b/vcl/source/gdi/print.cxx index c70835de47e7..16f6b53af7a8 100644 --- a/vcl/source/gdi/print.cxx +++ b/vcl/source/gdi/print.cxx @@ -277,7 +277,9 @@ static void ImplInitPrnQueueList() pSVData->maGDIData.mpPrinterQueueList = new ImplPrnQueueList; - pSVData->mpDefInst->GetPrinterQueueInfo( pSVData->maGDIData.mpPrinterQueueList ); + static const char* pEnv = getenv( "SAL_DISABLE_PRINTERLIST" ); + if( !pEnv || !*pEnv ) + pSVData->mpDefInst->GetPrinterQueueInfo( pSVData->maGDIData.mpPrinterQueueList ); } // ----------------------------------------------------------------------- @@ -336,9 +338,14 @@ const QueueInfo* Printer::GetQueueInfo( const String& rPrinterName, bool bStatus XubString Printer::GetDefaultPrinterName() { - ImplSVData* pSVData = ImplGetSVData(); + static const char* pEnv = getenv( "SAL_DISABLE_DEFAULTPRINTER" ); + if( !pEnv || !*pEnv ) + { + ImplSVData* pSVData = ImplGetSVData(); - return pSVData->mpDefInst->GetDefaultPrinter(); + return pSVData->mpDefInst->GetDefaultPrinter(); + } + return XubString(); } // ======================================================================= diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 609fe5ad339b..e958994c0c6a 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -38,6 +38,7 @@ #include "vcl/salprn.hxx" #include "vcl/svids.hrc" #include "vcl/metaact.hxx" +#include "vcl/msgbox.hxx" #include "tools/urlobj.hxx" @@ -310,8 +311,24 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr const JobSetup& i_rInitSetup ) { - // setup printer boost::shared_ptr pController( i_pController ); + + // check if there is a default printer; if not, show an error box (if appropriate) + if( GetDefaultPrinterName().Len() == 0 ) + { + if( pController->isShowDialogs() + // && ! pController->isDirectPrint() + ) + { + ErrorBox aBox( NULL, VclResId( SV_PRINT_NOPRINTERWARNING ) ); + aBox.Execute(); + } + pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDirect" ) ), + makeAny( sal_False ) ); + } + + // setup printer + // if no specific printer is already set, create one if( ! pController->getPrinter() ) { diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 856ba88525fa..83ea13e8478a 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -465,6 +465,12 @@ ModelessDialog SV_DLG_PRINT_PROGRESS }; }; +ErrorBox SV_PRINT_NOPRINTERWARNING +{ + Title = "%PRODUCTNAME"; + Message [en-US] = "No default printer found.\nPlease choose a printer and try again."; +}; + StringArray SV_PRINT_NATIVE_STRINGS { ItemList [en-US] = -- cgit From 7a172afb40d89766934075116f7b3a695f09b8b5 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 18:22:58 +0100 Subject: printerpullpages: #i106506# disable Pages radio button where unused --- vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/window/printdlg.cxx | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index deebb1f11254..e19b95023c75 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -101,6 +101,7 @@ namespace vcl FixedLine maNupLine; RadioButton maPagesBtn; RadioButton maBrochureBtn; + FixedText maPagesBoxTitleTxt; ListBox maNupPagesBox; // controls for "Custom" page mode @@ -126,6 +127,7 @@ namespace vcl vcl::RowOrColumn maLayout; boost::shared_ptr< vcl::RowOrColumn > mxBrochureDep; + boost::shared_ptr< vcl::LabeledElement >mxPagesBtnLabel; void setupLayout(); diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index a3badf32887f..1091c4c5b479 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -285,6 +285,7 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) , maNupLine( this, VclResId( SV_PRINT_PRT_NUP_LAYOUT_FL ) ) , maPagesBtn( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BTN ) ) , maBrochureBtn( this, VclResId( SV_PRINT_PRT_NUP_BROCHURE_BTN ) ) + , maPagesBoxTitleTxt( this, 0 ) , maNupPagesBox( this, VclResId( SV_PRINT_PRT_NUP_PAGES_BOX ) ) , maNupNumPagesTxt( this, VclResId( SV_PRINT_PRT_NUP_NUM_PAGES_TXT ) ) , maNupColEdt( this, VclResId( SV_PRINT_PRT_NUP_COLS_EDT ) ) @@ -330,6 +331,7 @@ PrintDialog::NUpTabPage::NUpTabPage( Window* i_pParent, const ResId& rResId ) maNupLine.SMHID2("NUpPage", "Layout"); maBrochureBtn.SMHID2("NUpPage", "Brochure" ); maPagesBtn.SMHID2( "NUpPage", "PagesPerSheet" ); + maPagesBoxTitleTxt.SMHID2( "NUpPage", "PagesPerSheetLabel" ); maNupPagesBox.SMHID2( "NUpPage", "PagesPerSheetBox" ); maNupNumPagesTxt.SMHID2( "NUpPage", "Columns" ); maNupColEdt.SMHID2( "NUpPage", "ColumnsBox" ); @@ -415,7 +417,8 @@ void PrintDialog::NUpTabPage::setupLayout() boost::shared_ptr< vcl::LabelColumn > xMainCol( new vcl::LabelColumn( xIndent.get() ) ); xIndent->setChild( xMainCol ); - xMainCol->addRow( &maPagesBtn, &maNupPagesBox ); + size_t nPagesIndex = xMainCol->addRow( &maPagesBtn, &maNupPagesBox ); + mxPagesBtnLabel = boost::dynamic_pointer_cast( xMainCol->getChild( nPagesIndex ) ); xRow.reset( new vcl::RowOrColumn( xMainCol.get(), false ) ); xMainCol->addRow( &maNupNumPagesTxt, xRow, nIndent ); @@ -1510,6 +1513,19 @@ void PrintDialog::setupOptionalUI() } } + // #i106506# if no brochure button, then the singular Pages radio button + // makes no sense, so replace it by a FixedText label + if( ! maNUpPage.maBrochureBtn.IsVisible() ) + { + if( maNUpPage.mxPagesBtnLabel.get() ) + { + maNUpPage.maPagesBoxTitleTxt.SetText( maNUpPage.maPagesBtn.GetText() ); + maNUpPage.maPagesBoxTitleTxt.Show( TRUE ); + maNUpPage.mxPagesBtnLabel->setLabel( &maNUpPage.maPagesBoxTitleTxt ); + maNUpPage.maPagesBtn.Show( FALSE ); + } + } + // update enable states checkOptionalControlDependencies(); -- cgit From 969bf03a947d80eacf0deb3c7a3fdfb86b2f5aba Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 19:19:29 +0100 Subject: printerpullpages: #i106507# remove layout page for math --- vcl/inc/vcl/print.hxx | 4 ++++ vcl/inc/vcl/prndlg.hxx | 2 ++ vcl/source/gdi/print3.cxx | 19 +++++++++++-------- vcl/source/window/printdlg.cxx | 14 ++++++++++++-- 4 files changed, 29 insertions(+), 10 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index 25ace16aea52..e91e3db0c9d7 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -460,6 +460,10 @@ public: const com::sun::star::beans::PropertyValue* getValue( const rtl::OUString& i_rPropertyName ) const; // get a sequence of properties com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > getValues( const com::sun::star::uno::Sequence< rtl::OUString >& ) const; + /* get a bool property + in case the property is unknown or not convertible to bool, i_bFallback is returned + */ + sal_Bool getBoolProperty( const rtl::OUString& i_rPropertyName, sal_Bool i_bFallback ) const; /* set a property value - can also be used to add another UI property */ diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index e19b95023c75..57a1e32df6d3 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -256,6 +256,8 @@ namespace vcl Size maDetailsCollapsedSize; Size maDetailsExpandedSize; + sal_Bool mbShowLayoutPage; + Size getJobPageSize(); void updateNup(); void updateNupFromPages(); diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e958994c0c6a..287969a146f3 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1413,22 +1413,25 @@ void PrinterController::pushPropertiesToPrinter() bool PrinterController::isShowDialogs() const { - sal_Bool bApi = sal_False; - const com::sun::star::beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsApi" ) ) ); - if( pVal ) - pVal->Value >>= bApi; + sal_Bool bApi = getBoolProperty( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsApi" ) ), sal_False ); return ! bApi && ! Application::IsHeadlessModeEnabled(); } bool PrinterController::isDirectPrint() const { - sal_Bool bDirect = sal_False; - const com::sun::star::beans::PropertyValue* pVal = getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDirect" ) ) ); - if( pVal ) - pVal->Value >>= bDirect; + sal_Bool bDirect = getBoolProperty( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDirect" ) ), sal_False ); return bDirect == sal_True; } +sal_Bool PrinterController::getBoolProperty( const rtl::OUString& i_rProperty, sal_Bool i_bFallback ) const +{ + sal_Bool bRet = i_bFallback; + const com::sun::star::beans::PropertyValue* pVal = getValue( i_rProperty ); + if( pVal ) + pVal->Value >>= bRet; + return bRet; +} + /* * PrinterOptionsHelper **/ diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 1091c4c5b479..971c629058c5 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -725,6 +725,7 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr>= bNoLayoutPage; + mbShowLayoutPage = ! bNoLayoutPage; + } } // bUseDependencyRow should only be true if a dependency exists -- cgit From 7e6ad41f327ffc8b3c783d0311f7ba5f1210fe1c Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 20:35:31 +0100 Subject: printerpullpages: #i106423# show a warning in case of empty direct print job --- vcl/inc/vcl/svids.hrc | 1 + vcl/source/gdi/print3.cxx | 12 ++++++++++++ vcl/source/src/print.src | 6 ++++++ 3 files changed, 19 insertions(+) diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index b3fcf9c70dd3..07923e33a4b0 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -164,6 +164,7 @@ #define SV_PRINT_NATIVE_STRINGS 2050 #define SV_PRINT_NOPRINTERWARNING 2051 +#define SV_PRINT_NOCONTENT 2052 #define SV_HELPTEXT_CLOSE 10000 #define SV_HELPTEXT_MINIMIZE 10001 diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 287969a146f3..1617e76cb9b2 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -403,6 +403,18 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr pController->setReversePrint( bReverse ); } + // in direct print case check whether there is anything to print. + // if not, show an errorbox (if appropriate) + if( pController->isShowDialogs() && pController->isDirectPrint() ) + { + if( pController->getFilteredPageCount() == 0 ) + { + ErrorBox aBox( NULL, VclResId( SV_PRINT_NOCONTENT ) ); + aBox.Execute(); + return; + } + } + // check if the printer brings up its own dialog // in that case leave the work to that dialog if( ! pController->getPrinter()->GetCapabilities( PRINTER_CAPABILITIES_EXTERNALDIALOG ) && diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index 83ea13e8478a..c1857544c708 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -471,6 +471,12 @@ ErrorBox SV_PRINT_NOPRINTERWARNING Message [en-US] = "No default printer found.\nPlease choose a printer and try again."; }; +ErrorBox SV_PRINT_NOCONTENT +{ + Title = "%PRODUCTNAME"; + Message [en-US] = "There are no pages to be printed. Please check your document for ranges relevant to printing."; +}; + StringArray SV_PRINT_NATIVE_STRINGS { ItemList [en-US] = -- cgit From 3c50f92e70664eaabc4bbb0e79440ad3a5a7f2ce Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 18 Nov 2009 20:51:54 +0100 Subject: printerpullpages: #i107010# fix persistency issue --- vcl/source/window/printdlg.cxx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index 971c629058c5..c53d19d6d2dc 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -870,12 +870,6 @@ PrintDialog::PrintDialog( Window* i_pParent, const boost::shared_ptr Date: Thu, 19 Nov 2009 18:50:20 +0100 Subject: printerpullpages: #i106560# fix theming / HC --- vcl/source/window/printdlg.cxx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index c53d19d6d2dc..e0c8bdc71caf 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -68,7 +68,10 @@ PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const Re { SetPaintTransparent( TRUE ); SetBackground(); - maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); + if( GetSettings().GetStyleSettings().GetHighContrastMode() ) + maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); + else + maPageVDev.SetBackground( Color( COL_WHITE ) ); } PrintDialog::PrintPreviewWindow::~PrintPreviewWindow() @@ -80,7 +83,10 @@ void PrintDialog::PrintPreviewWindow::DataChanged( const DataChangedEvent& i_rDC // react on settings changed if( i_rDCEvt.GetType() == DATACHANGED_SETTINGS ) { - maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); + if( GetSettings().GetStyleSettings().GetHighContrastMode() ) + maPageVDev.SetBackground( GetSettings().GetStyleSettings().GetWindowColor() ); + else + maPageVDev.SetBackground( Color( COL_WHITE ) ); } Window::DataChanged( i_rDCEvt ); } @@ -206,6 +212,13 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi SetQuickHelpText( aBuf.makeStringAndClear() ); #endif maMtf = i_rNewPreview; + if( GetSettings().GetStyleSettings().GetHighContrastMode() && + GetSettings().GetStyleSettings().GetWindowColor().IsDark() + ) + { + maMtf.ReplaceColors( Color( COL_BLACK ), Color( COL_WHITE ), 30 ); + } + maOrigSize = i_rOrigSize; maReplacementString = i_rReplacement; maPageVDev.SetReferenceDevice( i_nDPIX, i_nDPIY ); -- cgit From 3b6800d565cadc9e0e20da2d9725a87bcb114153 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 19 Nov 2009 18:55:41 +0100 Subject: printerpullpages: #i106192# evaluate error state after failed StartJob --- vcl/source/gdi/print3.cxx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 1617e76cb9b2..d5d8392b2f45 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -588,11 +588,12 @@ bool Printer::StartJob( const rtl::OUString& i_rJobName, boost::shared_ptrsetJobState( view::PrintableState_JOB_FAILED ); - mnError = ImplSalPrinterErrorCodeToVCL( mpPrinter->GetErrorCode() ); if ( !mnError ) mnError = PRINTER_GENERALERROR; + i_pController->setJobState( mnError == PRINTER_ABORT + ? view::PrintableState_JOB_ABORTED + : view::PrintableState_JOB_FAILED ); pSVData->mpDefInst->DestroyPrinter( mpPrinter ); mnCurPage = 0; mnCurPrintPage = 0; -- cgit From 4e0900fa9fae5db6d77fa759bf49164af21b83b9 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 20 Nov 2009 15:27:46 +0100 Subject: printerpullpages: #i91478# improvements for mac native print dialog --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 138 +++++++++----------------- 1 file changed, 47 insertions(+), 91 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 52f6c8c5b575..bde2a595bce1 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -567,7 +567,7 @@ static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) // resize the view itself aUnion.size.height += 10; - aUnion.size.width += 10; + aUnion.size.width += 20; [pView setFrameSize: aUnion.size]; if( aUnion.size.width > rMaxSize.width ) @@ -601,12 +601,34 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) NSView* pCurSubView = [pSubViews objectAtIndex: n]; NSRect aFrame = [pCurSubView frame]; aFrame.origin.y += nDiff; + // give separators the correct width + // separators are currently the only NSBoxes we use + if( [pCurSubView isMemberOfClass: [NSBox class]] ) + { + aFrame.size.width = aTabSize.width - aFrame.origin.x - 10; + } [pCurSubView setFrame: aFrame]; } } } } +static NSControl* createLabel( const rtl::OUString& i_rText ) +{ + NSString* pText = CreateNSString( i_rText ); + NSRect aTextRect = { { 0, 0 }, {20, 15} }; + NSTextField* pTextView = [[NSTextField alloc] initWithFrame: aTextRect]; + [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; + [pTextView setEditable: NO]; + [pTextView setSelectable: NO]; + [pTextView setDrawsBackground: NO]; + [pTextView setBordered: NO]; + [pTextView setStringValue: pText]; + [pTextView sizeToFit]; + [pText release]; + return pTextView; +} + @implementation AquaPrintAccessoryView +(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withController: (vcl::PrinterController*)pController withState: (PrintAccessoryViewState*)pState; @@ -703,7 +725,7 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) // so we have a single accessory view that is tabbed for grouping if( aCtrlType.equalsAscii( "Group" ) || ! pCurParent - || ( aCtrlType.equalsAscii( "Subgroup" ) && nCurY < -200 && ! bIgnore ) + || ( aCtrlType.equalsAscii( "Subgroup" ) && nCurY < -250 && ! bIgnore ) ) { rtl::OUString aGroupTitle( aText ); @@ -736,40 +758,20 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) if( bIgnore ) continue; - // if this is not the first view on the page - // insert a separator - NSArray* pArray = [pCurParent subviews]; - if( pArray && [pArray count] > 0 ) - { - NSRect aSepRect = { { 0, nCurY - 15 }, { 300, 15 } }; - NSBox* pBox = [[NSBox alloc] initWithFrame: aSepRect]; - [pBox setBoxType: NSBoxSeparator]; - [pCurParent addSubview: pBox]; - - nCurY -= 15; - } - - NSString* pText = CreateNSString( aText ); - NSRect aTextRect = { { 0, 0 }, { 300, 15 } }; - NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; - [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; - [pTextView setEditable: NO]; - [pTextView setSelectable: NO]; - [pTextView setDrawsBackground: NO]; - [pTextView setString: pText]; - [pTextView sizeToFit]; // FIXME: this does nothing - [pCurParent addSubview: [pTextView autorelease]]; - - aTextRect = [pTextView frame]; + NSControl* pTextView = createLabel( aText ); + [pCurParent addSubview: [pTextView autorelease]]; + NSRect aTextRect = [pTextView frame]; // move to nCurY aTextRect.origin.y = nCurY - aTextRect.size.height; [pTextView setFrame: aTextRect]; + + NSRect aSepRect = { { aTextRect.size.width + 1, aTextRect.origin.y }, { 100, 6 } }; + NSBox* pBox = [[NSBox alloc] initWithFrame: aSepRect]; + [pBox setBoxType: NSBoxSeparator]; + [pCurParent addSubview: [pBox autorelease]]; // update nCurY nCurY = aTextRect.origin.y - 5; - - // cleanup - [pText release]; } else if( bIgnoreSubgroup || bIgnore ) continue; @@ -813,15 +815,9 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) if( aText.getLength() ) { // add a label - NSString* pText = CreateNSString( aText ); - NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, { 300, 15 } }; - NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; - [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; - [pTextView setEditable: NO]; - [pTextView setSelectable: NO]; - [pTextView setDrawsBackground: NO]; - [pTextView setString: pText]; - [pTextView sizeToFit]; // FIXME: this does nothing + NSControl* pTextView = createLabel( aText ); + NSRect aTextRect = [pTextView frame]; + aTextRect.origin.x = nCurX + nAttachOffset; [pCurParent addSubview: [pTextView autorelease]]; // move to nCurY @@ -833,9 +829,6 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) // indent the radio group relative to the text // nOff = 20; - - // cleanup - [pText release]; } // setup radio matrix @@ -888,32 +881,11 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) } else if( aCtrlType.equalsAscii( "List" ) && pCurParent ) { - NSString* pText = CreateNSString( aText ); - - // measure the text - NSFont* pFont = [NSFont controlContentFontOfSize: 0]; - NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont - forKey: NSFontAttributeName]; - - NSSize aTextSize = [pText sizeWithAttributes: pDict]; - // leave a little space - aTextSize.width += 10; - aTextSize.height += 3; - // don't indent attached lists, looks bad in the existing cases - NSRect aTextRect = { { nCurX /* + nAttachOffset*/, 0 }, aTextSize }; - NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; - [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; - [pTextView setEditable: NO]; - [pTextView setSelectable: NO]; - [pTextView setDrawsBackground: NO]; - [pTextView setString: pText]; - [pTextView setVerticallyResizable: NO]; - [pTextView setHorizontallyResizable: YES]; - [pTextView sizeToFit]; // FIXME: this actually does nothing + NSControl* pTextView = createLabel( aText ); [pCurParent addSubview: [pTextView autorelease]]; - aTextRect = [pTextView frame]; - + NSRect aTextRect = [pTextView frame]; + aTextRect.origin.x = nCurX /* + nAttachOffset*/; // don't indent attached lists, looks bad in the existing cases NSRect aBtnRect = { { nCurX /*+ nAttachOffset*/ + aTextRect.size.width, 0 }, { 0, 15 } }; @@ -959,9 +931,6 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) // update nCurY nCurY = aBtnRect.origin.y - 5; - - // cleanup - [pText release]; } else if( (aCtrlType.equalsAscii( "Edit" ) || aCtrlType.equalsAscii( "Range" )) && pCurParent ) { @@ -969,27 +938,12 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) if( aText.getLength() ) { // add a label - NSString* pText = CreateNSString( aText ); - NSFont* pFont = [NSFont controlContentFontOfSize: 0]; - NSDictionary* pDict = [NSDictionary dictionaryWithObject: pFont - forKey: NSFontAttributeName]; - - NSSize aTextSize = [pText sizeWithAttributes: pDict]; - // leave a little space - aTextSize.width += 10; - aTextSize.height += 3; - - NSRect aTextRect = { { nCurX + nAttachOffset, 0 }, aTextSize }; - NSTextView* pTextView = [[NSTextView alloc] initWithFrame: aTextRect]; - [pTextView setFont: [NSFont controlContentFontOfSize: 0]]; - [pTextView setEditable: NO]; - [pTextView setSelectable: NO]; - [pTextView setDrawsBackground: NO]; - [pTextView setString: pText]; - [pTextView sizeToFit]; // FIXME: this does nothing + NSControl* pTextView = createLabel( aText ); [pCurParent addSubview: [pTextView autorelease]]; // move to nCurY + NSRect aTextRect = [pTextView frame]; + aTextRect.origin.x = nCurX + nAttachOffset; aTextRect.origin.y = nCurY - aTextRect.size.height; [pTextView setFrame: aTextRect]; @@ -997,10 +951,7 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) nCurY = aTextRect.origin.y - 5; // and set the offset for the real edit field - nOff = aTextSize.width + 5; - - // cleanup - [pText release]; + nOff = aTextRect.size.width + 5; } NSRect aFieldRect = { { nCurX + nOff + nAttachOffset, 0 }, { 100, 25 } }; @@ -1097,9 +1048,14 @@ static void adjustTabViews( NSTabView* pTabView, NSSize aTabSize ) DBG_ERROR( "Unsupported UI option" ); } } + pControllerProperties->updateEnableState(); adjustViewAndChildren( pCurParent, aMaxTabSize ); + // leave some space for the preview + if( aMaxTabSize.height < 200 ) + aMaxTabSize.height = 200; + // now reposition everything again so it is upper bound adjustTabViews( pTabView, aMaxTabSize ); -- cgit From 9bf73f92e0645538720958375b2930bead4d8dc7 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 23 Nov 2009 12:38:01 +0100 Subject: printerpullpages: #i91478# base dialog layout on HIG --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 159 +++++++++++++++++++++++--- 1 file changed, 146 insertions(+), 13 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index bde2a595bce1..60fac0dfae29 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -543,8 +543,97 @@ static void filterAccelerator( rtl::OUString& io_rText ) } @end -static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize ) +struct ColumnItem { + NSControl* pControl; + long nOffset; + NSControl* pSubControl; + + ColumnItem( NSControl* i_pControl = nil, long i_nOffset = 0, NSControl* i_pSub = nil ) + : pControl( i_pControl ) + , nOffset( i_nOffset ) + , pSubControl( i_pSub ) + {} + + long getWidth() const + { + long nWidth = 0; + if( pControl ) + { + NSRect aCtrlRect = [pControl frame]; + nWidth = aCtrlRect.size.width; + nWidth += nOffset; + if( pSubControl ) + { + NSRect aSubRect = [pSubControl frame]; + nWidth += aSubRect.size.width; + nWidth += aSubRect.origin.x - (aCtrlRect.origin.x + aCtrlRect.size.width); + } + } + return nWidth; + } +}; + +static void adjustViewAndChildren( NSView* pView, NSSize& rMaxSize, + std::vector< ColumnItem >& rLeftColumn, + std::vector< ColumnItem >& rRightColumn + ) +{ + // balance columns + + // first get overall column widths + long nLeftWidth = 0; + long nRightWidth = 0; + for( size_t i = 0; i < rLeftColumn.size(); i++ ) + { + long nW = rLeftColumn[i].getWidth(); + if( nW > nLeftWidth ) + nLeftWidth = nW; + } + for( size_t i = 0; i < rRightColumn.size(); i++ ) + { + long nW = rRightColumn[i].getWidth(); + if( nW > nRightWidth ) + nRightWidth = nW; + } + + // right align left column + for( size_t i = 0; i < rLeftColumn.size(); i++ ) + { + if( rLeftColumn[i].pControl ) + { + NSRect aCtrlRect = [rLeftColumn[i].pControl frame]; + long nX = nLeftWidth - aCtrlRect.size.width; + if( rLeftColumn[i].pSubControl ) + { + NSRect aSubRect = [rLeftColumn[i].pSubControl frame]; + nX -= aSubRect.size.width + (aSubRect.origin.x - (aCtrlRect.origin.x + aCtrlRect.size.width)); + aSubRect.origin.x = nLeftWidth - aSubRect.size.width; + [rLeftColumn[i].pSubControl setFrame: aSubRect]; + } + aCtrlRect.origin.x = nX; + [rLeftColumn[i].pControl setFrame: aCtrlRect]; + } + } + + // left align right column + for( size_t i = 0; i < rRightColumn.size(); i++ ) + { + if( rRightColumn[i].pControl ) + { + NSRect aCtrlRect = [rRightColumn[i].pControl frame]; + long nX = nLeftWidth + 3; + if( rRightColumn[i].pSubControl ) + { + NSRect aSubRect = [rRightColumn[i].pSubControl frame]; + aSubRect.origin.x = nX + aSubRect.origin.x - aCtrlRect.origin.x; + [rRightColumn[i].pSubControl setFrame: aSubRect]; + } + aCtrlRect.origin.x = nX; + [rRightColumn[i].pControl setFrame: aCtrlRect]; + } + } + NSArray* pSubViews = [pView subviews]; unsigned int nViews = [pSubViews count]; NSRect aUnion = { { 0, 0 }, { 0, 0 } }; @@ -629,6 +718,32 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) return pTextView; } +static void linebreakCell( NSCell* pBtn, const rtl::OUString& i_rText ) +{ + NSString* pText = CreateNSString( i_rText ); + [pBtn setTitle: pText]; + [pText release]; + NSSize aSize = [pBtn cellSize]; + if( aSize.width > 280 ) + { + // need two lines + // FIXME: dummy code, should really use linebreaking service instead + const sal_Unicode* pStr = i_rText.getStr(); + sal_Int32 nLen = i_rText.getLength(); + sal_Int32 nIndex = nLen / 2; + while( nIndex < nLen && pStr[nIndex] != ' ' ) + nIndex++; + if( nIndex < nLen ) + { + rtl::OUStringBuffer aBuf( i_rText ); + aBuf.setCharAt( nIndex, '\n' ); + pText = CreateNSString( aBuf.makeStringAndClear() ); + [pBtn setTitle: pText]; + [pText release]; + } + } +} + @implementation AquaPrintAccessoryView +(NSObject*)setupPrinterPanel: (NSPrintOperation*)pOp withController: (vcl::PrinterController*)pController withState: (PrintAccessoryViewState*)pState; @@ -641,7 +756,7 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) long nCurY = 0; long nCurX = 0; NSRect aViewFrame = { { 0, 0 }, {600, 400 } }; - NSRect aTabViewFrame = { { 200, 0 }, {400, 400 } }; + NSRect aTabViewFrame = { { 190, 0 }, {410, 400 } }; NSSize aMaxTabSize = { 0, 0 }; NSView* pAccessoryView = [[NSView alloc] initWithFrame: aViewFrame]; NSTabView* pTabView = [[NSTabView alloc] initWithFrame: aTabViewFrame]; @@ -651,6 +766,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) ControllerProperties* pControllerProperties = new ControllerProperties( pController, pOp, pAccessoryView, pTabView, pState ); ControlTarget* pCtrlTarget = [[ControlTarget alloc] initWithControllerMap: pControllerProperties]; + + std::vector< ColumnItem > aLeftColumn, aRightColumn; for( int i = 0; i < rOptions.getLength(); i++ ) { @@ -733,7 +850,7 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) aGroupTitle = pControllerProperties->getMoreString(); // set size of current parent if( pCurParent ) - adjustViewAndChildren( pCurParent, aMaxTabSize ); + adjustViewAndChildren( pCurParent, aMaxTabSize, aLeftColumn, aRightColumn ); // new tab item if( ! aText.getLength() ) @@ -750,6 +867,9 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) nCurX = 20; // reset Y nCurY = 0; + // clear columns + aLeftColumn.clear(); + aRightColumn.clear(); } if( aCtrlType.equalsAscii( "Subgroup" ) && pCurParent ) @@ -777,19 +897,20 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) continue; else if( aCtrlType.equalsAscii( "Bool" ) && pCurParent ) { - NSString* pText = CreateNSString( aText ); NSRect aCheckRect = { { nCurX + nAttachOffset, 0 }, { 0, 15 } }; NSButton* pBtn = [[NSButton alloc] initWithFrame: aCheckRect]; - [pBtn setButtonType: NSSwitchButton]; - [pBtn setTitle: pText]; + [pBtn setButtonType: NSSwitchButton]; sal_Bool bVal = sal_False; PropertyValue* pVal = pController->getValue( aPropertyName ); if( pVal ) pVal->Value >>= bVal; [pBtn setState: bVal ? NSOnState : NSOffState]; + linebreakCell( [pBtn cell], aText ); [pBtn sizeToFit]; [pCurParent addSubview: [pBtn autorelease]]; + aRightColumn.push_back( ColumnItem( pBtn ) ); + // connect target [pBtn setTarget: pCtrlTarget]; [pBtn setAction: @selector(triggered:)]; @@ -805,9 +926,6 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) // update nCurY nCurY = aCheckRect.origin.y - 5; - - // cleanup - [pText release]; } else if( aCtrlType.equalsAscii( "Radio" ) && pCurParent ) { @@ -819,6 +937,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) NSRect aTextRect = [pTextView frame]; aTextRect.origin.x = nCurX + nAttachOffset; [pCurParent addSubview: [pTextView autorelease]]; + + aLeftColumn.push_back( ColumnItem( pTextView ) ); // move to nCurY aTextRect.origin.y = nCurY - aTextRect.size.height; @@ -853,15 +973,16 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) { NSCell* pCell = [pCells objectAtIndex: m]; filterAccelerator( aChoices[m] ); - NSString* pTitle = CreateNSString( aChoices[m] ); - [pCell setTitle: pTitle]; + linebreakCell( pCell, aChoices[m] ); + //NSString* pTitle = CreateNSString( aChoices[m] ); + //[pCell setTitle: pTitle]; // connect target and action [pCell setTarget: pCtrlTarget]; [pCell setAction: @selector(triggered:)]; int nTag = pControllerProperties->addNameAndValueTag( aPropertyName, m ); pControllerProperties->addObservedControl( pCell ); [pCell setTag: nTag]; - [pTitle release]; + //[pTitle release]; // set current selection if( nSelectVal == m ) [pMatrix selectCellAtRow: m column: 0]; @@ -874,6 +995,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) [pMatrix setFrame: aRadioRect]; [pCurParent addSubview: [pMatrix autorelease]]; + aRightColumn.push_back( ColumnItem( pMatrix ) ); + // update nCurY nCurY = aRadioRect.origin.y - 5; @@ -884,6 +1007,7 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) // don't indent attached lists, looks bad in the existing cases NSControl* pTextView = createLabel( aText ); [pCurParent addSubview: [pTextView autorelease]]; + aLeftColumn.push_back( ColumnItem( pTextView ) ); NSRect aTextRect = [pTextView frame]; aTextRect.origin.x = nCurX /* + nAttachOffset*/; @@ -915,6 +1039,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) [pBtn sizeToFit]; [pCurParent addSubview: [pBtn autorelease]]; + + aRightColumn.push_back( ColumnItem( pBtn ) ); // connect target and action [pBtn setTarget: pCtrlTarget]; @@ -941,6 +1067,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) NSControl* pTextView = createLabel( aText ); [pCurParent addSubview: [pTextView autorelease]]; + aLeftColumn.push_back( ColumnItem( pTextView ) ); + // move to nCurY NSRect aTextRect = [pTextView frame]; aTextRect.origin.x = nCurX + nAttachOffset; @@ -962,6 +1090,8 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) [pFieldView sizeToFit]; // FIXME: this does nothing [pCurParent addSubview: [pFieldView autorelease]]; + aRightColumn.push_back( ColumnItem( pFieldView ) ); + // add the field to observed controls for enabled state changes // also add a tag just for this purpose pControllerProperties->addObservedControl( pFieldView ); @@ -986,6 +1116,9 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) [pStep setValueWraps: NO]; [pStep setTag: nTag]; [pCurParent addSubview: [pStep autorelease]]; + + aRightColumn.back().pSubControl = pStep; + pControllerProperties->addObservedControl( pStep ); [pStep setTarget: pCtrlTarget]; [pStep setAction: @selector(triggered:)]; @@ -1050,7 +1183,7 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) } pControllerProperties->updateEnableState(); - adjustViewAndChildren( pCurParent, aMaxTabSize ); + adjustViewAndChildren( pCurParent, aMaxTabSize, aLeftColumn, aRightColumn ); // leave some space for the preview if( aMaxTabSize.height < 200 ) -- cgit From b0fe07fec29262fdc5e1aaf97812caadbb9d5c15 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 23 Nov 2009 13:30:17 +0100 Subject: printerpullpages: #i106836# allow less strict parsing of passed ranges string --- tools/inc/tools/multisel.hxx | 4 ++-- tools/source/memtools/multisel.cxx | 25 ++++++++++++++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/tools/inc/tools/multisel.hxx b/tools/inc/tools/multisel.hxx index bd2f7023bf8d..9de3cc172e70 100644 --- a/tools/inc/tools/multisel.hxx +++ b/tools/inc/tools/multisel.hxx @@ -131,7 +131,7 @@ class TOOLS_DLLPUBLIC StringRangeEnumerator sal_Int32 mnMax; sal_Int32 mnOffset; - bool insertRange( sal_Int32 nFirst, sal_Int32 nLast, bool bSequence ); + bool insertRange( sal_Int32 nFirst, sal_Int32 nLast, bool bSequence, bool bMayAdjust ); bool checkValue( sal_Int32, const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; public: class TOOLS_DLLPUBLIC Iterator @@ -177,7 +177,7 @@ public: sal_Int32 getLogicalOffset() const { return mnOffset; } void setLogicalOffset( sal_Int32 i_nOffset ) { mnOffset = i_nOffset; } - bool setRange( const rtl::OUString& i_rNewRange ); + bool setRange( const rtl::OUString& i_rNewRange, bool i_bStrict = false ); bool hasValue( sal_Int32 nValue, const std::set< sal_Int32 >* i_pPossibleValues = NULL ) const; diff --git a/tools/source/memtools/multisel.cxx b/tools/source/memtools/multisel.cxx index 4f5ccbbabeae..5fe920b6998a 100644 --- a/tools/source/memtools/multisel.cxx +++ b/tools/source/memtools/multisel.cxx @@ -901,7 +901,7 @@ bool StringRangeEnumerator::checkValue( sal_Int32 i_nValue, const std::set< sal_ return true; } -bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, bool bSequence ) +bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, bool bSequence, bool bMayAdjust ) { bool bSuccess = true; if( bSequence ) @@ -910,6 +910,17 @@ bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, i_nFirst = mnMin; if( i_nLast == -1 ) i_nLast = mnMax; + if( bMayAdjust ) + { + if( i_nFirst < mnMin ) + i_nFirst = mnMin; + if( i_nFirst > mnMax ) + i_nFirst = mnMax; + if( i_nLast < mnMin ) + i_nLast = mnMin; + if( i_nLast > mnMax ) + i_nLast = mnMax; + } if( checkValue( i_nFirst ) && checkValue( i_nLast ) ) { maSequence.push_back( Range( i_nFirst, i_nLast ) ); @@ -947,7 +958,7 @@ bool StringRangeEnumerator::insertRange( sal_Int32 i_nFirst, sal_Int32 i_nLast, return bSuccess; } -bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) +bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange, bool i_bStrict ) { mnCount = 0; maSequence.clear(); @@ -957,7 +968,7 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) { if( mnMin >= 0 && mnMax >= 0 ) { - insertRange( mnMin, mnMax, mnMin != mnMax ); + insertRange( mnMin, mnMax, mnMin != mnMax, ! i_bStrict ); } return true; } @@ -977,7 +988,7 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) { if( bSequence ) { - if( ! insertRange( nLastNumber, nNumber, true ) ) + if( ! insertRange( nLastNumber, nNumber, true, ! i_bStrict ) && i_bStrict ) { bSuccess = false; break; @@ -986,7 +997,7 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) } else { - if( ! insertRange( nNumber, nNumber, false ) ) + if( ! insertRange( nNumber, nNumber, false, ! i_bStrict ) && i_bStrict ) { bSuccess = false; break; @@ -1017,7 +1028,7 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) if( bInsertRange ) { - if( ! insertRange( nLastNumber, nNumber, bSequence ) ) + if( ! insertRange( nLastNumber, nNumber, bSequence, ! i_bStrict ) && i_bStrict ) { bSuccess = false; break; @@ -1029,7 +1040,7 @@ bool StringRangeEnumerator::setRange( const rtl::OUString& i_rNewRange ) pInput++; } // insert last entries - insertRange( nLastNumber, nNumber, bSequence ); + insertRange( nLastNumber, nNumber, bSequence, ! i_bStrict ); return bSuccess; } -- cgit From 5d7cea9f0f556b7e88921b206683f9c968261a50 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 23 Nov 2009 15:45:18 +0100 Subject: printerpullpages: #i91478# proper word breaking --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 60fac0dfae29..9e37c0632f4e 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -37,11 +37,16 @@ #include "vcl/image.hxx" #include "vcl/virdev.hxx" #include "vcl/svdata.hxx" +#include "vcl/svapp.hxx" +#include "vcl/unohelp.hxx" #include "vcl/svids.hrc" #include "tools/resary.hxx" +#include "com/sun/star/i18n/XBreakIterator.hpp" +#include "com/sun/star/i18n/WordType.hpp" + #include using namespace vcl; @@ -718,6 +723,21 @@ static NSControl* createLabel( const rtl::OUString& i_rText ) return pTextView; } +static sal_Int32 findBreak( const rtl::OUString& i_rText, sal_Int32 i_nPos ) +{ + sal_Int32 nRet = i_rText.getLength(); + Reference< i18n::XBreakIterator > xBI( vcl::unohelper::CreateBreakIterator() ); + if( xBI.is() ) + { + i18n::Boundary aBoundary = xBI->getWordBoundary( i_rText, i_nPos, + Application::GetSettings().GetLocale(), + i18n::WordType::ANYWORD_IGNOREWHITESPACES, + sal_True ); + nRet = aBoundary.endPos; + } + return nRet; +} + static void linebreakCell( NSCell* pBtn, const rtl::OUString& i_rText ) { NSString* pText = CreateNSString( i_rText ); @@ -727,12 +747,9 @@ static void linebreakCell( NSCell* pBtn, const rtl::OUString& i_rText ) if( aSize.width > 280 ) { // need two lines - // FIXME: dummy code, should really use linebreaking service instead - const sal_Unicode* pStr = i_rText.getStr(); sal_Int32 nLen = i_rText.getLength(); sal_Int32 nIndex = nLen / 2; - while( nIndex < nLen && pStr[nIndex] != ' ' ) - nIndex++; + nIndex = findBreak( i_rText, nIndex ); if( nIndex < nLen ) { rtl::OUStringBuffer aBuf( i_rText ); -- cgit From 78f36b84e4e181fe5d0bcb5cc8606a56df256982 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 23 Nov 2009 19:08:31 +0100 Subject: vcl108: #i106704# fix Length3 entry for Type1 fonts, also merge fix for issue 106572 --- vcl/source/gdi/pdfwriter_impl.cxx | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index e7ee18ec7705..146196e86877 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -2973,24 +2973,18 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont } nEndBinaryIndex = nIndex; - // and count forward again to the point where we have nFound '0' - // to get the corect value for nLength3 - sal_Int32 nLength3 = 0; - sal_Int32 nL3Index = nIndex; - while( nFound && nL3Index < nFontLen ) + // nLength3 is the rest of the file - excluding any section headers + sal_Int32 nLength3 = nFontLen - nIndex; + for( it = aSections.begin(); it != aSections.end(); ++it ) { - for( it = aSections.begin(); it != aSections.end() && (nL3Index < *it || nL3Index > ((*it) + 5) ); ++it ) - ; - if( it == aSections.end() ) + if( *it >= nIndex ) { - // inside the 512 '0' block there may only be whitespace - // according to T1 spec; probably it would be to simple - // if all fonts complied - if( pFontData[nL3Index] == '0' ) - nFound--; - nLength3++; + // special case: nIndex inside a section marker + if( nIndex >= *it ) + nLength3 -= (*it)+5 - nIndex; + else + nLength3 -= 5; } - nL3Index++; } // search for beginning of binary section @@ -3612,6 +3606,7 @@ sal_Int32 PDFWriterImpl::emitFontDescriptor( const ImplFontData* pFont, FontSubs break; case FontSubsetInfo::TYPE1_PFA: case FontSubsetInfo::TYPE1_PFB: + case FontSubsetInfo::ANY_TYPE1: break; default: DBG_ERROR( "unknown fonttype in PDF font descriptor" ); -- cgit From 739473cd061d8fbf91ae232d0e3a4ec68a10f174 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 24 Nov 2009 17:40:41 +0100 Subject: printerpullpages: #i107065# ensure correct mapmode for borders on subpages --- vcl/source/gdi/print3.cxx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index d5d8392b2f45..2b16d2c611fd 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -776,7 +776,7 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD io_rSubPage.Clip( i_rClipRect ); // save gstate - o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION | PUSH_MAPMODE ) ); + o_rMtf.AddAction( new MetaPushAction( PUSH_ALL ) ); // clip to page rect o_rMtf.AddAction( new MetaClipRegionAction( Region( i_rClipRect ), TRUE ) ); @@ -785,17 +785,24 @@ static void appendSubPage( GDIMetaFile& o_rMtf, const Rectangle& i_rClipRect, GD io_rSubPage.WindStart(); io_rSubPage.Play( o_rMtf ); + // restore gstate + o_rMtf.AddAction( new MetaPopAction() ); + // draw a border if( i_bDrawBorder ) { + // save gstate + o_rMtf.AddAction( new MetaPushAction( PUSH_LINECOLOR | PUSH_FILLCOLOR | PUSH_CLIPREGION | PUSH_MAPMODE ) ); + o_rMtf.AddAction( new MetaMapModeAction( MapMode( MAP_100TH_MM ) ) ); + Rectangle aBorderRect( i_rClipRect ); o_rMtf.AddAction( new MetaLineColorAction( Color( COL_BLACK ), TRUE ) ); o_rMtf.AddAction( new MetaFillColorAction( Color( COL_TRANSPARENT ), FALSE ) ); o_rMtf.AddAction( new MetaRectAction( aBorderRect ) ); - } - // restore gstate - o_rMtf.AddAction( new MetaPopAction() ); + // restore gstate + o_rMtf.AddAction( new MetaPopAction() ); + } } PrinterController::PageSize PrinterController::getFilteredPageFile( int i_nFilteredPage, GDIMetaFile& o_rMtf, bool i_bMayUseCache ) -- cgit From ca116ee69b6c238e7243002bf1650332dc098902 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 25 Nov 2009 19:23:34 +0100 Subject: vcl108: #i106547# active/inactive scrollbars --- vcl/aqua/inc/salgdi.h | 1 + vcl/aqua/source/gdi/salnativewidgets.cxx | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/vcl/aqua/inc/salgdi.h b/vcl/aqua/inc/salgdi.h index 4933dbc48586..33e4862c258c 100644 --- a/vcl/aqua/inc/salgdi.h +++ b/vcl/aqua/inc/salgdi.h @@ -359,6 +359,7 @@ private: void ApplyXorContext(); void Pattern50Fill(); UInt32 getState( ControlState nState ); + UInt32 getTrackState( ControlState nState ); }; class XorEmulation diff --git a/vcl/aqua/source/gdi/salnativewidgets.cxx b/vcl/aqua/source/gdi/salnativewidgets.cxx index 754358823a93..1536299331cb 100644 --- a/vcl/aqua/source/gdi/salnativewidgets.cxx +++ b/vcl/aqua/source/gdi/salnativewidgets.cxx @@ -450,6 +450,15 @@ UInt32 AquaSalGraphics::getState( ControlState nState ) return kThemeStateActive; } +UInt32 AquaSalGraphics::getTrackState( ControlState nState ) +{ + bool bDrawActive = mpFrame ? ([mpFrame->getWindow() isKeyWindow] ? true : false) : true; + if( (nState & CTRL_STATE_ENABLED) == 0 || ! bDrawActive ) + return kThemeTrackInactive; + + return kThemeTrackActive; +} + /* * DrawNativeControl() * @@ -767,7 +776,10 @@ BOOL AquaSalGraphics::drawNativeControl(ControlType nType, aTrackInfo.attributes = kThemeTrackHorizontal; if( Application::GetSettings().GetLayoutRTL() ) aTrackInfo.attributes |= kThemeTrackRightToLeft; - aTrackInfo.enableState = (nState & CTRL_STATE_ENABLED) ? kThemeTrackActive : kThemeTrackInactive; + aTrackInfo.enableState = getTrackState( nState ); + // the intro bitmap never gets key anyway; we want to draw that enabled + if( nType == CTRL_INTROPROGRESS ) + aTrackInfo.enableState = kThemeTrackActive; aTrackInfo.filler1 = 0; aTrackInfo.trackInfo.progress.phase = static_cast(CFAbsoluteTimeGetCurrent()*10.0); @@ -799,7 +811,7 @@ BOOL AquaSalGraphics::drawNativeControl(ControlType nType, aTrackDraw.attributes = kThemeTrackShowThumb; if( nPart == PART_DRAW_BACKGROUND_HORZ ) aTrackDraw.attributes |= kThemeTrackHorizontal; - aTrackDraw.enableState = kThemeTrackActive; + aTrackDraw.enableState = getTrackState( nState ); ScrollBarTrackInfo aScrollInfo; aScrollInfo.viewsize = pScrollbarVal->mnVisibleSize; -- cgit From 1c46a6da7e010243817963156cb45b8f20ebc8fa Mon Sep 17 00:00:00 2001 From: "Ocke Janssen [oj]" Date: Thu, 26 Nov 2009 08:42:51 +0100 Subject: dba33b: defines for debug was missing --- comphelper/source/property/property.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/comphelper/source/property/property.cxx b/comphelper/source/property/property.cxx index 14b3b8f9169d..17949b9889dd 100644 --- a/comphelper/source/property/property.cxx +++ b/comphelper/source/property/property.cxx @@ -67,7 +67,9 @@ namespace comphelper using ::com::sun::star::uno::cpp_queryInterface; using ::com::sun::star::uno::cpp_acquire; using ::com::sun::star::uno::cpp_release; +#if OSL_DEBUG_LEVEL > 0 using ::com::sun::star::lang::XServiceInfo; +#endif using ::com::sun::star::uno::UNO_QUERY; /** === end UNO using === **/ namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute; -- cgit From 05e8ff4c39b2a603b86e7fa587cbaa096332182d Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 26 Nov 2009 11:15:10 +0100 Subject: vcl108: #i107228# fix an uninitalized warning from valgrind (thanks cmc) --- vcl/source/window/status.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/vcl/source/window/status.cxx b/vcl/source/window/status.cxx index 4aaef6a707b1..a4c067061c30 100644 --- a/vcl/source/window/status.cxx +++ b/vcl/source/window/status.cxx @@ -156,6 +156,7 @@ void StatusBar::ImplInit( Window* pParent, WinBits nStyle ) mbProgressMode = FALSE; mbInUserDraw = FALSE; mbBottomBorder = FALSE; + mnItemsWidth = STATUSBAR_OFFSET_X; mnDX = 0; mnDY = 0; mnCalcHeight = 0; -- cgit From 8b2c1496752e50702b5e7d015cbf55594f220b21 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 27 Nov 2009 12:55:08 +0100 Subject: printerpullpages: #i107119# add a tooltip to the preview window --- vcl/inc/vcl/prndlg.hxx | 1 + vcl/inc/vcl/svids.hrc | 1 + vcl/source/src/print.src | 6 ++++++ vcl/source/window/printdlg.cxx | 8 +++++--- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/vcl/inc/vcl/prndlg.hxx b/vcl/inc/vcl/prndlg.hxx index 57a1e32df6d3..f1b69e1ca3aa 100644 --- a/vcl/inc/vcl/prndlg.hxx +++ b/vcl/inc/vcl/prndlg.hxx @@ -60,6 +60,7 @@ namespace vcl Size maOrigSize; VirtualDevice maPageVDev; rtl::OUString maReplacementString; + rtl::OUString maToolTipString; public: PrintPreviewWindow( Window* pParent, const ResId& ); virtual ~PrintPreviewWindow(); diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 07923e33a4b0..695fa6f849e8 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -97,6 +97,7 @@ #define SV_PRINT_PRT_COMMENT 13 #define SV_PRINT_TOFILE_TXT 14 #define SV_PRINT_DEFPRT_TXT 15 +#define SV_PRINT_PRINTPREVIEW_TXT 16 #define SV_PRINT_TAB_NUP 1 #define SV_PRINT_PRT_NUP_LAYOUT_FL 1 diff --git a/vcl/source/src/print.src b/vcl/source/src/print.src index c1857544c708..0125c0dfbeb3 100644 --- a/vcl/source/src/print.src +++ b/vcl/source/src/print.src @@ -118,6 +118,12 @@ ModalDialog SV_DLG_PRINT Text [en-US] = "Default printer"; }; + + String SV_PRINT_PRINTPREVIEW_TXT + { + Text [en-US] = "Print preview"; + }; + TabPage SV_PRINT_TAB_NUP { Text [en-US] = "Page Layout"; diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index e0c8bdc71caf..daf25324e263 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -65,6 +65,7 @@ PrintDialog::PrintPreviewWindow::PrintPreviewWindow( Window* i_pParent, const Re : Window( i_pParent, i_rId ) , maOrigSize( 10, 10 ) , maPageVDev( *this ) + , maToolTipString( String( VclResId( SV_PRINT_PRINTPREVIEW_TXT ) ) ) { SetPaintTransparent( TRUE ); SetBackground(); @@ -202,15 +203,16 @@ void PrintDialog::PrintPreviewWindow::setPreview( const GDIMetaFile& i_rNewPrevi sal_Int32 i_nDPIY ) { - #if OSL_DEBUG_LEVEL > 0 rtl::OUStringBuffer aBuf( 256 ); - aBuf.appendAscii( "PageSize: " ); + aBuf.append( maToolTipString ); + #if OSL_DEBUG_LEVEL > 0 + aBuf.appendAscii( "\n---\nPageSize: " ); aBuf.append( sal_Int32( i_rOrigSize.Width()/100) ); aBuf.appendAscii( "mm x " ); aBuf.append( sal_Int32( i_rOrigSize.Height()/100) ); aBuf.appendAscii( "mm" ); - SetQuickHelpText( aBuf.makeStringAndClear() ); #endif + SetQuickHelpText( aBuf.makeStringAndClear() ); maMtf = i_rNewPreview; if( GetSettings().GetStyleSettings().GetHighContrastMode() && GetSettings().GetStyleSettings().GetWindowColor().IsDark() -- cgit From dc5c1da812d3feecd465cf81506d1bea82b7c6c8 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 27 Nov 2009 13:54:10 +0100 Subject: vcl108: #i107260# clipboard shutdown (thanks cmc) --- vcl/unx/source/dtrans/X11_dndcontext.cxx | 12 +- vcl/unx/source/dtrans/X11_dndcontext.hxx | 20 ++-- vcl/unx/source/dtrans/X11_selection.cxx | 192 +++++++++++++++++++++---------- vcl/unx/source/dtrans/X11_selection.hxx | 100 +++++++++------- vcl/unx/source/dtrans/bmp.cxx | 2 +- vcl/unx/source/dtrans/bmp.hxx | 2 + vcl/util/makefile.mk | 1 + 7 files changed, 209 insertions(+), 120 deletions(-) diff --git a/vcl/unx/source/dtrans/X11_dndcontext.cxx b/vcl/unx/source/dtrans/X11_dndcontext.cxx index 59832c27c2a7..71aebde5b7af 100644 --- a/vcl/unx/source/dtrans/X11_dndcontext.cxx +++ b/vcl/unx/source/dtrans/X11_dndcontext.cxx @@ -42,8 +42,8 @@ using namespace x11; */ DropTargetDropContext::DropTargetDropContext( - Window aDropWindow, - Time aTimestamp, + XLIB_Window aDropWindow, + XLIB_Time aTimestamp, SelectionManager& rManager ) : m_aDropWindow( aDropWindow ), m_nTimestamp( aTimestamp ), @@ -77,8 +77,8 @@ void DropTargetDropContext::dropComplete( sal_Bool success ) throw() */ DropTargetDragContext::DropTargetDragContext( - Window aDropWindow, - Time aTimestamp, + XLIB_Window aDropWindow, + XLIB_Time aTimestamp, SelectionManager& rManager ) : m_aDropWindow( aDropWindow ), m_nTimestamp( aTimestamp ), @@ -106,8 +106,8 @@ void DropTargetDragContext::rejectDrag() throw() */ DragSourceContext::DragSourceContext( - Window aDropWindow, - Time aTimestamp, + XLIB_Window aDropWindow, + XLIB_Time aTimestamp, SelectionManager& rManager ) : m_aDropWindow( aDropWindow ), m_nTimestamp( aTimestamp ), diff --git a/vcl/unx/source/dtrans/X11_dndcontext.hxx b/vcl/unx/source/dtrans/X11_dndcontext.hxx index f2ecb7b0841b..3626b86d8617 100644 --- a/vcl/unx/source/dtrans/X11_dndcontext.hxx +++ b/vcl/unx/source/dtrans/X11_dndcontext.hxx @@ -36,7 +36,9 @@ #include #include +#include "tools/prex.h" #include +#include "tools/postx.h" using namespace com::sun::star::uno; @@ -49,12 +51,12 @@ namespace x11 { ::com::sun::star::datatransfer::dnd::XDropTargetDropContext > { - Window m_aDropWindow; - Time m_nTimestamp; + XLIB_Window m_aDropWindow; + XLIB_Time m_nTimestamp; SelectionManager& m_rManager; Reference< XInterface > m_xManagerRef; public: - DropTargetDropContext( Window, Time, SelectionManager& ); + DropTargetDropContext( XLIB_Window, XLIB_Time, SelectionManager& ); virtual ~DropTargetDropContext(); // XDropTargetDropContext @@ -68,12 +70,12 @@ namespace x11 { ::com::sun::star::datatransfer::dnd::XDropTargetDragContext > { - Window m_aDropWindow; - Time m_nTimestamp; + XLIB_Window m_aDropWindow; + XLIB_Time m_nTimestamp; SelectionManager& m_rManager; Reference< XInterface > m_xManagerRef; public: - DropTargetDragContext( Window, Time, SelectionManager& ); + DropTargetDragContext( XLIB_Window, XLIB_Time, SelectionManager& ); virtual ~DropTargetDragContext(); // XDropTargetDragContext @@ -86,12 +88,12 @@ namespace x11 { ::com::sun::star::datatransfer::dnd::XDragSourceContext > { - Window m_aDropWindow; - Time m_nTimestamp; + XLIB_Window m_aDropWindow; + XLIB_Time m_nTimestamp; SelectionManager& m_rManager; Reference< XInterface > m_xManagerRef; public: - DragSourceContext( Window, Time, SelectionManager& ); + DragSourceContext( XLIB_Window, XLIB_Time, SelectionManager& ); virtual ~DragSourceContext(); // XDragSourceContext diff --git a/vcl/unx/source/dtrans/X11_selection.cxx b/vcl/unx/source/dtrans/X11_selection.cxx index c6036ae4f78e..07f2cfd5e087 100644 --- a/vcl/unx/source/dtrans/X11_selection.cxx +++ b/vcl/unx/source/dtrans/X11_selection.cxx @@ -35,11 +35,13 @@ #include #include #include +#include "tools/prex.h" #include #include #include #include #include +#include "tools/postx.h" #if defined(LINUX) || defined(NETBSD) || defined (FREEBSD) #include #else @@ -53,6 +55,8 @@ #include #include +#include "vcl/svapp.hxx" + // pointer bitmaps #include #include @@ -66,9 +70,9 @@ #include #include #include -#ifndef OSL_PROCESS_H #include -#endif + +#include #define DRAG_EVENT_MASK ButtonPressMask |\ ButtonReleaseMask |\ @@ -81,6 +85,7 @@ using namespace com::sun::star::datatransfer::dnd; using namespace com::sun::star::lang; using namespace com::sun::star::awt; using namespace com::sun::star::uno; +using namespace com::sun::star::frame; using namespace cppu; using namespace osl; using namespace rtl; @@ -280,7 +285,7 @@ SelectionManager::SelectionManager() : m_aDragRunning.reset(); } -Cursor SelectionManager::createCursor( const char* pPointerData, const char* pMaskData, int width, int height, int hotX, int hotY ) +XLIB_Cursor SelectionManager::createCursor( const char* pPointerData, const char* pMaskData, int width, int height, int hotX, int hotY ) { Pixmap aPointer; Pixmap aMask; @@ -306,7 +311,7 @@ Cursor SelectionManager::createCursor( const char* pPointerData, const char* pMa pMaskData, width, height ); - Cursor aCursor = + XLIB_Cursor aCursor = XCreatePixmapCursor( m_pDisplay, aPointer, aMask, &aBlack, &aWhite, hotX, @@ -928,7 +933,7 @@ bool SelectionManager::getPasteData( Atom selection, Atom type, Sequence< sal_In if( it == m_aSelections.end() ) return false; - Window aSelectionOwner = XGetSelectionOwner( m_pDisplay, selection ); + XLIB_Window aSelectionOwner = XGetSelectionOwner( m_pDisplay, selection ); if( aSelectionOwner == None ) return false; if( aSelectionOwner == m_aWindow ) @@ -1480,7 +1485,7 @@ static sal_Size GetTrueFormatSize(int nFormat) } bool SelectionManager::sendData( SelectionAdaptor* pAdaptor, - Window requestor, + XLIB_Window requestor, Atom target, Atom property, Atom selection ) @@ -1587,7 +1592,7 @@ bool SelectionManager::sendData( SelectionAdaptor* pAdaptor, { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "using INCR protocol\n" ); - std::hash_map< Window, std::hash_map< Atom, IncrementalTransfer > >::const_iterator win_it = m_aIncrementals.find( requestor ); + std::hash_map< XLIB_Window, std::hash_map< Atom, IncrementalTransfer > >::const_iterator win_it = m_aIncrementals.find( requestor ); if( win_it != m_aIncrementals.end() ) { std::hash_map< Atom, IncrementalTransfer >::const_iterator inc_it = win_it->second.find( property ); @@ -1986,7 +1991,7 @@ bool SelectionManager::handleSendPropertyNotify( XPropertyEvent& rNotify ) // feed incrementals if( rNotify.state == PropertyDelete ) { - std::hash_map< Window, std::hash_map< Atom, IncrementalTransfer > >::iterator it; + std::hash_map< XLIB_Window, std::hash_map< Atom, IncrementalTransfer > >::iterator it; it = m_aIncrementals.find( rNotify.window ); if( it != m_aIncrementals.end() ) { @@ -2168,12 +2173,12 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) ResettableMutexGuard aGuard(m_aMutex); // handle drop related events - Window aSource = rMessage.data.l[0]; - Window aTarget = rMessage.window; + XLIB_Window aSource = rMessage.data.l[0]; + XLIB_Window aTarget = rMessage.window; bool bHandled = false; - ::std::hash_map< Window, DropTargetEntry >::iterator it = + ::std::hash_map< XLIB_Window, DropTargetEntry >::iterator it = m_aDropTargets.find( aTarget ); #if OSL_DEBUG_LEVEL > 1 @@ -2187,7 +2192,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) fprintf( stderr, "but no target found\n" ); else if( ! it->second.m_pTarget->m_bActive ) fprintf( stderr, "but target is inactive\n" ); - else if( m_aDropEnterEvent.data.l[0] != None && (Window)m_aDropEnterEvent.data.l[0] != aSource ) + else if( m_aDropEnterEvent.data.l[0] != None && (XLIB_Window)m_aDropEnterEvent.data.l[0] != aSource ) fprintf( stderr, "but source 0x%lx is unknown (expected 0x%lx or 0)\n", aSource, m_aDropEnterEvent.data.l[0] ); else fprintf( stderr, "processing.\n" ); @@ -2208,7 +2213,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) if( it != m_aDropTargets.end() && it->second.m_pTarget->m_bActive && - ( m_aDropEnterEvent.data.l[0] == None || Window(m_aDropEnterEvent.data.l[0]) == aSource ) + ( m_aDropEnterEvent.data.l[0] == None || XLIB_Window(m_aDropEnterEvent.data.l[0]) == aSource ) ) { if( rMessage.message_type == m_nXdndEnter ) @@ -2224,7 +2229,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) } else if( rMessage.message_type == m_nXdndPosition && - aSource == Window(m_aDropEnterEvent.data.l[0]) + aSource == XLIB_Window(m_aDropEnterEvent.data.l[0]) ) { bHandled = true; @@ -2232,7 +2237,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) if( ! m_bDropEnterSent ) m_nDropTimestamp = m_nDropTime; - Window aChild; + XLIB_Window aChild; XTranslateCoordinates( m_pDisplay, it->second.m_aRootWindow, it->first, @@ -2280,7 +2285,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) } else if( rMessage.message_type == m_nXdndLeave && - aSource == Window(m_aDropEnterEvent.data.l[0]) + aSource == XLIB_Window(m_aDropEnterEvent.data.l[0]) ) { bHandled = true; @@ -2298,7 +2303,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) } else if( rMessage.message_type == m_nXdndDrop && - aSource == Window(m_aDropEnterEvent.data.l[0]) + aSource == XLIB_Window(m_aDropEnterEvent.data.l[0]) ) { bHandled = true; @@ -2345,7 +2350,7 @@ bool SelectionManager::handleDropEvent( XClientMessageEvent& rMessage ) * methods for XDropTargetDropContext */ -void SelectionManager::dropComplete( sal_Bool bSuccess, Window aDropWindow, Time ) +void SelectionManager::dropComplete( sal_Bool bSuccess, XLIB_Window aDropWindow, XLIB_Time ) { ClearableMutexGuard aGuard(m_aMutex); @@ -2542,21 +2547,21 @@ bool SelectionManager::updateDragAction( int modifierState ) // ------------------------------------------------------------------------ -void SelectionManager::sendDropPosition( bool bForce, Time eventTime ) +void SelectionManager::sendDropPosition( bool bForce, XLIB_Time eventTime ) { ClearableMutexGuard aGuard(m_aMutex); if( m_bDropSent ) return; - ::std::hash_map< Window, DropTargetEntry >::const_iterator it = + ::std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it = m_aDropTargets.find( m_aDropWindow ); if( it != m_aDropTargets.end() ) { if( it->second.m_pTarget->m_bActive ) { int x, y; - Window aChild; + XLIB_Window aChild; XTranslateCoordinates( m_pDisplay, it->second.m_aRootWindow, m_aDropWindow, m_nLastDragX, m_nLastDragY, &x, &y, &aChild ); DropTargetDragEvent dtde; dtde.Source = static_cast< OWeakObject* >(it->second.m_pTarget ); @@ -2612,7 +2617,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) bool bHandled = false; // for shortcut - ::std::hash_map< Window, DropTargetEntry >::const_iterator it = + ::std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it = m_aDropTargets.find( m_aDropWindow ); #if OSL_DEBUG_LEVEL > 1 switch( rMessage.type ) @@ -2635,7 +2640,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) case ButtonRelease: fprintf( stderr, "handleDragEvent: ButtonRelease %d (m_nDragButton = %d)\n", rMessage.xbutton.button, m_nDragButton ); break; - case KeyPress: + case XLIB_KeyPress: fprintf( stderr, "handleDragEvent: KeyPress\n" ); break; case KeyRelease: @@ -2719,7 +2724,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) bool bForce = false; int root_x = rMessage.type == MotionNotify ? rMessage.xmotion.x_root : rMessage.xcrossing.x_root; int root_y = rMessage.type == MotionNotify ? rMessage.xmotion.y_root : rMessage.xcrossing.y_root; - Window root = rMessage.type == MotionNotify ? rMessage.xmotion.root : rMessage.xcrossing.root; + XLIB_Window root = rMessage.type == MotionNotify ? rMessage.xmotion.root : rMessage.xcrossing.root; m_nDragTimestamp = rMessage.type == MotionNotify ? rMessage.xmotion.time : rMessage.xcrossing.time; aGuard.clear(); @@ -2736,7 +2741,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) sendDropPosition( bForce, rMessage.type == MotionNotify ? rMessage.xmotion.time : rMessage.xcrossing.time ); } } - else if( rMessage.type == KeyPress || rMessage.type == KeyRelease ) + else if( rMessage.type == XLIB_KeyPress || rMessage.type == KeyRelease ) { bHandled = true; KeySym aKey = XKeycodeToKeysym( m_pDisplay, rMessage.xkey.keycode, 0 ); @@ -2793,7 +2798,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) case XK_Control_L: nNewState = ControlMask;break; // just interested in shift and ctrl for dnd } - if( rMessage.type == KeyPress ) + if( rMessage.type == XLIB_KeyPress ) nState |= nNewState; else nState &= ~nNewState; @@ -2815,7 +2820,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) { bHandled = true; int x, y; - Window aChild; + XLIB_Window aChild; XTranslateCoordinates( m_pDisplay, rMessage.xbutton.root, m_aDropWindow, rMessage.xbutton.x_root, rMessage.xbutton.y_root, &x, &y, &aChild ); DropTargetDropEvent dtde; dtde.Source = static_cast< OWeakObject* >(it->second.m_pTarget ); @@ -2865,7 +2870,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) { bHandled = true; - Window aDummy; + XLIB_Window aDummy; XEvent aEvent; aEvent.type = ButtonPress; aEvent.xbutton.display = m_pDisplay; @@ -2924,7 +2929,7 @@ bool SelectionManager::handleDragEvent( XEvent& rMessage ) // ------------------------------------------------------------------------ -void SelectionManager::accept( sal_Int8 dragOperation, Window aDropWindow, Time ) +void SelectionManager::accept( sal_Int8 dragOperation, XLIB_Window aDropWindow, XLIB_Time ) { if( aDropWindow == m_aCurrentDropWindow ) { @@ -2946,7 +2951,7 @@ void SelectionManager::accept( sal_Int8 dragOperation, Window aDropWindow, Time // ------------------------------------------------------------------------ -void SelectionManager::reject( Window aDropWindow, Time ) +void SelectionManager::reject( XLIB_Window aDropWindow, XLIB_Time ) { if( aDropWindow == m_aCurrentDropWindow ) { @@ -2982,7 +2987,7 @@ sal_Bool SelectionManager::isDragImageSupported() throw() sal_Int32 SelectionManager::getDefaultCursor( sal_Int8 dragAction ) throw() { - Cursor aCursor = m_aNoneCursor; + XLIB_Cursor aCursor = m_aNoneCursor; if( dragAction & DNDConstants::ACTION_MOVE ) aCursor = m_aMoveCursor; else if( dragAction & DNDConstants::ACTION_COPY ) @@ -2994,7 +2999,7 @@ sal_Int32 SelectionManager::getDefaultCursor( sal_Int8 dragAction ) throw() // ------------------------------------------------------------------------ -int SelectionManager::getXdndVersion( Window aWindow, Window& rProxy ) +int SelectionManager::getXdndVersion( XLIB_Window aWindow, XLIB_Window& rProxy ) { Atom* pProperties = NULL; int nProperties = 0; @@ -3022,7 +3027,7 @@ int SelectionManager::getXdndVersion( Window aWindow, Window& rProxy ) if( pBytes ) { if( nType == XA_WINDOW ) - rProxy = *(Window*)pBytes; + rProxy = *(XLIB_Window*)pBytes; XFree( pBytes ); pBytes = NULL; if( rProxy != None ) @@ -3032,7 +3037,7 @@ int SelectionManager::getXdndVersion( Window aWindow, Window& rProxy ) &nType, &nFormat, &nItems, &nBytes, &pBytes ); if( pBytes ) { - if( nType == XA_WINDOW && *(Window*)pBytes != rProxy ) + if( nType == XA_WINDOW && *(XLIB_Window*)pBytes != rProxy ) rProxy = None; XFree( pBytes ); pBytes = NULL; @@ -3044,7 +3049,7 @@ int SelectionManager::getXdndVersion( Window aWindow, Window& rProxy ) break; } } - Window aAwareWindow = rProxy != None ? rProxy : aWindow; + XLIB_Window aAwareWindow = rProxy != None ? rProxy : aWindow; XGetWindowProperty( m_pDisplay, aAwareWindow, m_nXdndAware, 0, 1, False, XA_ATOM, &nType, &nFormat, &nItems, &nBytes, &pBytes ); @@ -3062,7 +3067,7 @@ int SelectionManager::getXdndVersion( Window aWindow, Window& rProxy ) // ------------------------------------------------------------------------ -void SelectionManager::updateDragWindow( int nX, int nY, Window aRoot ) +void SelectionManager::updateDragWindow( int nX, int nY, XLIB_Window aRoot ) { ResettableMutexGuard aGuard( m_aMutex ); @@ -3071,9 +3076,9 @@ void SelectionManager::updateDragWindow( int nX, int nY, Window aRoot ) m_nLastDragX = nX; m_nLastDragY = nY; - Window aParent = aRoot; - Window aChild; - Window aNewProxy = None, aNewCurrentWindow = None; + XLIB_Window aParent = aRoot; + XLIB_Window aChild; + XLIB_Window aNewProxy = None, aNewCurrentWindow = None; int nNewProtocolVersion = -1; int nWinX, nWinY; @@ -3114,7 +3119,7 @@ void SelectionManager::updateDragWindow( int nX, int nY, Window aRoot ) dsde.DropAction = nNewProtocolVersion >= 0 ? m_nUserDragAction : DNDConstants::ACTION_COPY; dsde.UserAction = nNewProtocolVersion >= 0 ? m_nUserDragAction : DNDConstants::ACTION_COPY; - ::std::hash_map< Window, DropTargetEntry >::const_iterator it; + ::std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it; if( aNewCurrentWindow != m_aDropWindow ) { #if OSL_DEBUG_LEVEL > 1 @@ -3263,11 +3268,11 @@ void SelectionManager::startDrag( // the pointer is located in. since said window should be one // of our DropTargets at the time of executeDrag we can use // them for a start - Window aRoot, aParent, aChild; + XLIB_Window aRoot, aParent, aChild; int root_x, root_y, win_x, win_y; unsigned int mask; - ::std::hash_map< Window, DropTargetEntry >::const_iterator it; + ::std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it; it = m_aDropTargets.begin(); while( it != m_aDropTargets.end() ) { @@ -3379,10 +3384,9 @@ void SelectionManager::startDrag( m_bDropSuccess = false; m_bWaitingForPrimaryConversion = false; m_nDragButton = Button1; // default to left button - if( trigger.Event.getValueTypeName().equalsAsciiL( "com.sun.star.awt.MouseEvent", 27 ) ) + com::sun::star::awt::MouseEvent aEvent; + if( trigger.Event >>= aEvent ) { - MouseEvent aEvent; - trigger.Event >>= aEvent; if( aEvent.Buttons & MouseButton::LEFT ) m_nDragButton = Button1; else if( aEvent.Buttons & MouseButton::RIGHT ) @@ -3519,10 +3523,10 @@ sal_Int32 SelectionManager::getCurrentCursor() // ------------------------------------------------------------------------ -void SelectionManager::setCursor( sal_Int32 cursor, Window aDropWindow, Time ) +void SelectionManager::setCursor( sal_Int32 cursor, XLIB_Window aDropWindow, XLIB_Time ) { MutexGuard aGuard( m_aMutex ); - if( aDropWindow == m_aDropWindow && Cursor(cursor) != m_aCurrentCursor ) + if( aDropWindow == m_aDropWindow && XLIB_Cursor(cursor) != m_aCurrentCursor ) { if( m_xDragSourceListener.is() && ! m_bDropSent ) { @@ -3535,7 +3539,7 @@ void SelectionManager::setCursor( sal_Int32 cursor, Window aDropWindow, Time ) // ------------------------------------------------------------------------ -void SelectionManager::setImage( sal_Int32, Window, Time ) +void SelectionManager::setImage( sal_Int32, XLIB_Window, XLIB_Time ) { } @@ -3668,7 +3672,7 @@ bool SelectionManager::handleXEvent( XEvent& rEvent ) case MotionNotify: case ButtonPress: case ButtonRelease: - case KeyPress: + case XLIB_KeyPress: case KeyRelease: bHandled = handleDragEvent( rEvent ); break; @@ -3734,6 +3738,14 @@ void SelectionManager::run( void* pThis ) timeval aLast; gettimeofday( &aLast, 0 ); + Reference< XMultiServiceFactory > xFact( ::comphelper::getProcessServiceFactory() ); + if( xFact.is() ) + { + Reference< XDesktop > xDesktop( xFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ), UNO_QUERY ); + if( xDesktop.is() ) + xDesktop->addTerminateListener(This); + } + while( osl_scheduleThread(This->m_aThread) ) { This->dispatchEvent( 1000 ); @@ -3750,7 +3762,7 @@ void SelectionManager::run( void* pThis ) { if( it->first != This->m_nXdndSelection && ! it->second->m_bOwner ) { - Window aOwner = XGetSelectionOwner( This->m_pDisplay, it->first ); + XLIB_Window aOwner = XGetSelectionOwner( This->m_pDisplay, it->first ); if( aOwner != it->second->m_aLastOwner ) { it->second->m_aLastOwner = aOwner; @@ -3774,6 +3786,40 @@ void SelectionManager::run( void* pThis ) #endif } +void SelectionManager::shutdown() throw() +{ + ResettableMutexGuard aGuard(m_aMutex); + // stop dispatching + if( m_aThread ) + { + osl_terminateThread( m_aThread ); + /* + * Allow thread to finish before app exits to avoid pulling the carpet + * out from under it if pasting is occuring during shutdown + * + * a) allow it to have the Mutex and + * b) reschedule to allow it to complete callbacks to any + * Application::GetSolarMutex protected regions, etc. e.g. + * TransferableHelper::getTransferDataFlavors (via + * SelectionManager::handleSelectionRequest) which it might + * currently be trying to enter. + * + * Otherwise the thread may be left still waiting on a GlobalMutex + * when that gets destroyed, letting the thread blow up and die + * when enters the section in a now dead OOo instance. + */ + aGuard.clear(); + while (osl_isThreadRunning(m_aThread)) + Application::Yield(); + osl_joinWithThread( m_aThread ); + osl_destroyThread( m_aThread ); + m_aThread = NULL; + aGuard.reset(); + } + m_xDisplayConnection->removeEventHandler( Any(), this ); + m_xDisplayConnection.clear(); +} + // ------------------------------------------------------------------------ sal_Bool SelectionManager::handleEvent( const Any& event ) throw() @@ -3782,10 +3828,10 @@ sal_Bool SelectionManager::handleEvent( const Any& event ) throw() if( (event >>= aSeq) ) { XEvent* pEvent = (XEvent*)aSeq.getArray(); - Time nTimestamp = CurrentTime; + XLIB_Time nTimestamp = CurrentTime; if( pEvent->type == ButtonPress || pEvent->type == ButtonRelease ) nTimestamp = pEvent->xbutton.time; - else if( pEvent->type == KeyPress || pEvent->type == KeyRelease ) + else if( pEvent->type == XLIB_KeyPress || pEvent->type == KeyRelease ) nTimestamp = pEvent->xkey.time; else if( pEvent->type == MotionNotify ) nTimestamp = pEvent->xmotion.time; @@ -3806,16 +3852,38 @@ sal_Bool SelectionManager::handleEvent( const Any& event ) throw() #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "SelectionManager got downing event\n" ); #endif - MutexGuard aGuard(m_aMutex); - // stop dispatching - if( m_aThread ) - osl_terminateThread( m_aThread ); - m_xDisplayConnection->removeEventHandler( Any(), this ); - m_xDisplayConnection.clear(); + shutdown(); } return sal_True; } +void SAL_CALL SelectionManager::disposing( const ::com::sun::star::lang::EventObject& ) + throw( ::com::sun::star::uno::RuntimeException ) +{ +} + +void SAL_CALL SelectionManager::queryTermination( const ::com::sun::star::lang::EventObject& ) + throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException ) +{ +} + +/* + * To be safe, shutdown needs to be called before the ~SfxApplication is called, waiting until + * the downing event can be too late if paste are requested during shutdown and ~SfxApplication + * has been called before vcl is shutdown + */ +void SAL_CALL SelectionManager::notifyTermination( const ::com::sun::star::lang::EventObject& rEvent ) + throw( ::com::sun::star::uno::RuntimeException ) +{ + Reference< XDesktop > xDesktop( rEvent.Source, UNO_QUERY ); + if( xDesktop.is() == sal_True ) + xDesktop->removeTerminateListener( this ); + #if OSL_DEBUG_LEVEL > 1 + fprintf( stderr, "SelectionManager got app termination event\n" ); + #endif + shutdown(); +} + // ------------------------------------------------------------------------ void SelectionManager::registerHandler( Atom selection, SelectionAdaptor& rAdaptor ) @@ -3846,12 +3914,12 @@ void SelectionManager::deregisterHandler( Atom selection ) // ------------------------------------------------------------------------ -void SelectionManager::registerDropTarget( Window aWindow, DropTarget* pTarget ) +void SelectionManager::registerDropTarget( XLIB_Window aWindow, DropTarget* pTarget ) { MutexGuard aGuard(m_aMutex); // sanity check - ::std::hash_map< Window, DropTargetEntry >::const_iterator it = + ::std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it = m_aDropTargets.find( aWindow ); if( it != m_aDropTargets.end() ) OSL_ASSERT( "attempt to register window as drop target twice" ); @@ -3877,7 +3945,7 @@ void SelectionManager::registerDropTarget( Window aWindow, DropTarget* pTarget ) // ------------------------------------------------------------------------ -void SelectionManager::deregisterDropTarget( Window aWindow ) +void SelectionManager::deregisterDropTarget( XLIB_Window aWindow ) { ClearableMutexGuard aGuard(m_aMutex); @@ -3885,7 +3953,7 @@ void SelectionManager::deregisterDropTarget( Window aWindow ) if( aWindow == m_aDragSourceWindow && m_aDragRunning.check() ) { // abort drag - std::hash_map< Window, DropTargetEntry >::const_iterator it = + std::hash_map< XLIB_Window, DropTargetEntry >::const_iterator it = m_aDropTargets.find( m_aDropWindow ); if( it != m_aDropTargets.end() ) { diff --git a/vcl/unx/source/dtrans/X11_selection.hxx b/vcl/unx/source/dtrans/X11_selection.hxx index dc6c41247bbd..fa6c310ef8c1 100644 --- a/vcl/unx/source/dtrans/X11_selection.hxx +++ b/vcl/unx/source/dtrans/X11_selection.hxx @@ -32,6 +32,7 @@ #define _DTRANS_X11_SELECTION_HXX_ #include +#include #include #include #include @@ -39,6 +40,7 @@ #include #include #include +#include #include #ifndef _OSL_CONDITION_HXX_ @@ -48,7 +50,9 @@ #include #include +#include "tools/prex.h" #include +#include "tools/postx.h" #define XDND_IMPLEMENTATION_NAME "com.sun.star.datatransfer.dnd.XdndSupport" #define XDND_DROPTARGET_IMPLEMENTATION_NAME "com.sun.star.datatransfer.dnd.XdndDropTarget" @@ -84,7 +88,7 @@ namespace x11 { ::osl::Mutex m_aMutex; bool m_bActive; sal_Int8 m_nDefaultActions; - Window m_aTargetWindow; + XLIB_Window m_aTargetWindow; class SelectionManager* m_pSelectionManager; Reference< ::com::sun::star::datatransfer::dnd::XDragSource > m_xSelectionManager; @@ -155,10 +159,11 @@ namespace x11 { class SelectionManager : - public ::cppu::WeakImplHelper3< + public ::cppu::WeakImplHelper4< ::com::sun::star::datatransfer::dnd::XDragSource, ::com::sun::star::lang::XInitialization, - ::com::sun::star::awt::XEventHandler + ::com::sun::star::awt::XEventHandler, + ::com::sun::star::frame::XTerminateListener >, public SelectionAdaptor { @@ -175,7 +180,7 @@ namespace x11 { { Sequence< sal_Int8 > m_aData; int m_nBufferPos; - Window m_aRequestor; + XLIB_Window m_aRequestor; Atom m_aProperty; Atom m_aTarget; int m_nFormat; @@ -209,11 +214,11 @@ namespace x11 { Atom m_aUTF8Type; bool m_bHaveCompound; bool m_bOwner; - Window m_aLastOwner; + XLIB_Window m_aLastOwner; PixmapHolder* m_pPixmap; - // m_nOrigTimestamp contains the timestamp at which the seclection - // was acquired; needed for TIMESTAMP target - Time m_nOrigTimestamp; + // m_nOrigXLIB_Timestamp contains the XLIB_Timestamp at which the seclection + // was acquired; needed for XLIB_TimeSTAMP target + XLIB_Time m_nOrigTimestamp; Selection() : m_eState( Inactive ), m_pAdaptor( NULL ), @@ -234,7 +239,7 @@ namespace x11 { struct DropTargetEntry { DropTarget* m_pTarget; - Window m_aRootWindow; + XLIB_Window m_aRootWindow; DropTargetEntry() : m_pTarget( NULL ), m_aRootWindow( None ) {} DropTargetEntry( DropTarget* pTarget ) : @@ -257,13 +262,13 @@ namespace x11 { oslThread m_aThread; oslThread m_aDragExecuteThread; ::osl::Condition m_aDragRunning; - Window m_aWindow; + XLIB_Window m_aWindow; Reference< ::com::sun::star::awt::XDisplayConnection > m_xDisplayConnection; Reference< com::sun::star::script::XInvocation > m_xBitmapConverter; sal_Int32 m_nSelectionTimeout; - Time m_nSelectionTimestamp; + XLIB_Time m_nSelectionTimestamp; // members used for Xdnd @@ -272,21 +277,21 @@ namespace x11 { // contains the XdndEnterEvent of a drop action running // with one of our targets. The data.l[0] member - // (conatining the drag source window) is set + // (conatining the drag source XLIB_Window) is set // to None while that is not the case XClientMessageEvent m_aDropEnterEvent; // set to false on XdndEnter // set to true on first XdndPosition or XdndLeave bool m_bDropEnterSent; - Window m_aCurrentDropWindow; - // time code of XdndDrop - Time m_nDropTime; + XLIB_Window m_aCurrentDropWindow; + // XLIB_Time code of XdndDrop + XLIB_Time m_nDropTime; sal_Int8 m_nLastDropAction; // XTransferable for Xdnd with foreign drag source Reference< ::com::sun::star::datatransfer::XTransferable > m_xDropTransferable; int m_nLastX, m_nLastY; - Time m_nDropTimestamp; + XLIB_Time m_nDropTimestamp; // set to true when calling drop() // if another XdndEnter is received this shows that // someone forgot to call dropComplete - we should reset @@ -296,10 +301,10 @@ namespace x11 { // drag only // None if no Dnd action is running with us as source - Window m_aDropWindow; - // either m_aDropWindow or its XdndProxy - Window m_aDropProxy; - Window m_aDragSourceWindow; + XLIB_Window m_aDropWindow; + // either m_aDropXLIB_Window or its XdndProxy + XLIB_Window m_aDropProxy; + XLIB_Window m_aDragSourceWindow; // XTransferable for Xdnd when we are drag source Reference< ::com::sun::star::datatransfer::XTransferable > m_xDragSourceTransferable; @@ -321,20 +326,20 @@ namespace x11 { bool m_bDropSent; time_t m_nDropTimeout; bool m_bWaitingForPrimaryConversion; - Time m_nDragTimestamp; + XLIB_Time m_nDragTimestamp; // drag cursors - Cursor m_aMoveCursor; - Cursor m_aCopyCursor; - Cursor m_aLinkCursor; - Cursor m_aNoneCursor; - Cursor m_aCurrentCursor; + XLIB_Cursor m_aMoveCursor; + XLIB_Cursor m_aCopyCursor; + XLIB_Cursor m_aLinkCursor; + XLIB_Cursor m_aNoneCursor; + XLIB_Cursor m_aCurrentCursor; // drag and drop int m_nCurrentProtocolVersion; - ::std::hash_map< Window, DropTargetEntry > + ::std::hash_map< XLIB_Window, DropTargetEntry > m_aDropTargets; @@ -374,7 +379,7 @@ namespace x11 { ::std::hash_map< Atom, Selection* > m_aSelections; // IncrementalTransfers in progress - std::hash_map< Window, std::hash_map< Atom, IncrementalTransfer > > + std::hash_map< XLIB_Window, std::hash_map< Atom, IncrementalTransfer > > m_aIncrementals; // do not use X11 multithreading capabilities @@ -398,12 +403,12 @@ namespace x11 { // dnd helpers void sendDragStatus( Atom nDropAction ); - void sendDropPosition( bool bForce, Time eventTime ); + void sendDropPosition( bool bForce, XLIB_Time eventXLIB_Time ); bool updateDragAction( int modifierState ); - int getXdndVersion( Window aWindow, Window& rProxy ); - Cursor createCursor( const char* pPointerData, const char* pMaskData, int width, int height, int hotX, int hotY ); - // coordinates on root window - void updateDragWindow( int nX, int nY, Window aRoot ); + int getXdndVersion( XLIB_Window aXLIB_Window, XLIB_Window& rProxy ); + XLIB_Cursor createCursor( const char* pPointerData, const char* pMaskData, int width, int height, int hotX, int hotY ); + // coordinates on root XLIB_Window + void updateDragWindow( int nX, int nY, XLIB_Window aRoot ); bool getPasteData( Atom selection, Atom type, Sequence< sal_Int8 >& rData ); // returns true if conversion was successful @@ -412,7 +417,7 @@ namespace x11 { Atom nSelection, int & rFormat, Sequence< sal_Int8 >& rData ); - bool sendData( SelectionAdaptor* pAdaptor, Window requestor, Atom target, Atom property, Atom selection ); + bool sendData( SelectionAdaptor* pAdaptor, XLIB_Window requestor, Atom target, Atom property, Atom selection ); // thread dispatch loop public: @@ -438,7 +443,7 @@ namespace x11 { static SelectionManager& get( const ::rtl::OUString& rDisplayName = ::rtl::OUString() ); Display * getDisplay() { return m_pDisplay; }; - Window getWindow() { return m_aWindow; }; + XLIB_Window getWindow() { return m_aWindow; }; void registerHandler( Atom selection, SelectionAdaptor& rAdaptor ); @@ -464,20 +469,22 @@ namespace x11 { bool getPasteData( Atom selection, const ::rtl::OUString& rType, Sequence< sal_Int8 >& rData ); // for XDropTarget to register/deregister itself - void registerDropTarget( Window aWindow, DropTarget* pTarget ); - void deregisterDropTarget( Window aWindow ); + void registerDropTarget( XLIB_Window aXLIB_Window, DropTarget* pTarget ); + void deregisterDropTarget( XLIB_Window aXLIB_Window ); // for XDropTarget{Drag|Drop}Context - void accept( sal_Int8 dragOperation, Window aDropWindow, Time aTimestamp ); - void reject( Window aDropWindow, Time aTimestamp ); - void dropComplete( sal_Bool success, Window aDropWindow, Time aTimestamp ); + void accept( sal_Int8 dragOperation, XLIB_Window aDropXLIB_Window, XLIB_Time aXLIB_Timestamp ); + void reject( XLIB_Window aDropXLIB_Window, XLIB_Time aXLIB_Timestamp ); + void dropComplete( sal_Bool success, XLIB_Window aDropXLIB_Window, XLIB_Time aXLIB_Timestamp ); // for XDragSourceContext sal_Int32 getCurrentCursor(); - void setCursor( sal_Int32 cursor, Window aDropWindow, Time aTimestamp ); - void setImage( sal_Int32 image, Window aDropWindow, Time aTimestamp ); + void setCursor( sal_Int32 cursor, XLIB_Window aDropXLIB_Window, XLIB_Time aXLIB_Timestamp ); + void setImage( sal_Int32 image, XLIB_Window aDropXLIB_Window, XLIB_Time aXLIB_Timestamp ); void transferablesFlavorsChanged(); + void shutdown() throw(); + // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& arguments ) throw( ::com::sun::star::uno::Exception ); @@ -499,6 +506,15 @@ namespace x11 { virtual void clearTransferable() throw(); virtual void fireContentsChanged() throw(); virtual Reference< XInterface > getReference() throw(); + + // XEventListener + virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); + + // XTerminateListener + virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) + throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException ); + virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) + throw( ::com::sun::star::uno::RuntimeException ); }; // ------------------------------------------------------------------------ diff --git a/vcl/unx/source/dtrans/bmp.cxx b/vcl/unx/source/dtrans/bmp.cxx index 49219bfb0e2a..f3c7d78617a6 100644 --- a/vcl/unx/source/dtrans/bmp.cxx +++ b/vcl/unx/source/dtrans/bmp.cxx @@ -356,7 +356,7 @@ sal_uInt8* x11::X11_getBmpFromPixmap( ) { // get geometry of drawable - Window aRoot; + XLIB_Window aRoot; int x,y; unsigned int w, h, bw, d; XGetGeometry( pDisplay, aDrawable, &aRoot, &x, &y, &w, &h, &bw, &d ); diff --git a/vcl/unx/source/dtrans/bmp.hxx b/vcl/unx/source/dtrans/bmp.hxx index baf04ac31d90..6331122e726d 100644 --- a/vcl/unx/source/dtrans/bmp.hxx +++ b/vcl/unx/source/dtrans/bmp.hxx @@ -31,10 +31,12 @@ #ifndef _DTRANS_BMP_HXX_ #define _DTRANS_BMP_HXX_ +#include "tools/prex.h" #include #include #include #include +#include "tools/postx.h" #include #include diff --git a/vcl/util/makefile.mk b/vcl/util/makefile.mk index 32620d9e966a..49b051b3557c 100644 --- a/vcl/util/makefile.mk +++ b/vcl/util/makefile.mk @@ -303,6 +303,7 @@ SHL2STDLIBS=\ $(VOSLIB) \ $(BASEGFXLIB) \ $(UNOTOOLSLIB) \ + $(COMPHELPERLIB) \ $(CPPUHELPERLIB) \ $(CPPULIB) \ $(SALLIB) -- cgit From 8e1696a1e3402f66342d590733a9afdbe4ea840b Mon Sep 17 00:00:00 2001 From: hdu Date: Tue, 1 Dec 2009 10:37:14 +0100 Subject: #i106264# prevent ushort-overflow in GSUB.cov2 --- vcl/source/fontsubset/gsub.cxx | 13 ++++++------- vcl/source/glyphs/gcach_ftyp.cxx | 13 ++++++------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/vcl/source/fontsubset/gsub.cxx b/vcl/source/fontsubset/gsub.cxx index 600c03194210..a1c3344f3e5a 100644 --- a/vcl/source/fontsubset/gsub.cxx +++ b/vcl/source/fontsubset/gsub.cxx @@ -42,6 +42,7 @@ namespace vcl { typedef sal_uInt32 ULONG; +typedef sal_uInt32 UINT32; typedef sal_uInt16 USHORT; typedef sal_uInt8 FT_Byte; @@ -280,13 +281,11 @@ int ReadGSUB( struct _TrueTypeFont* pTTFile, return false; for( int i = nCntRange; --i >= 0; ) { - const USHORT nGlyph0 = NEXT_UShort( pCoverage ); - const USHORT nGlyph1 = NEXT_UShort( pCoverage ); - const USHORT nStartCoverageIndex = NEXT_UShort( pCoverage ); - OSL_ENSURE( aSubstVector.size() == nStartCoverageIndex, "coverage index mismatch"); - (void)nStartCoverageIndex; - for( USHORT j = nGlyph0; j <= nGlyph1; ++j ) - aSubstVector.push_back( GlyphSubst( j, 0 ) ); + const UINT32 nGlyph0 = NEXT_UShort( pCoverage ); + const UINT32 nGlyph1 = NEXT_UShort( pCoverage ); + const USHORT nCovIdx = NEXT_UShort( pCoverage ); + for( UINT32 j = nGlyph0; j <= nGlyph1; ++j ) + aSubstVector.push_back( GlyphSubst( static_cast(j + nCovIdx), 0 ) ); } } break; diff --git a/vcl/source/glyphs/gcach_ftyp.cxx b/vcl/source/glyphs/gcach_ftyp.cxx index 18857b94af8f..b724893e139c 100644 --- a/vcl/source/glyphs/gcach_ftyp.cxx +++ b/vcl/source/glyphs/gcach_ftyp.cxx @@ -2487,14 +2487,12 @@ bool FreetypeServerFont::ApplyGSUB( const ImplFontSelectData& rFSD ) pCoverage += 2; for( int i = nCntRange; --i >= 0; ) { - const USHORT nGlyph0 = GetUShort( pCoverage+0 ); - const USHORT nGlyph1 = GetUShort( pCoverage+2 ); - const USHORT nStartCoverageIndex = GetUShort( pCoverage+4 ); - DBG_ASSERT( aSubstVector.size() == nStartCoverageIndex, "coverage index mismatch"); - (void)nStartCoverageIndex; + const UINT32 nGlyph0 = GetUShort( pCoverage+0 ); + const UINT32 nGlyph1 = GetUShort( pCoverage+2 ); + const USHORT nCovIdx = GetUShort( pCoverage+4 ); pCoverage += 6; - for( USHORT j = nGlyph0; j <= nGlyph1; ++j ) - aSubstVector.push_back( GlyphSubst( j, 0 ) ); + for( UINT32 j = nGlyph0; j <= nGlyph1; ++j ) + aSubstVector.push_back( GlyphSubst( static_cast(j + nCovIdx), 0 ) ); } } break; @@ -2538,3 +2536,4 @@ bool FreetypeServerFont::ApplyGSUB( const ImplFontSelectData& rFSD ) } // ======================================================================= + -- cgit From 83408633977416f4f2e612555471431bf9acf4c9 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 1 Dec 2009 18:01:53 +0100 Subject: vcl108: #i107358# fix uninitialized member (thanks cmc!) --- vcl/source/gdi/pdfwriter_impl.hxx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vcl/source/gdi/pdfwriter_impl.hxx b/vcl/source/gdi/pdfwriter_impl.hxx index 7d5ec2bf4f61..29de6d4f5971 100644 --- a/vcl/source/gdi/pdfwriter_impl.hxx +++ b/vcl/source/gdi/pdfwriter_impl.hxx @@ -679,6 +679,7 @@ private: m_aOverlineColor( COL_TRANSPARENT ), m_nAntiAlias( 1 ), m_nLayoutMode( 0 ), + m_aDigitLanguage( 0 ), m_nTransparentPercent( 0 ), m_nFlags( 0xffff ), m_nUpdateFlags( 0xffff ) @@ -693,6 +694,7 @@ private: m_aClipRegion( rState.m_aClipRegion ), m_nAntiAlias( rState.m_nAntiAlias ), m_nLayoutMode( rState.m_nLayoutMode ), + m_aDigitLanguage( rState.m_aDigitLanguage ), m_nTransparentPercent( rState.m_nTransparentPercent ), m_nFlags( rState.m_nFlags ), m_nUpdateFlags( rState.m_nUpdateFlags ) @@ -710,6 +712,7 @@ private: m_aClipRegion = rState.m_aClipRegion; m_nAntiAlias = rState.m_nAntiAlias; m_nLayoutMode = rState.m_nLayoutMode; + m_aDigitLanguage = rState.m_aDigitLanguage; m_nTransparentPercent = rState.m_nTransparentPercent; m_nFlags = rState.m_nFlags; m_nUpdateFlags = rState.m_nUpdateFlags; -- cgit From cab402a8aa21c2ba6d2d66d45d44b3b2b07cedf8 Mon Sep 17 00:00:00 2001 From: "Frank Schoenheit [fs]" Date: Thu, 3 Dec 2009 14:12:42 +0100 Subject: diagnostics --- unotools/source/config/confignode.cxx | 37 ++++++++++------------------------- 1 file changed, 10 insertions(+), 27 deletions(-) diff --git a/unotools/source/config/confignode.cxx b/unotools/source/config/confignode.cxx index 56d258461e95..c8134137db0c 100644 --- a/unotools/source/config/confignode.cxx +++ b/unotools/source/config/confignode.cxx @@ -468,16 +468,9 @@ namespace utl aReturn = m_xHierarchyAccess->getByHierarchicalName(_rPath); } } - catch(NoSuchElementException& e) + catch(const NoSuchElementException&) { - #if OSL_DEBUG_LEVEL > 0 - rtl::OStringBuffer aBuf( 256 ); - aBuf.append("OConfigurationNode::getNodeValue: caught a NoSuchElementException while trying to open "); - aBuf.append( rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ) ); - OSL_ENSURE(sal_False, aBuf.getStr()); - #else - (void)e; - #endif + DBG_UNHANDLED_EXCEPTION(); } return aReturn; } @@ -500,7 +493,7 @@ namespace utl } catch(Exception&) { - OSL_ENSURE(sal_False, "OConfigurationNode::cloneAsRoot: could not retrieve the node path!"); + DBG_UNHANDLED_EXCEPTION(); } } @@ -561,13 +554,9 @@ namespace utl m_xCommitter->commitChanges(); return sal_True; } - catch(WrappedTargetException&) - { - OSL_ENSURE(sal_False, "OConfigurationTreeRoot::commit: caught a WrappedTargetException!"); - } - catch(RuntimeException&) + catch(const Exception&) { - OSL_ENSURE(sal_False, "OConfigurationTreeRoot::commit: caught a RuntimeException!"); + DBG_UNHANDLED_EXCEPTION(); } return sal_False; } @@ -604,7 +593,7 @@ namespace utl } catch(const Exception&) { - OSL_ENSURE(sal_False, "OConfigurationTreeRoot::createWithProvider: unable to check the service conformance of the provider given!"); + DBG_UNHANDLED_EXCEPTION(); } } #endif @@ -648,15 +637,9 @@ namespace utl try { xComp->dispose(); } catch(Exception&) { } } } - catch(Exception& e) + catch(const Exception&) { - #if OSL_DEBUG_LEVEL > 0 - ::rtl::OString sMessage( "OConfigurationTreeRoot::createWithProvider: caught an exception while creating the access object!\nmessage:\n" ); - sMessage += ::rtl::OString( e.Message.getStr(), e.Message.getLength(), RTL_TEXTENCODING_ASCII_US ); - OSL_ENSURE( sal_False, sMessage.getStr() ); - #else - (void)e; - #endif + DBG_UNHANDLED_EXCEPTION(); } } bTryAgain = CM_PREFER_UPDATABLE == _eMode; @@ -683,9 +666,9 @@ namespace utl if (xProviderAsFac.is()) return createWithProvider(xProviderAsFac, _rPath, _nDepth, _eMode, _bLazyWrite); } - catch(Exception&) + catch(const Exception&) { - OSL_ENSURE(sal_False, "OConfigurationTreeRoot::createWithServiceFactory: error while instantiating the provider service!"); + DBG_UNHANDLED_EXCEPTION(); } } return OConfigurationTreeRoot(); -- cgit From 11c7cf17c5b96e2201cfaf43f5b4aa6cf2c34906 Mon Sep 17 00:00:00 2001 From: sj Date: Thu, 3 Dec 2009 16:31:03 +0100 Subject: impress181: #i107292#: Applied patch, wmf filter is now supporting embedded EMF data from the META_ESCAPE action. --- svtools/source/filter.vcl/wmf/winmtf.cxx | 5 + svtools/source/filter.vcl/wmf/winmtf.hxx | 15 +++ svtools/source/filter.vcl/wmf/winwmf.cxx | 216 ++++++++++++++++++++++--------- svtools/source/filter.vcl/wmf/wmfwr.cxx | 80 ++++++++++++ svtools/source/filter.vcl/wmf/wmfwr.hxx | 9 ++ 5 files changed, 264 insertions(+), 61 deletions(-) diff --git a/svtools/source/filter.vcl/wmf/winmtf.cxx b/svtools/source/filter.vcl/wmf/winmtf.cxx index 6f1caae18750..3db3e6957e41 100644 --- a/svtools/source/filter.vcl/wmf/winmtf.cxx +++ b/svtools/source/filter.vcl/wmf/winmtf.cxx @@ -2195,3 +2195,8 @@ void WinMtfOutput::Pop() } } +void WinMtfOutput::AddFromGDIMetaFile( GDIMetaFile& rGDIMetaFile ) +{ + rGDIMetaFile.Play( *mpGDIMetaFile, 0xFFFFFFFF ); +} + diff --git a/svtools/source/filter.vcl/wmf/winmtf.hxx b/svtools/source/filter.vcl/wmf/winmtf.hxx index ada590a19675..f3b2482f63bc 100644 --- a/svtools/source/filter.vcl/wmf/winmtf.hxx +++ b/svtools/source/filter.vcl/wmf/winmtf.hxx @@ -672,6 +672,7 @@ class WinMtfOutput void MoveClipRegion( const Size& rSize ); void SetClipPath( const PolyPolygon& rPolyPoly, sal_Int32 nClippingMode, sal_Bool bIsMapped ); void UpdateClipRegion(); + void AddFromGDIMetaFile( GDIMetaFile& rGDIMetaFile ); WinMtfOutput( GDIMetaFile& rGDIMetaFile ); virtual ~WinMtfOutput(); @@ -734,6 +735,18 @@ private: UINT16 nUnitsPerInch; sal_uInt32 nRecSize; + // embedded EMF data + SvMemoryStream* pEMFStream; + + // total number of comment records containing EMF data + sal_uInt32 nEMFRecCount; + + // number of EMF records read + sal_uInt32 nEMFRec; + + // total size of embedded EMF data + sal_uInt32 nEMFSize; + sal_uInt32 nSkipActions; sal_uInt32 nCurrentAction; sal_uInt32 nUnicodeEscapeAction; @@ -755,6 +768,8 @@ public: WMFReader( SvStream& rStreamWMF, GDIMetaFile& rGDIMetaFile, FilterConfigItem* pConfigItem = NULL ) : WinMtf( new WinMtfOutput( rGDIMetaFile ), rStreamWMF, pConfigItem ) {}; + ~WMFReader(); + // Liesst aus dem Stream eine WMF-Datei und fuellt das GDIMetaFile void ReadWMF(); }; diff --git a/svtools/source/filter.vcl/wmf/winwmf.cxx b/svtools/source/filter.vcl/wmf/winwmf.cxx index 0930b0ece8a8..54629383a4f8 100644 --- a/svtools/source/filter.vcl/wmf/winwmf.cxx +++ b/svtools/source/filter.vcl/wmf/winwmf.cxx @@ -32,6 +32,7 @@ #include "precompiled_svtools.hxx" #include "winmtf.hxx" +#include #include #include #include @@ -831,81 +832,136 @@ void WMFReader::ReadRecordParams( USHORT nFunc ) pWMF->SetError( SVSTREAM_FILEFORMAT_ERROR ); break; } - if ( nRecSize >= 12 ) // minimal escape lenght + if ( nRecSize >= 4 ) // minimal escape lenght { - sal_uInt16 nMode, nLen, OO; - sal_uInt32 Magic, nCheck,nEsc; + sal_uInt16 nMode, nLen; *pWMF >> nMode - >> nLen - >> OO - >> Magic - >> nCheck - >> nEsc; - if ( ( nMode == W_MFCOMMENT ) && ( nLen >= 14 ) && ( OO == 0x4f4f ) && ( Magic == 0xa2c2a ) ) + >> nLen; + if ( ( nMode == W_MFCOMMENT ) && ( nLen >= 4 ) ) { - sal_uInt32 nEscLen = nLen - 14; - if ( nEscLen <= ( nRecSize * 2 ) ) + sal_uInt32 nNewMagic; // we have to read int32 for + *pWMF >> nNewMagic; // META_ESCAPE_ENHANCED_METAFILE CommentIdentifier + + if( nNewMagic == 0x2c2a4f4f && nLen >= 14 ) { + sal_uInt16 nMagic2; + *pWMF >> nMagic2; + if( nMagic2 == 0x0a ) // 2nd half of magic + { // continue with private escape + sal_uInt32 nCheck, nEsc; + *pWMF >> nCheck + >> nEsc; + + sal_uInt32 nEscLen = nLen - 14; + if ( nEscLen <= ( nRecSize * 2 ) ) + { #ifdef OSL_BIGENDIAN - sal_uInt32 nTmp = SWAPLONG( nEsc ); - sal_uInt32 nCheckSum = rtl_crc32( 0, &nTmp, 4 ); + sal_uInt32 nTmp = SWAPLONG( nEsc ); + sal_uInt32 nCheckSum = rtl_crc32( 0, &nTmp, 4 ); #else - sal_uInt32 nCheckSum = rtl_crc32( 0, &nEsc, 4 ); + sal_uInt32 nCheckSum = rtl_crc32( 0, &nEsc, 4 ); #endif - sal_Int8* pData = NULL; + sal_Int8* pData = NULL; - if ( ( static_cast< sal_uInt64 >( nEscLen ) + pWMF->Tell() ) > nMetaRecEndPos ) - { - pWMF->SetError( SVSTREAM_FILEFORMAT_ERROR ); - break; - } - if ( nEscLen > 0 ) - { - pData = new sal_Int8[ nEscLen ]; - pWMF->Read( pData, nEscLen ); - nCheckSum = rtl_crc32( nCheckSum, pData, nEscLen ); - } - if ( nCheck == nCheckSum ) - { - switch( nEsc ) - { - case PRIVATE_ESCAPE_UNICODE : - { // we will use text instead of polygons only if we have the correct font - if ( aVDev.IsFontAvailable( pOut->GetFont().GetName() ) ) + if ( ( static_cast< sal_uInt64 >( nEscLen ) + pWMF->Tell() ) > nMetaRecEndPos ) + { + pWMF->SetError( SVSTREAM_FILEFORMAT_ERROR ); + break; + } + if ( nEscLen > 0 ) + { + pData = new sal_Int8[ nEscLen ]; + pWMF->Read( pData, nEscLen ); + nCheckSum = rtl_crc32( nCheckSum, pData, nEscLen ); + } + if ( nCheck == nCheckSum ) + { + switch( nEsc ) { - Point aPt; - String aString; - sal_uInt32 i, nStringLen, nDXCount; - sal_Int32* pDXAry = NULL; - SvMemoryStream aMemoryStream( nEscLen ); - aMemoryStream.Write( pData, nEscLen ); - aMemoryStream.Seek( STREAM_SEEK_TO_BEGIN ); - aMemoryStream >> aPt.X() - >> aPt.Y() - >> nStringLen; - - if ( ( static_cast< sal_uInt64 >( nStringLen ) * sizeof( sal_Unicode ) ) < ( nEscLen - aMemoryStream.Tell() ) ) - { - sal_Unicode* pBuf = aString.AllocBuffer( (xub_StrLen)nStringLen ); - for ( i = 0; i < nStringLen; i++ ) - aMemoryStream >> pBuf[ i ]; - aMemoryStream >> nDXCount; - if ( ( static_cast< sal_uInt64 >( nDXCount ) * sizeof( sal_Int32 ) ) >= ( nEscLen - aMemoryStream.Tell() ) ) - nDXCount = 0; - if ( nDXCount ) - pDXAry = new sal_Int32[ nDXCount ]; - for ( i = 0; i < nDXCount; i++ ) - aMemoryStream >> pDXAry[ i ]; - aMemoryStream >> nSkipActions; - pOut->DrawText( aPt, aString, pDXAry ); - delete[] pDXAry; + case PRIVATE_ESCAPE_UNICODE : + { // we will use text instead of polygons only if we have the correct font + if ( aVDev.IsFontAvailable( pOut->GetFont().GetName() ) ) + { + Point aPt; + String aString; + sal_uInt32 i, nStringLen, nDXCount; + sal_Int32* pDXAry = NULL; + SvMemoryStream aMemoryStream( nEscLen ); + aMemoryStream.Write( pData, nEscLen ); + aMemoryStream.Seek( STREAM_SEEK_TO_BEGIN ); + aMemoryStream >> aPt.X() + >> aPt.Y() + >> nStringLen; + + if ( ( static_cast< sal_uInt64 >( nStringLen ) * sizeof( sal_Unicode ) ) < ( nEscLen - aMemoryStream.Tell() ) ) + { + sal_Unicode* pBuf = aString.AllocBuffer( (xub_StrLen)nStringLen ); + for ( i = 0; i < nStringLen; i++ ) + aMemoryStream >> pBuf[ i ]; + aMemoryStream >> nDXCount; + if ( ( static_cast< sal_uInt64 >( nDXCount ) * sizeof( sal_Int32 ) ) >= ( nEscLen - aMemoryStream.Tell() ) ) + nDXCount = 0; + if ( nDXCount ) + pDXAry = new sal_Int32[ nDXCount ]; + for ( i = 0; i < nDXCount; i++ ) + aMemoryStream >> pDXAry[ i ]; + aMemoryStream >> nSkipActions; + pOut->DrawText( aPt, aString, pDXAry ); + delete[] pDXAry; + } + } } + break; } } - break; + delete[] pData; + } + } + } + else if ( nNewMagic == 0x43464D57 && nLen >= 34 && ( nLen + 10 <= nRecSize * 2 )) + { + sal_uInt32 nComType, nVersion, nFlags, nComRecCount, + nCurRecSize, nRemainingSize, nEMFTotalSize; + sal_uInt16 nCheck; + + *pWMF >> nComType >> nVersion >> nCheck >> nFlags + >> nComRecCount >> nCurRecSize + >> nRemainingSize >> nEMFTotalSize; // the nRemainingSize is not mentioned in MSDN documentation + // but it seems to be required to read in data produced by OLE + + if( nComType == 0x01 && nVersion == 0x10000 && nComRecCount ) + { + if( !nEMFRec ) + { // first EMF comment + nEMFRecCount = nComRecCount; + nEMFSize = nEMFTotalSize; + pEMFStream = new SvMemoryStream( nEMFSize ); + } + else if( ( nEMFRecCount != nComRecCount ) || ( nEMFSize != nEMFTotalSize ) ) // add additional checks here + { + // total records should be the same as in previous comments + nEMFRecCount = 0xFFFFFFFF; + delete pEMFStream; + pEMFStream = NULL; + } + nEMFRec++; + + if( pEMFStream && nCurRecSize + 34 > nLen ) + { + nEMFRecCount = 0xFFFFFFFF; + delete pEMFStream; + pEMFStream = NULL; + } + + if( pEMFStream ) + { + sal_Int8* pBuf = new sal_Int8[ nCurRecSize ]; + sal_uInt32 nCount = pWMF->Read( pBuf, nCurRecSize ); + if( nCount == nCurRecSize ) + pEMFStream->Write( pBuf, nCount ); + delete[] pBuf; } } - delete[] pData; } } } @@ -1023,6 +1079,11 @@ void WMFReader::ReadWMF() nCurrentAction = 0; nUnicodeEscapeAction = 0; + pEMFStream = NULL; + nEMFRecCount = 0; + nEMFRec = 0; + nEMFSize = 0; + pOut->SetMapMode( MM_ANISOTROPIC ); pOut->SetWinOrg( Point() ); pOut->SetWinExt( Size( 1, 1 ) ); @@ -1070,6 +1131,33 @@ void WMFReader::ReadWMF() ReadRecordParams( nFunction ); else nSkipActions--; + + if( pEMFStream && nEMFRecCount == nEMFRec ) + { + GDIMetaFile aMeta; + pEMFStream->Seek( 0 ); + EnhWMFReader* pEMFReader = new EnhWMFReader ( *pEMFStream, aMeta ); + BOOL bRead = pEMFReader->ReadEnhWMF(); + delete pEMFReader; // destroy first!!! + + if( bRead ) + { + pOut->AddFromGDIMetaFile( aMeta ); + pOut->SetrclFrame( Rectangle(0, 0, aMeta.GetPrefSize().Width(), aMeta.GetPrefSize().Height() )); + // we have successfully read the embedded EMF data + // no need to process WMF data further + break; + } + else + { + // something went wrong + // continue with WMF, don't try this again + delete pEMFStream; + pEMFStream = NULL; + } + + } + nPos += nRecSize * 2; if ( nPos <= nEndPos ) pWMF->Seek( nPos ); @@ -1333,3 +1421,9 @@ sal_Bool WMFReader::GetPlaceableBound( Rectangle& rPlaceableBound, SvStream* pSt return bRet; } +WMFReader::~WMFReader() +{ + if( pEMFStream ) + delete pEMFStream; +} + diff --git a/svtools/source/filter.vcl/wmf/wmfwr.cxx b/svtools/source/filter.vcl/wmf/wmfwr.cxx index ee3a71c51f9d..f6ff58426a6a 100644 --- a/svtools/source/filter.vcl/wmf/wmfwr.cxx +++ b/svtools/source/filter.vcl/wmf/wmfwr.cxx @@ -33,6 +33,7 @@ #include #include "wmfwr.hxx" +#include "emfwr.hxx" #include #include #include @@ -1807,6 +1808,7 @@ BOOL WMFWriter::WriteWMF( const GDIMetaFile& rMTF, SvStream& rTargetStream, { WMFWriterAttrStackMember * pAt; + bEmbedEMF = TRUE; bStatus=TRUE; pConvert = 0; pVirDev = new VirtualDevice; @@ -1870,6 +1872,8 @@ BOOL WMFWriter::WriteWMF( const GDIMetaFile& rMTF, SvStream& rTargetStream, CountActionsAndBitmaps(rMTF); WriteHeader(rMTF,bPlaceable); + if( bEmbedEMF ) + WriteEmbeddedEMF( rMTF ); WMFRecord_SetWindowOrg(Point(0,0)); WMFRecord_SetWindowExt(rMTF.GetPrefSize()); WMFRecord_SetBkMode( TRUE ); @@ -1948,3 +1952,79 @@ USHORT WMFWriter::CalcSaveTargetMapMode(MapMode& rMapMode, return nDivisor; } + +// ------------------------------------------------------------------------ + +void WMFWriter::WriteEmbeddedEMF( const GDIMetaFile& rMTF ) +{ + EMFWriter aEMFWriter; + SvMemoryStream aStream; + if( aEMFWriter.WriteEMF( rMTF, aStream ) ) + { + aStream.Seek( 0 ); + sal_Size nTotalSize = aStream.GetSize(); + if( nTotalSize > SAL_MAX_UINT32 ) + return; + sal_uInt32 nRemainingSize = static_cast< sal_uInt32 >( nTotalSize ); + sal_uInt32 nRecCounts = ( (nTotalSize - 1) / 0x2000 ) + 1; + sal_uInt16 nCheckSum = 0, nWord; + + sal_uInt32 nPos = 0; + + while( nPos + 1 < nTotalSize ) + { + aStream >> nWord; + nCheckSum ^= nWord; + nPos += 2; + } + + nCheckSum = static_cast< sal_uInt16 >( nCheckSum * -1 ); + + aStream.Seek( 0 ); + while( nRemainingSize > 0 ) + { + sal_uInt32 nCurSize; + if( nRemainingSize > 0x2000 ) + { + nCurSize = 0x2000; + nRemainingSize -= 0x2000; + } + else + { + nCurSize = nRemainingSize; + nRemainingSize = 0; + } + WriteEMFRecord( aStream, + nCurSize, + nRemainingSize, + nTotalSize, + nRecCounts, + nCheckSum ); + nCheckSum = 0; + } + } +} + +// ------------------------------------------------------------------------ + +void WMFWriter::WriteEMFRecord( SvMemoryStream& rStream, sal_uInt32 nCurSize, sal_uInt32 nRemainingSize, + sal_uInt32 nTotalSize, sal_uInt32 nRecCounts, sal_uInt16 nCheckSum ) +{ + // according to http://msdn.microsoft.com/en-us/library/dd366152%28PROT.13%29.aspx + WriteRecordHeader( 0, W_META_ESCAPE ); + *pWMF << (sal_uInt16)W_MFCOMMENT // same as META_ESCAPE_ENHANCED_METAFILE + << (sal_uInt16)( nCurSize + 34 ) // we will always have a 34 byte escape header: + << (sal_uInt32) 0x43464D57 // WMFC + << (sal_uInt32) 0x00000001 // Comment type + << (sal_uInt32) 0x00010000 // version + << nCheckSum // check sum + << (sal_uInt32) 0 // flags = 0 + << nRecCounts // total number of records + << nCurSize // size of this record's data + << nRemainingSize // remaining size of data in following records, missing in MSDN documentation + << nTotalSize; // total size of EMF stream + + pWMF->Write( static_cast< const sal_Char* >( rStream.GetData() ) + rStream.Tell(), nCurSize ); + rStream.SeekRel( nCurSize ); + UpdateRecordHeader(); +} diff --git a/svtools/source/filter.vcl/wmf/wmfwr.hxx b/svtools/source/filter.vcl/wmf/wmfwr.hxx index 48986a280404..a98b496a17e2 100644 --- a/svtools/source/filter.vcl/wmf/wmfwr.hxx +++ b/svtools/source/filter.vcl/wmf/wmfwr.hxx @@ -128,6 +128,8 @@ private: ULONG nWrittenBitmaps; // Anzahl der bereits geschriebenen Bitmaps ULONG nActBitmapPercent; // Wieviel Prozent die naechste Bitmap schon geschrieben ist. + BOOL bEmbedEMF; // optionally embedd EMF data into WMF + void MayCallback(); // Berechnet anhand der obigen 5 Parameter eine Prozentzahl // und macht dann ggf. einen Callback. Setzt bStatus auf FALSE wenn User abbrechen @@ -207,6 +209,13 @@ private: void WriteHeader(const GDIMetaFile & rMTF, BOOL bPlaceable); void UpdateHeader(); + void WriteEmbeddedEMF( const GDIMetaFile& rMTF ); + void WriteEMFRecord( SvMemoryStream& rStream, sal_uInt32 nCurSize, + sal_uInt32 nRemainingSize, + sal_uInt32 nTotalSize, + sal_uInt32 nRecCounts, + sal_uInt16 nCheckSum ); + USHORT CalcSaveTargetMapMode(MapMode& rMapMode, const Size& rPrefSize); public: -- cgit From a79c517a0ca64c79b3b2694b19b28b81dec2346e Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 3 Dec 2009 17:51:33 +0100 Subject: vcl108: #i106833# sort encoding to get correct subsetted font --- vcl/unx/source/printergfx/glyphset.cxx | 38 +++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/vcl/unx/source/printergfx/glyphset.cxx b/vcl/unx/source/printergfx/glyphset.cxx index 156517d98220..5adff6683267 100644 --- a/vcl/unx/source/printergfx/glyphset.cxx +++ b/vcl/unx/source/printergfx/glyphset.cxx @@ -46,6 +46,7 @@ #include #include +#include using namespace vcl; using namespace psp; @@ -785,6 +786,17 @@ GlyphSet::PSUploadEncoding(osl::File* pOutFile, PrinterGfx &rGfx) return sal_True; } +struct EncEntry +{ + sal_uChar aEnc; + long aGID; + + EncEntry() : aEnc( 0 ), aGID( 0 ) {} + + bool operator<( const EncEntry& rRight ) const + { return aEnc < rRight.aEnc; } +}; + static void CreatePSUploadableFont( TrueTypeFont* pSrcFont, FILE* pTmpFile, const char* pGlyphSetName, int nGlyphCount, /*const*/ sal_uInt16* pRequestedGlyphs, /*const*/ sal_uChar* pEncoding, @@ -796,17 +808,29 @@ static void CreatePSUploadableFont( TrueTypeFont* pSrcFont, FILE* pTmpFile, if( bAllowType42 ) nTargetMask |= FontSubsetInfo::TYPE42_FONT; + std::vector< EncEntry > aSorted( nGlyphCount, EncEntry() ); + for( int i = 0; i < nGlyphCount; i++ ) + { + aSorted[i].aEnc = pEncoding[i]; + aSorted[i].aGID = pRequestedGlyphs[i]; + } + + std::stable_sort( aSorted.begin(), aSorted.end() ); + + std::vector< sal_uChar > aEncoding( nGlyphCount ); + std::vector< long > aRequestedGlyphs( nGlyphCount ); + + for( int i = 0; i < nGlyphCount; i++ ) + { + aEncoding[i] = aSorted[i].aEnc; + aRequestedGlyphs[i] = aSorted[i].aGID; + } + FontSubsetInfo aInfo; aInfo.LoadFont( pSrcFont ); -#if 1 // TODO: remove 16bit->long conversion when input args has been changed - long aRequestedGlyphs[256]; - for( int i = 0; i < nGlyphCount; ++i ) - aRequestedGlyphs[i] = pRequestedGlyphs[i]; -#endif - aInfo.CreateFontSubset( nTargetMask, pTmpFile, pGlyphSetName, - aRequestedGlyphs, pEncoding, nGlyphCount, NULL ); + &aRequestedGlyphs[0], &aEncoding[0], nGlyphCount, NULL ); } sal_Bool -- cgit From 655b08e832103e37a5fc59cd1d9bc50d7a2ad4c0 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 4 Dec 2009 11:35:30 +0100 Subject: printerpullpages: #i92516# print to file option not persistent anymore --- vcl/source/window/printdlg.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx index daf25324e263..649ca21a32b8 100644 --- a/vcl/source/window/printdlg.cxx +++ b/vcl/source/window/printdlg.cxx @@ -697,12 +697,14 @@ void PrintDialog::OutputOptPage::setupLayout() void PrintDialog::OutputOptPage::readFromSettings() { + #if 0 SettingsConfigItem* pItem = SettingsConfigItem::get(); rtl::OUString aValue; aValue = pItem->getValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PrintDialog" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ToFile" ) ) ); maToFileBox.Check( aValue.equalsIgnoreAsciiCaseAscii( "true" ) ); + #endif } void PrintDialog::OutputOptPage::storeToSettings() -- cgit From 66ad3e12c985a02c98785280b6660527f9a03dbf Mon Sep 17 00:00:00 2001 From: sj Date: Fri, 4 Dec 2009 16:59:41 +0100 Subject: impress181: #i105480#: applied patch (using HeaderExtionsion2 now, fixed EMR_EOF record, added bounding rectangle to EMR_FILLPATH and EMR_STROKEPATH, now closing pathes properly, resolution changed from pixel to 100th_mm) --- svtools/source/filter.vcl/wmf/emfwr.cxx | 103 +++++++++++++++++++++----------- svtools/source/filter.vcl/wmf/emfwr.hxx | 1 + 2 files changed, 68 insertions(+), 36 deletions(-) diff --git a/svtools/source/filter.vcl/wmf/emfwr.cxx b/svtools/source/filter.vcl/wmf/emfwr.cxx index df56afc4a250..dc193e489166 100644 --- a/svtools/source/filter.vcl/wmf/emfwr.cxx +++ b/svtools/source/filter.vcl/wmf/emfwr.cxx @@ -162,6 +162,8 @@ #define TA_RTLREADING 256 #define TA_MASK (TA_BASELINE+TA_CENTER+TA_UPDATECP+TA_RTLREADING) +#define MM_ANISOTROPIC 8 + // ------------- // - EMFWriter - // ------------- @@ -181,19 +183,37 @@ BOOL EMFWriter::WriteEMF( const GDIMetaFile& rMtf, SvStream& rOStm, FilterConfig maVDev.SetMapMode( rMtf.GetPrefMapMode() ); mpFilterConfigItem = pFilterConfigItem; + // don't work with pixel as destination map mode -> higher resolution preferrable + maDestMapMode.SetMapUnit( MAP_100TH_MM ); + const Size aMtfSizePix( maVDev.LogicToPixel( rMtf.GetPrefSize(), rMtf.GetPrefMapMode() ) ); const Size aMtfSizeLog( maVDev.LogicToLogic( rMtf.GetPrefSize(), rMtf.GetPrefMapMode(), MAP_100TH_MM ) ); // seek over header - rOStm.SeekRel( 100 ); + // use [MS-EMF 2.2.11] HeaderExtension2 Object, otherwise resulting EMF cannot be converted with GetWinMetaFileBits() + rOStm.SeekRel( 108 ); // write initial values - ImplBeginRecord( WIN_EMR_SETWINDOWORGEX ); - (*mpStm) << (INT32) 0 << (INT32) 0; + + // set 100th mm map mode in EMF + ImplBeginRecord( WIN_EMR_SETMAPMODE ); + (*mpStm) << (INT32) MM_ANISOTROPIC; + ImplEndRecord(); + + ImplBeginRecord( WIN_EMR_SETVIEWPORTEXTEX ); + (*mpStm) << (INT32) maVDev.ImplGetDPIX() << (INT32) maVDev.ImplGetDPIY(); ImplEndRecord(); ImplBeginRecord( WIN_EMR_SETWINDOWEXTEX ); - (*mpStm) << (INT32) aMtfSizePix.Width() << (INT32) aMtfSizePix.Height(); + (*mpStm) << (INT32) 2540 << (INT32) 2540; + ImplEndRecord(); + + ImplBeginRecord( WIN_EMR_SETVIEWPORTORGEX ); + (*mpStm) << (INT32) 0 << (INT32) 0; + ImplEndRecord(); + + ImplBeginRecord( WIN_EMR_SETWINDOWORGEX ); + (*mpStm) << (INT32) 0 << (INT32) 0; ImplEndRecord(); ImplWriteRasterOp( ROP_OVERPAINT ); @@ -207,7 +227,7 @@ BOOL EMFWriter::WriteEMF( const GDIMetaFile& rMtf, SvStream& rOStm, FilterConfig ImplBeginRecord( WIN_EMR_EOF ); (*mpStm)<< (sal_uInt32)0 // nPalEntries - << (sal_uInt32)0x16 // offPalEntries + << (sal_uInt32)0x10 // offPalEntries << (sal_uInt32)0x14; // nSizeLast ImplEndRecord(); @@ -215,14 +235,15 @@ BOOL EMFWriter::WriteEMF( const GDIMetaFile& rMtf, SvStream& rOStm, FilterConfig // write header const ULONG nEndPos = mpStm->Tell(); mpStm->Seek( nHeaderPos ); - (*mpStm) << (UINT32) 0x00000001 << (UINT32) 100; - (*mpStm) << (INT32) 0 << (INT32) 0 << (INT32) ( aMtfSizePix.Width() - 1 ) << (INT32) ( aMtfSizePix.Height() - 1 ); - (*mpStm) << (INT32) 0 << (INT32) 0 << (INT32) ( aMtfSizeLog.Width() - 1 ) << (INT32) ( aMtfSizeLog.Height() - 1 ); - (*mpStm) << (UINT32) 0x464d4520 << (UINT32) 0x10000 << (UINT32) ( nEndPos - nHeaderPos ); - (*mpStm) << (UINT32) mnRecordCount << (UINT16) ( mnHandleCount + 1 ) << (UINT16) 0 << (UINT32) 0 << (UINT32) 0 << (UINT32) 0; - (*mpStm) << (INT32) aMtfSizePix.Width() << (INT32) aMtfSizePix.Height(); - (*mpStm) << (INT32) ( aMtfSizeLog.Width() / 100 ) << (INT32) ( aMtfSizeLog.Height() / 100 ); - (*mpStm) << (UINT32) 0 << (UINT32) 0 << (UINT32) 0; + (*mpStm) << (UINT32) 0x00000001 << (UINT32) 108 //use [MS-EMF 2.2.11] HeaderExtension2 Object + << (INT32) 0 << (INT32) 0 << (INT32) ( aMtfSizePix.Width() - 1 ) << (INT32) ( aMtfSizePix.Height() - 1 ) + << (INT32) 0 << (INT32) 0 << (INT32) ( aMtfSizeLog.Width() - 1 ) << (INT32) ( aMtfSizeLog.Height() - 1 ) + << (UINT32) 0x464d4520 << (UINT32) 0x10000 << (UINT32) ( nEndPos - nHeaderPos ) + << (UINT32) mnRecordCount << (UINT16) ( mnHandleCount + 1 ) << (UINT16) 0 << (UINT32) 0 << (UINT32) 0 << (UINT32) 0 + << (INT32) aMtfSizePix.Width() << (INT32) aMtfSizePix.Height() + << (INT32) ( aMtfSizeLog.Width() / 100 ) << (INT32) ( aMtfSizeLog.Height() / 100 ) + << (UINT32) 0 << (UINT32) 0 << (UINT32) 0 + << (INT32) ( aMtfSizeLog.Width() * 10 ) << (INT32) ( aMtfSizeLog.Height() * 10 ); //use [MS-EMF 2.2.11] HeaderExtension2 Object mpStm->Seek( nEndPos ); delete[] mpHandlesUsed; @@ -520,35 +541,32 @@ void EMFWriter::ImplWriteRasterOp( RasterOp eRop ) void EMFWriter::ImplWriteExtent( long nExtent ) { - const Size aSize( maVDev.LogicToPixel( Size( nExtent, nExtent ) ) ); - (*mpStm) << (INT32) aSize.Width(); + nExtent = maVDev.LogicToLogic( Size( nExtent, 0 ), maVDev.GetMapMode(), maDestMapMode ).Width(); + (*mpStm) << (INT32) nExtent; } // ----------------------------------------------------------------------------- void EMFWriter::ImplWritePoint( const Point& rPoint ) { - const Point aPoint( maVDev.LogicToPixel( rPoint ) ); - - (*mpStm) << (INT32) aPoint.X() << (INT32) aPoint.Y(); + const Point aPoint( maVDev.LogicToLogic( rPoint, maVDev.GetMapMode(), maDestMapMode )); + (*mpStm) << (INT32) aPoint.X() << (INT32) aPoint.Y(); } // ----------------------------------------------------------------------------- void EMFWriter::ImplWriteSize( const Size& rSize) { - const Size aSize( maVDev.LogicToPixel( rSize ) ); - - (*mpStm) << (INT32) aSize.Width() << (INT32) aSize.Height(); + const Size aSize( maVDev.LogicToLogic( rSize, maVDev.GetMapMode(), maDestMapMode )); + (*mpStm) << (INT32) aSize.Width() << (INT32) aSize.Height(); } // ----------------------------------------------------------------------------- void EMFWriter::ImplWriteRect( const Rectangle& rRect ) { - const Rectangle aRect( maVDev.LogicToPixel( rRect ) ); - - (*mpStm) << aRect.Left() << aRect.Top() << aRect.Right() << aRect.Bottom(); + const Rectangle aRect( maVDev.LogicToLogic ( rRect, maVDev.GetMapMode(), maDestMapMode )); + (*mpStm) << aRect.Left() << aRect.Top() << aRect.Right() << aRect.Bottom(); } // ----------------------------------------------------------------------------- @@ -647,12 +665,20 @@ void EMFWriter::ImplWritePath( const PolyPolygon& rPolyPoly, sal_Bool bClosed ) const Polygon& rPoly = rPolyPoly[ i ]; while ( n < rPoly.GetSize() ) { - sal_uInt16 nBezPoints = 0; - if ( n ) + if( n == 0 ) { - while ( ( ( nBezPoints + n + 2 ) < rPoly.GetSize() ) && ( rPoly.GetFlags( nBezPoints + n ) == POLY_CONTROL ) ) - nBezPoints += 3; + ImplBeginRecord( WIN_EMR_MOVETOEX ); + ImplWritePoint( rPoly[ 0 ] ); + ImplEndRecord(); + n++; + continue; } + + sal_uInt16 nBezPoints = 0; + + while ( ( ( nBezPoints + n + 2 ) < rPoly.GetSize() ) && ( rPoly.GetFlags( nBezPoints + n ) == POLY_CONTROL ) ) + nBezPoints += 3; + if ( nBezPoints ) { ImplBeginRecord( WIN_EMR_POLYBEZIERTO ); @@ -672,22 +698,26 @@ void EMFWriter::ImplWritePath( const PolyPolygon& rPolyPoly, sal_Bool bClosed ) sal_uInt16 nPoints = 1; while( ( nPoints + n ) < rPoly.GetSize() && ( rPoly.GetFlags( nPoints + n ) != POLY_CONTROL ) ) nPoints++; - ImplBeginRecord( WIN_EMR_MOVETOEX ); - ImplWritePoint( rPoly[ n ] ); - ImplEndRecord(); + if ( nPoints > 1 ) { ImplBeginRecord( WIN_EMR_POLYLINETO ); - Polygon aNewPoly( nPoints ); - aNewPoly[ 0 ] = rPoly[ n ]; - for ( o = 1; o < nPoints; o++ ) - aNewPoly[ o ] = rPoly[ n + o ]; + Polygon aNewPoly( nPoints + 1 ); + aNewPoly[ 0 ] = rPoly[ n - 1]; + for ( o = 1; o <= nPoints; o++ ) + aNewPoly[ o ] = rPoly[ n - 1 + o ]; ImplWriteRect( aNewPoly.GetBoundRect() ); - (*mpStm) << (sal_uInt32)( nPoints - 1 ); + (*mpStm) << (sal_uInt32)( nPoints ); for( o = 1; o < aNewPoly.GetSize(); o++ ) ImplWritePoint( aNewPoly[ o ] ); ImplEndRecord(); } + else + { + ImplBeginRecord( WIN_EMR_LINETO ); + ImplWritePoint( rPoly[ n ] ); + ImplEndRecord(); + } n = n + nPoints; } if ( bClosed && ( n == rPoly.GetSize() ) ) @@ -700,6 +730,7 @@ void EMFWriter::ImplWritePath( const PolyPolygon& rPolyPoly, sal_Bool bClosed ) ImplBeginRecord( WIN_EMR_ENDPATH ); ImplEndRecord(); ImplBeginRecord( bClosed ? WIN_EMR_FILLPATH : WIN_EMR_STROKEPATH ); + ImplWriteRect( rPolyPoly.GetBoundRect() ); ImplEndRecord(); } diff --git a/svtools/source/filter.vcl/wmf/emfwr.hxx b/svtools/source/filter.vcl/wmf/emfwr.hxx index 150aa1692ade..2994a10d81f1 100644 --- a/svtools/source/filter.vcl/wmf/emfwr.hxx +++ b/svtools/source/filter.vcl/wmf/emfwr.hxx @@ -47,6 +47,7 @@ class EMFWriter private: VirtualDevice maVDev; + MapMode maDestMapMode; FilterConfigItem* mpFilterConfigItem; SvStream* mpStm; BOOL* mpHandlesUsed; -- cgit From d5adb4b029ec99f46c114f238bdd5ebc5c2d768f Mon Sep 17 00:00:00 2001 From: hdu Date: Mon, 7 Dec 2009 09:43:27 +0100 Subject: #i107415# fix caching problem for big-sized graphite fonts (thanks kstribley!) --- vcl/inc/vcl/graphite_cache.hxx | 4 +++- vcl/source/glyphs/graphite_layout.cxx | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/graphite_cache.hxx b/vcl/inc/vcl/graphite_cache.hxx index 5a537c5f1e48..73e3e2c9f1fe 100644 --- a/vcl/inc/vcl/graphite_cache.hxx +++ b/vcl/inc/vcl/graphite_cache.hxx @@ -58,10 +58,11 @@ public: void clear(); #ifdef GRCACHE_REUSE_VECTORS void setGlyphVectors(long nWidth, GraphiteLayout::Glyphs & vGlyphs, std::vector vCharDxs, - std::vector & vChar2Base, std::vector & vGlyph2Char) + std::vector & vChar2Base, std::vector & vGlyph2Char, float fScale) { clearVectors(); mnWidth = nWidth; + m_fontScale = fScale; mvGlyphs.insert(mvGlyphs.begin(), vGlyphs.begin(), vGlyphs.end()); mvCharDxs.insert(mvCharDxs.begin(),vCharDxs.begin(),vCharDxs.end()); mvChar2BaseGlyph.insert(mvChar2BaseGlyph.begin(),vChar2Base.begin(),vChar2Base.end()); @@ -78,6 +79,7 @@ public: const std::vector & charDxs() const { return mvCharDxs; } const std::vector & char2BaseGlyph() const { return mvChar2BaseGlyph; } const std::vector & glyph2Char() const { return mvGlyph2Char; } + float & fontScale() { return m_fontScale; } #endif private: rtl::OUString * m_rope; diff --git a/vcl/source/glyphs/graphite_layout.cxx b/vcl/source/glyphs/graphite_layout.cxx index 86dee2749efa..c09062108dda 100644 --- a/vcl/source/glyphs/graphite_layout.cxx +++ b/vcl/source/glyphs/graphite_layout.cxx @@ -720,6 +720,7 @@ bool GraphiteLayout::LayoutGlyphs(ImplLayoutArgs& rArgs, gr::Segment * pSegment) #ifdef GRCACHE_REUSE_VECTORS // if we have an exact match, then we can reuse the glyph vectors from before if (pSegRecord && (pSegRecord->glyphs().size() > 0) && + (pSegRecord->fontScale() == mfScaling) && !(SAL_LAYOUT_FOR_FALLBACK & rArgs.mnFlags) ) { mnWidth = pSegRecord->width(); @@ -765,7 +766,8 @@ bool GraphiteLayout::LayoutGlyphs(ImplLayoutArgs& rArgs, gr::Segment * pSegment) !(SAL_LAYOUT_FOR_FALLBACK & rArgs.mnFlags)) { pSegRecord->setGlyphVectors(mnWidth, mvGlyphs, mvCharDxs, - mvChar2BaseGlyph, mvGlyph2Char); + mvChar2BaseGlyph, mvGlyph2Char, + mfScaling); } #endif #endif -- cgit From 26e6d1abc8e5c083bfc96d12d7b51a7baee0eabd Mon Sep 17 00:00:00 2001 From: sj Date: Mon, 7 Dec 2009 12:00:14 +0100 Subject: impress181: #i107457#: applied patch (WMF/EMF import, text background is now correctly set) --- svtools/source/filter.vcl/wmf/winmtf.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/svtools/source/filter.vcl/wmf/winmtf.cxx b/svtools/source/filter.vcl/wmf/winmtf.cxx index 3db3e6957e41..58dfdec45ee1 100644 --- a/svtools/source/filter.vcl/wmf/winmtf.cxx +++ b/svtools/source/filter.vcl/wmf/winmtf.cxx @@ -1522,9 +1522,9 @@ void WinMtfOutput::DrawText( Point& rPosition, String& rText, sal_Int32* pDXArry aTmp.SetFillColor( maBkColor ); if( mnBkMode == TRANSPARENT ) - maFont.SetTransparent( sal_True ); + aTmp.SetTransparent( sal_True ); else - maFont.SetTransparent( sal_False ); + aTmp.SetTransparent( sal_False ); if ( ( mnTextAlign & TA_BASELINE) == TA_BASELINE ) aTmp.SetAlign( ALIGN_BASELINE ); -- cgit From 6265bf19dd38b9c3dfd81828dc07ad579d02065d Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 7 Dec 2009 16:26:07 +0100 Subject: vcl108: #b6906380# fix desktop switch logic --- vcl/source/window/window.cxx | 3 +++ vcl/unx/gtk/window/gtkframe.cxx | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/vcl/source/window/window.cxx b/vcl/source/window/window.cxx index 63bf407ce49f..d2683f918931 100644 --- a/vcl/source/window/window.cxx +++ b/vcl/source/window/window.cxx @@ -4755,7 +4755,10 @@ void Window::doLazyDelete() SystemWindow* pSysWin = dynamic_cast(this); DockingWindow* pDockWin = dynamic_cast(this); if( pSysWin || ( pDockWin && pDockWin->IsFloatingMode() ) ) + { + Show( FALSE ); SetParent( ImplGetDefaultWindow() ); + } vcl::LazyDeletor::Delete( this ); } diff --git a/vcl/unx/gtk/window/gtkframe.cxx b/vcl/unx/gtk/window/gtkframe.cxx index eff7319d6efc..9d401d84770d 100644 --- a/vcl/unx/gtk/window/gtkframe.cxx +++ b/vcl/unx/gtk/window/gtkframe.cxx @@ -1307,7 +1307,7 @@ void GtkSalFrame::Show( BOOL bVisible, BOOL bNoActivate ) setMinMaxSize(); // #i45160# switch to desktop where a dialog with parent will appear - if( m_pParent && m_pParent->m_nWorkArea != m_nWorkArea ) + if( m_pParent && m_pParent->m_nWorkArea != m_nWorkArea && GTK_WIDGET_MAPPED(m_pParent->m_pWindow) ) getDisplay()->getWMAdaptor()->switchToWorkArea( m_pParent->m_nWorkArea ); if( isFloatGrabWindow() && -- cgit From 021d695170ab31cd91163fbbf58d30f8643a6a6f Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 7 Dec 2009 18:18:45 +0100 Subject: printerpullpages: #i91478# fix a scaling issue in native mac dialog --- vcl/aqua/source/gdi/aquaprintaccessoryview.mm | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm index 9e37c0632f4e..798fefef1b25 100644 --- a/vcl/aqua/source/gdi/aquaprintaccessoryview.mm +++ b/vcl/aqua/source/gdi/aquaprintaccessoryview.mm @@ -102,7 +102,7 @@ class ControllerProperties PrintAccessoryViewState* i_pState ) : mpController( i_pController ), mnNextTag( 0 ), - mnLastPageCount( i_pController->getPageCountProtected() ), + mnLastPageCount( i_pController->getFilteredPageCount() ), mpState( i_pState ), mpOp( i_pOp ), mpAccessoryView( i_pAccessoryView ), @@ -130,7 +130,7 @@ class ControllerProperties // TODO: refresh page count etc from mpController // page range may have changed depending on options - sal_Int32 nPages = mpController->getPageCountProtected(); + sal_Int32 nPages = mpController->getFilteredPageCount(); #if OSL_DEBUG_LEVEL > 1 if( nPages != mnLastPageCount ) fprintf( stderr, "trouble: number of pages changed from %ld to %ld !\n", mnLastPageCount, nPages ); @@ -314,6 +314,9 @@ class ControllerProperties GDIMetaFile aMtf; PrinterController::PageSize aPageSize( mpController->getFilteredPageFile( i_nPage, aMtf, false ) ); VirtualDevice aDev; + // see salprn.cxx, currently we pretend to be a 720dpi device on printers + aDev.SetReferenceDevice( 720, 720 ); + aDev.EnableOutput( TRUE ); Size aLogicSize( aDev.PixelToLogic( aPixelSize, MapMode( MAP_100TH_MM ) ) ); double fScaleX = double(aLogicSize.Width())/double(aPageSize.aSize.Width()); double fScaleY = double(aLogicSize.Height())/double(aPageSize.aSize.Height()); -- cgit From 96be2a9615b9243e59cc103d60c8cb5c9340df52 Mon Sep 17 00:00:00 2001 From: "Thomas Lange [tl]" Date: Tue, 8 Dec 2009 13:00:42 +0100 Subject: #i105728#, #i105730#, #i105727# intelli UI thingies --- vcl/inc/vcl/print.hxx | 7 +++++-- vcl/source/gdi/print3.cxx | 6 ++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/print.hxx b/vcl/inc/vcl/print.hxx index e91e3db0c9d7..daea0c941dd0 100644 --- a/vcl/inc/vcl/print.hxx +++ b/vcl/inc/vcl/print.hxx @@ -600,19 +600,22 @@ class VCL_DLLPUBLIC PrinterOptionsHelper sal_Bool mbAttachToDependency; rtl::OUString maGroupHint; sal_Bool mbInternalOnly; + sal_Bool mbEnabled; com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > maAddProps; UIControlOptions( const rtl::OUString& i_rDependsOnName = rtl::OUString(), sal_Int32 i_nDependsOnEntry = -1, sal_Bool i_bAttachToDependency = sal_False, const rtl::OUString& i_rGroupHint = rtl::OUString(), - sal_Bool i_bInternalOnly = sal_False + sal_Bool i_bInternalOnly = sal_False, + sal_Bool i_bEnabled = sal_True ) : maDependsOnName( i_rDependsOnName ) , mnDependsOnEntry( i_nDependsOnEntry ) , mbAttachToDependency( i_bAttachToDependency ) , maGroupHint( i_rGroupHint ) - , mbInternalOnly( i_bInternalOnly ) {} + , mbInternalOnly( i_bInternalOnly ) + , mbEnabled( i_bEnabled ) {} }; // general control diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index 2b16d2c611fd..e687fce01d1f 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -1562,6 +1562,7 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, + i_rControlOptions.maAddProps.getLength() // additional props + (i_rControlOptions.maGroupHint.getLength() ? 1 : 0) // grouping + (i_rControlOptions.mbInternalOnly ? 1 : 0) // internal hint + + (i_rControlOptions.mbEnabled ? 0 : 1) // enabled ; if( i_rControlOptions.maDependsOnName.getLength() ) { @@ -1616,6 +1617,11 @@ Any PrinterOptionsHelper::getUIControlOpt( const rtl::OUString& i_rTitle, aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InternalUIOnly" ) ); aCtrl[nUsed++].Value <<= sal_True; } + if( ! i_rControlOptions.mbEnabled ) + { + aCtrl[nUsed ].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Enabled" ) ); + aCtrl[nUsed++].Value <<= sal_False; + } sal_Int32 nAddProps = i_rControlOptions.maAddProps.getLength(); for( sal_Int32 i = 0; i < nAddProps; i++ ) -- cgit From 6c1aa68d76169c11c1f56a19ce4f12393e6bca51 Mon Sep 17 00:00:00 2001 From: sj Date: Tue, 8 Dec 2009 18:05:50 +0100 Subject: impress181: #i97966#: fixed resource problem, now the error message is notifying a read error instead of "Move background page assignment" when trying to load an encrypted PPT document --- svtools/source/misc/ehdl.cxx | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/svtools/source/misc/ehdl.cxx b/svtools/source/misc/ehdl.cxx index 6e89193f1b6b..9031c8c7fdd1 100644 --- a/svtools/source/misc/ehdl.cxx +++ b/svtools/source/misc/ehdl.cxx @@ -321,16 +321,21 @@ BOOL SfxErrorHandler::GetClassString(ULONG lClassId, String &rStr) const */ { - - ResId aId(RID_ERRHDL, *pMgr); - ErrorResource_Impl aEr(aId, (USHORT)lClassId); - if(aEr) + BOOL bRet = FALSE; + com::sun::star::lang::Locale aLocale( Application::GetSettings().GetUILocale() ); + ResMgr* pResMgr = ResMgr::CreateResMgr(CREATEVERSIONRESMGR_NAME(ofa), aLocale ); + if( pResMgr ) { - rStr=((ResString)aEr).GetString(); - return TRUE; + ResId aId(RID_ERRHDL, *pResMgr ); + ErrorResource_Impl aEr(aId, (USHORT)lClassId); + if(aEr) + { + rStr=((ResString)aEr).GetString(); + bRet = TRUE; + } } - else - return FALSE; + delete pResMgr; + return bRet; } //------------------------------------------------------------------------- @@ -379,10 +384,10 @@ BOOL SfxErrorHandler::GetErrorString( BOOL bRet = FALSE; rStr=String(SvtResId(RID_ERRHDL_CLASS)); - ResId *pResId = new ResId(nId, *pMgr); + ResId aResId(nId, *pMgr); { - ErrorResource_Impl aEr(*pResId, (USHORT)lErrId); + ErrorResource_Impl aEr(aResId, (USHORT)lErrId); if(aEr) { ResString aErrorString(aEr); @@ -408,7 +413,6 @@ BOOL SfxErrorHandler::GetErrorString( rStr.SearchAndReplace(String::CreateFromAscii( "$(CLASS)" ),aErrStr); } - delete pResId; return bRet; } -- cgit From ad7022af48b1b91e605c86ebf1eb91ce66635385 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 8 Dec 2009 18:43:39 +0100 Subject: vcl108: #i104264# use caret width setting from system --- vcl/win/source/window/salframe.cxx | 5 +++++ 1 file changed, 5 insertions(+) mode change 100644 => 100755 vcl/win/source/window/salframe.cxx diff --git a/vcl/win/source/window/salframe.cxx b/vcl/win/source/window/salframe.cxx old mode 100644 new mode 100755 index 53f822a1e409..77d9a702d186 --- a/vcl/win/source/window/salframe.cxx +++ b/vcl/win/source/window/salframe.cxx @@ -2977,6 +2977,11 @@ void WinSalFrame::UpdateSettings( AllSettings& rSettings ) aStyleSettings.SetCheckedColor( Color( nRed, nGreen, nBlue ) ); } + // caret width + DWORD nCaretWidth = 2; + if( SystemParametersInfo( SPI_GETCARETWIDTH, 0, &nCaretWidth, 0 ) ) + aStyleSettings.SetCursorSize( nCaretWidth ); + // High contrast HIGHCONTRAST hc; hc.cbSize = sizeof( HIGHCONTRAST ); -- cgit From 0d1debd8e0179006d80f7f9ca443d21730f14dae Mon Sep 17 00:00:00 2001 From: hdu Date: Wed, 9 Dec 2009 13:19:49 +0100 Subject: #i107552# ignore SFNT fonts with broken name table (thanks cmc!) --- vcl/source/fontsubset/sft.cxx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/vcl/source/fontsubset/sft.cxx b/vcl/source/fontsubset/sft.cxx index 0accc42af968..964d6a93ac3c 100644 --- a/vcl/source/fontsubset/sft.cxx +++ b/vcl/source/fontsubset/sft.cxx @@ -1094,6 +1094,14 @@ static void GetNames(TrueTypeFont *t) const sal_uInt8* table = getTable( t, O_name ); int nTableSize = getTableSize(t, O_name); + if (nTableSize < 4) + { +#if OSL_DEBUG_LEVEL > 1 + fprintf(stderr, "O_name table too small\n"); +#endif + return; + } + sal_uInt16 n = GetUInt16(table, 2, 1); int i, r; sal_Bool bPSNameOK = sal_True; @@ -1681,7 +1689,6 @@ int OpenTTFontFile( const char* fname, sal_uInt32 facenum, TrueTypeFont** ttf ) goto cleanup; } - if (((*ttf)->ptr = (sal_uInt8 *) mmap(0, (*ttf)->fsize, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { ret = SF_MEMORY; goto cleanup; @@ -2702,7 +2709,7 @@ void GetTTGlobalFontInfo(TrueTypeFont *ttf, TTGlobalFontInfo *info) } table = getTable(ttf, O_post); - if (table) { + if (table && getTableSize(ttf, O_post) >= 12+sizeof(sal_uInt32)) { info->pitch = GetUInt32(table, 12, 1); info->italicAngle = GetInt32(table, 4, 1); } @@ -2808,6 +2815,15 @@ int GetTTNameRecords(TrueTypeFont *ttf, NameRecord **nr) { const sal_uInt8* table = getTable(ttf, O_name); int nTableSize = getTableSize(ttf, O_name ); + + if (nTableSize < 6) + { +#if OSL_DEBUG_LEVEL > 1 + fprintf(stderr, "O_name table too small\n"); +#endif + return 0; + } + sal_uInt16 n = GetUInt16(table, 2, 1); int nStrBase = GetUInt16(table, 4, 1); int i; -- cgit From 64e8661d76db6b02396d82b7d1f28dd3088a334f Mon Sep 17 00:00:00 2001 From: "Thomas Lange [tl]" Date: Fri, 11 Dec 2009 11:34:10 +0100 Subject: #i106926# fixed hidden text in view when cancelling print to file --- vcl/source/gdi/print3.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/vcl/source/gdi/print3.cxx b/vcl/source/gdi/print3.cxx index e687fce01d1f..6778cfbc867e 100644 --- a/vcl/source/gdi/print3.cxx +++ b/vcl/source/gdi/print3.cxx @@ -436,7 +436,12 @@ void Printer::ImplPrintJob( const boost::shared_ptr& i_pContr { rtl::OUString aFile = queryFile( pController->getPrinter().get() ); if( ! aFile.getLength() ) + { + GDIMetaFile aPageFile; + i_pController->setLastPage( sal_True ); + i_pController->getFilteredPageFile( 0, aPageFile ); return; + } pController->setValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LocalFileName" ) ), makeAny( aFile ) ); } -- cgit From d5a8b4a9cf542b6567ccd69a67a96ade941cfba3 Mon Sep 17 00:00:00 2001 From: sj Date: Fri, 11 Dec 2009 12:22:43 +0100 Subject: impress181: #i107614#: fixed build error, dxerr9.h has been renamed to dxerr.h in the latest DirectX SDK from August 2009 --- canvas/source/directx/dx_winstuff.hxx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/canvas/source/directx/dx_winstuff.hxx b/canvas/source/directx/dx_winstuff.hxx index 1c64506c0f21..47658991e74b 100755 --- a/canvas/source/directx/dx_winstuff.hxx +++ b/canvas/source/directx/dx_winstuff.hxx @@ -89,7 +89,7 @@ #include #include - #include +// #include #i107614# removing include, it has been changed in the latest sdk fron August2009 from dxerr9.h into dxerr.h typedef IDirect3DSurface9 surface_type; @@ -97,11 +97,11 @@ #undef DrawText -#ifdef __MINGW32__ -using ::std::max; -using ::std::min; -#endif - +#ifdef __MINGW32__ +using ::std::max; +using ::std::min; +#endif + #include #ifdef min -- cgit From 5f6d2c4a5c2210efa12a8009bdaedf408197b06f Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 11 Dec 2009 15:48:06 +0100 Subject: vcl108: #i107595# fix debug compile (thanks arielch) --- vcl/unx/source/app/randrwrapper.cxx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vcl/unx/source/app/randrwrapper.cxx b/vcl/unx/source/app/randrwrapper.cxx index 8d01b64d4680..49de00d22639 100644 --- a/vcl/unx/source/app/randrwrapper.cxx +++ b/vcl/unx/source/app/randrwrapper.cxx @@ -282,6 +282,9 @@ void RandRWrapper::releaseWrapper() #include "saldisp.hxx" #include "salframe.h" +#if OSL_DEBUG_LEVEL > 1 +#include +#endif void SalDisplay::InitRandR( XLIB_Window aRoot ) const { -- cgit From 1c0ea39cacdd551310d1f263b652d0e0aefa68b6 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 15 Dec 2009 11:53:06 +0100 Subject: vcl108: #i100644# be prepared for empty invocation values --- vcl/unx/source/printer/ppdparser.cxx | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/vcl/unx/source/printer/ppdparser.cxx b/vcl/unx/source/printer/ppdparser.cxx index 95bc7bca41ca..705dcf8ccad7 100644 --- a/vcl/unx/source/printer/ppdparser.cxx +++ b/vcl/unx/source/printer/ppdparser.cxx @@ -806,20 +806,34 @@ void PPDParser::parse( ::std::list< ByteString >& rLines ) // read in more lines if necessary for multiline values aLine = aCurrentLine.Copy( nPos+1 ); - while( ! ( aLine.GetTokenCount( '"' ) & 1 ) && - line != rLines.end() ) - // while there is an even number of tokens; that m_eans - // an odd number of doubleqoutes + if( aLine.Len() ) { - // copy the newlines also - aLine += '\n'; - aLine += *line; - ++line; + while( ! ( aLine.GetTokenCount( '"' ) & 1 ) && + line != rLines.end() ) + // while there is an even number of tokens; that means + // an odd number of doubleqoutes + { + // copy the newlines also + aLine += '\n'; + aLine += *line; + ++line; + } } aLine = WhitespaceToSpace( aLine ); + // #i100644# handle a missing value (actually a broken PPD) + if( ! aLine.Len() ) + { + pValue->m_aValue = String(); + pValue->m_aValueTranslation = String(); + if( pValue->m_aOption.Len() && + aKey.CompareTo( "JCL", 3 ) != COMPARE_EQUAL ) + pValue->m_eType = eInvocation; + else + pValue->m_eType = eQuoted; + } // check for invocation or quoted value - if( aLine.GetChar(0) == '"' ) + else if( aLine.GetChar(0) == '"' ) { aLine.Erase( 0, 1 ); nTransPos = aLine.Search( '"' ); -- cgit From 51da2ee75357b631f4970517e2bccabf12e7e561 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 15 Dec 2009 12:31:08 +0100 Subject: vcl108: #i95682# omit JobPatch entries in CUPS case as CUPS adds them itself --- vcl/inc/vcl/printerinfomanager.hxx | 2 ++ vcl/unx/source/printer/cupsmgr.cxx | 4 ++++ vcl/unx/source/printer/printerinfomanager.cxx | 1 + vcl/unx/source/printergfx/printerjob.cxx | 3 +++ 4 files changed, 10 insertions(+) diff --git a/vcl/inc/vcl/printerinfomanager.hxx b/vcl/inc/vcl/printerinfomanager.hxx index 810ad428c9db..2fb6ef1c2413 100644 --- a/vcl/inc/vcl/printerinfomanager.hxx +++ b/vcl/inc/vcl/printerinfomanager.hxx @@ -136,6 +136,7 @@ protected: Type m_eType; bool m_bUseIncludeFeature; + bool m_bUseJobPatch; rtl::OUString m_aSystemDefaultPaper; bool m_bDisableCUPS; @@ -226,6 +227,7 @@ public: virtual bool addOrRemovePossible() const; bool getUseIncludeFeature() const { return m_bUseIncludeFeature; } + bool getUseJobPatch() const { return m_bUseJobPatch; } // check whether a printer's feature string contains a subfeature bool checkFeatureToken( const rtl::OUString& rPrinterName, const char* pToken ) const; diff --git a/vcl/unx/source/printer/cupsmgr.cxx b/vcl/unx/source/printer/cupsmgr.cxx index d0c7f184fb06..4c38479f1107 100644 --- a/vcl/unx/source/printer/cupsmgr.cxx +++ b/vcl/unx/source/printer/cupsmgr.cxx @@ -533,6 +533,10 @@ void CUPSManager::initialize() pDest->options ); if( pOpt ) m_bUseIncludeFeature = true; + // do not send include JobPatch; CUPS will insert that itself + // TODO: currently unknwon which versions of CUPS insert JobPatches + // so currently it is assumed CUPS = don't insert JobPatch files + m_bUseJobPatch = false; rtl_TextEncoding aEncoding = osl_getThreadTextEncoding(); int nPrinter = m_nDests; diff --git a/vcl/unx/source/printer/printerinfomanager.cxx b/vcl/unx/source/printer/printerinfomanager.cxx index b3e5b4667a6a..afe4182cd766 100644 --- a/vcl/unx/source/printer/printerinfomanager.cxx +++ b/vcl/unx/source/printer/printerinfomanager.cxx @@ -119,6 +119,7 @@ PrinterInfoManager::PrinterInfoManager( Type eType ) : m_pQueueInfo( NULL ), m_eType( eType ), m_bUseIncludeFeature( false ), + m_bUseJobPatch( true ), m_aSystemDefaultPaper( RTL_CONSTASCII_USTRINGPARAM( "A4" ) ), m_bDisableCUPS( false ) { diff --git a/vcl/unx/source/printergfx/printerjob.cxx b/vcl/unx/source/printergfx/printerjob.cxx index 783dd5ff2b47..5a51f1d76b92 100644 --- a/vcl/unx/source/printergfx/printerjob.cxx +++ b/vcl/unx/source/printergfx/printerjob.cxx @@ -914,6 +914,9 @@ bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob ) void PrinterJob::writeJobPatch( osl::File* pFile, const JobData& rJobData ) { + if( ! PrinterInfoManager::get().getUseJobPatch() ) + return; + const PPDKey* pKey = NULL; if( rJobData.m_pParser ) -- cgit From b9a98a3a5853988afc5489eea36954fb29cf59fc Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 15 Dec 2009 18:38:02 +0100 Subject: remove a debug remnant --- vcl/unx/gtk/app/gtkinst.cxx | 5 ----- 1 file changed, 5 deletions(-) diff --git a/vcl/unx/gtk/app/gtkinst.cxx b/vcl/unx/gtk/app/gtkinst.cxx index af3a1df97a8c..92a8ff641a38 100644 --- a/vcl/unx/gtk/app/gtkinst.cxx +++ b/vcl/unx/gtk/app/gtkinst.cxx @@ -144,11 +144,6 @@ extern "C" if( ! ( pNoXInitThreads && *pNoXInitThreads ) ) XInitThreads(); - #if OSL_DEBUG_LEVEL > 1 - int nFd = open( "/home/pl93762/log.txt", O_CREAT | O_TRUNC | O_WRONLY, 0755 ); - dup2( nFd, STDERR_FILENO ); - #endif - const gchar* pVersion = gtk_check_version( 2, 2, 0 ); if( pVersion ) { -- cgit From 085de48cba0c845b939b4b50fc9ae7439a030460 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 15 Dec 2009 19:29:01 +0100 Subject: vcl108: #i102696# make menubar behave more gtk like in case of gtk plugin --- vcl/source/window/menu.cxx | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/vcl/source/window/menu.cxx b/vcl/source/window/menu.cxx index c9e0c23e7f16..5b99cd084360 100644 --- a/vcl/source/window/menu.cxx +++ b/vcl/source/window/menu.cxx @@ -5578,6 +5578,17 @@ BOOL MenuBarWindow::ImplHandleKeyEvent( const KeyEvent& rKEvent, BOOL bFromMenu n = pMenu->GetItemCount()-1; } + // handling gtk like (aka mbOpenMenuOnF10) + // do not highlight an item when opening a sub menu + // unless there already was a higlighted sub menu item + bool bWasHighlight = false; + if( pActivePopup ) + { + MenuFloatingWindow* pSubWindow = dynamic_cast(pActivePopup->ImplGetWindow()); + if( pSubWindow ) + bWasHighlight = (pSubWindow->GetHighlightedItem() != ITEMPOS_INVALID); + } + USHORT nLoop = n; if( nCode == KEY_HOME ) @@ -5604,7 +5615,10 @@ BOOL MenuBarWindow::ImplHandleKeyEvent( const KeyEvent& rKEvent, BOOL bFromMenu MenuItemData* pData = (MenuItemData*)pMenu->GetItemList()->GetDataFromPos( n ); if ( ( pData->eType != MENUITEM_SEPARATOR ) && pMenu->ImplIsVisible( n ) ) { - ChangeHighlightItem( n, TRUE ); + BOOL bDoSelect = TRUE; + if( ImplGetSVData()->maNWFData.mbOpenMenuOnF10 ) + bDoSelect = bWasHighlight; + ChangeHighlightItem( n, bDoSelect ); break; } } while ( n != nLoop ); -- cgit From 2740353e241613fd17fcd8ce57583129490a19d2 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 16 Dec 2009 11:31:36 +0100 Subject: vcl108: #i107271# fix invalid iterator access (thanks cmc) --- vcl/unx/source/gdi/salgdi.cxx | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/vcl/unx/source/gdi/salgdi.cxx b/vcl/unx/source/gdi/salgdi.cxx index c09803dcb269..490a92d12a0f 100644 --- a/vcl/unx/source/gdi/salgdi.cxx +++ b/vcl/unx/source/gdi/salgdi.cxx @@ -1427,14 +1427,17 @@ bool X11SalGraphics::drawPolyPolygon( const ::basegfx::B2DPolyPolygon& rOrigPoly // unless it splits another trapezoid that is still active bool bSplit = false; ActiveTrapSet::iterator aActiveTrapsIt = aActiveTraps.begin(); - for(; aActiveTrapsIt != aActiveTraps.end(); ++aActiveTrapsIt ) + while(aActiveTrapsIt != aActiveTraps.end()) { XTrapezoid& rLeftTrap = aTrapVector[ *aActiveTrapsIt ]; // skip until first overlap candidate // TODO: use stl::*er_bound() instead if( IsLeftOf( aTrapezoid.left, rLeftTrap.left) ) + { + ++aActiveTrapsIt; continue; + } // in the ActiveTrapSet there are still trapezoids where // a vertical overlap with new trapezoids is no longer possible @@ -1445,15 +1448,26 @@ bool X11SalGraphics::drawPolyPolygon( const ::basegfx::B2DPolyPolygon& rOrigPoly { ActiveTrapSet::iterator it = aActiveTrapsIt; if( aActiveTrapsIt != aActiveTraps.begin() ) + { --aActiveTrapsIt; - aActiveTraps.erase( it ); + aActiveTraps.erase( it ); + ++aActiveTrapsIt; + } + else + { + aActiveTraps.erase( it ); + aActiveTrapsIt = aActiveTraps.begin(); + } continue; } // check if there is horizontal overlap // aTrapezoid.left==rLeftTrap.right is allowed though if( !IsLeftOf( aTrapezoid.left, rLeftTrap.right ) ) + { + ++aActiveTrapsIt; continue; + } // prepare to split the old trapezoid and keep its upper part // find the old trapezoids entry in the VerticalTrapSet and remove it -- cgit From 5df27651727b0c7899a7220f972799a99694254d Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 16 Dec 2009 17:38:59 +0100 Subject: vcl108: #i94111# support globalized PPDs --- padmin/source/prtsetup.cxx | 23 +- padmin/source/prtsetup.hxx | 2 +- vcl/inc/vcl/ppdparser.hxx | 23 +- vcl/unx/headless/svpprn.cxx | 2 +- vcl/unx/source/gdi/salprnpsp.cxx | 2 +- vcl/unx/source/printer/ppdparser.cxx | 448 ++++++++++++++++++++++++++++------- 6 files changed, 393 insertions(+), 107 deletions(-) diff --git a/padmin/source/prtsetup.cxx b/padmin/source/prtsetup.cxx index 6cf4f8b257b1..69217e2d0063 100644 --- a/padmin/source/prtsetup.cxx +++ b/padmin/source/prtsetup.cxx @@ -44,9 +44,9 @@ using namespace rtl; using namespace psp; using namespace padmin; -void RTSDialog::insertAllPPDValues( ListBox& rBox, const PPDKey* pKey ) +void RTSDialog::insertAllPPDValues( ListBox& rBox, const PPDParser* pParser, const PPDKey* pKey ) { - if( ! pKey ) + if( ! pKey || ! pParser ) return; const PPDValue* pValue = NULL; @@ -56,7 +56,7 @@ void RTSDialog::insertAllPPDValues( ListBox& rBox, const PPDKey* pKey ) for( int i = 0; i < pKey->countValues(); i++ ) { pValue = pKey->getValue( i ); - aOptionText = pValue->m_aOptionTranslation.Len() ? pValue->m_aOptionTranslation : pValue->m_aOption; + aOptionText = pParser->translateOption( pKey->getKey(), pValue->m_aOption) ; if( m_aJobData.m_aContext.checkConstraints( pKey, pValue ) ) { @@ -282,7 +282,7 @@ void RTSPaperPage::update() if( m_pParent->m_aJobData.m_pParser && (pKey = m_pParent->m_aJobData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "Duplex" ) ) )) ) { - m_pParent->insertAllPPDValues( m_aDuplexBox, pKey ); + m_pParent->insertAllPPDValues( m_aDuplexBox, m_pParent->m_aJobData.m_pParser, pKey ); } else { @@ -294,7 +294,7 @@ void RTSPaperPage::update() if( m_pParent->m_aJobData.m_pParser && (pKey = m_pParent->m_aJobData.m_pParser->getKey( String( RTL_CONSTASCII_USTRINGPARAM( "PageSize" ) ) )) ) { - m_pParent->insertAllPPDValues( m_aPaperBox, pKey ); + m_pParent->insertAllPPDValues( m_aPaperBox, m_pParent->m_aJobData.m_pParser, pKey ); } else { @@ -306,7 +306,7 @@ void RTSPaperPage::update() if( m_pParent->m_aJobData.m_pParser && (pKey = m_pParent->m_aJobData.m_pParser->getKey( String::CreateFromAscii( "InputSlot" ) )) ) { - m_pParent->insertAllPPDValues( m_aSlotBox, pKey ); + m_pParent->insertAllPPDValues( m_aSlotBox, m_pParent->m_aJobData.m_pParser, pKey ); } else { @@ -411,8 +411,8 @@ RTSDevicePage::RTSDevicePage( RTSDialog* pParent ) : ! pKey->getKey().EqualsAscii( "Duplex" ) ) { - USHORT nPos = - m_aPPDKeyBox.InsertEntry( pKey->getUITranslation().Len() ? pKey->getUITranslation() : pKey->getKey() ); + String aEntry( m_pParent->m_aJobData.m_pParser->translateKey( pKey->getKey() ) ); + USHORT nPos = m_aPPDKeyBox.InsertEntry( aEntry ); m_aPPDKeyBox.SetEntryData( nPos, (void*)pKey ); } } @@ -466,10 +466,11 @@ void RTSDevicePage::FillValueBox( const PPDKey* pKey ) for( int i = 0; i < pKey->countValues(); i++ ) { pValue = pKey->getValue( i ); - if( m_pParent->m_aJobData.m_aContext.checkConstraints( pKey, pValue ) ) + if( m_pParent->m_aJobData.m_aContext.checkConstraints( pKey, pValue ) && + m_pParent->m_aJobData.m_pParser ) { - USHORT nPos = - m_aPPDValueBox.InsertEntry( pValue->m_aOptionTranslation.Len() ? pValue->m_aOptionTranslation : pValue->m_aOption ); + String aEntry( m_pParent->m_aJobData.m_pParser->translateOption( pKey->getKey(), pValue->m_aOption ) ); + USHORT nPos = m_aPPDValueBox.InsertEntry( aEntry ); m_aPPDValueBox.SetEntryData( nPos, (void*)pValue ); } } diff --git a/padmin/source/prtsetup.hxx b/padmin/source/prtsetup.hxx index 8487daa158da..1e296fa9ed88 100644 --- a/padmin/source/prtsetup.hxx +++ b/padmin/source/prtsetup.hxx @@ -85,7 +85,7 @@ class RTSDialog : public TabDialog DECL_LINK( ClickButton, Button* ); // helper functions - void insertAllPPDValues( ListBox&, const ::psp::PPDKey* ); + void insertAllPPDValues( ListBox&, const psp::PPDParser*, const psp::PPDKey* ); public: RTSDialog( const ::psp::PrinterInfo& rJobData, const String& rPrinter, bool bAllPages, Window* pParent = NULL ); ~RTSDialog(); diff --git a/vcl/inc/vcl/ppdparser.hxx b/vcl/inc/vcl/ppdparser.hxx index ed9f91b97d99..ba5bc5004362 100644 --- a/vcl/inc/vcl/ppdparser.hxx +++ b/vcl/inc/vcl/ppdparser.hxx @@ -37,11 +37,14 @@ #include "tools/string.hxx" #include "tools/stream.hxx" +#include "com/sun/star/lang/Locale.hpp" + #define PRINTER_PPDDIR "driver" namespace psp { class PPDParser; +class PPDTranslator; enum PPDValueType { eInvocation, eQuoted, eSymbol, eString, eNo }; @@ -49,9 +52,7 @@ struct PPDValue { PPDValueType m_eType; String m_aOption; - String m_aOptionTranslation; String m_aValue; - String m_aValueTranslation; }; // ---------------------------------------------------------------------- @@ -80,7 +81,6 @@ public: private: bool m_bUIOption; - String m_aUITranslation; UIType m_eUIType; int m_nOrderDependency; SetupType m_eSetupType; @@ -102,7 +102,6 @@ public: const String& getKey() const { return m_aKey; } bool isUIKey() const { return m_bUIOption; } - const String& getUITranslation() const { return m_aUITranslation; } UIType getUIType() const { return m_eUIType; } SetupType getSetupType() const { return m_eSetupType; } int getOrderDependency() const { return m_nOrderDependency; } @@ -185,6 +184,9 @@ private: // fonts const PPDKey* m_pFontList; + // translations + PPDTranslator* m_pTranslator; + PPDParser( const String& rFile ); ~PPDParser(); @@ -193,7 +195,7 @@ private: void parseConstraint( const ByteString& rLine ); void parse( std::list< ByteString >& rLines ); - String handleTranslation( const ByteString& rString ); + String handleTranslation( const ByteString& i_rString, bool i_bIsGlobalized ); static void scanPPDDir( const String& rDir ); static void initPPDFiles(); @@ -277,6 +279,17 @@ public: String& rEncoding, String& rCharset ) const; const String& getFont( int ) const; + + + rtl::OUString translateKey( const rtl::OUString& i_rKey, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) const; + rtl::OUString translateOption( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) const; + rtl::OUString translateValue( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) const; }; // ---------------------------------------------------------------------- diff --git a/vcl/unx/headless/svpprn.cxx b/vcl/unx/headless/svpprn.cxx index 1882b50e6ad7..a3a5c3c7a9c9 100644 --- a/vcl/unx/headless/svpprn.cxx +++ b/vcl/unx/headless/svpprn.cxx @@ -707,7 +707,7 @@ String PspSalInfoPrinter::GetPaperBinName( const ImplJobSetup* pJobSetup, ULONG { const PPDValue* pValue = pKey->getValue( nPaperBin ); if( pValue ) - aRet = pValue->m_aOptionTranslation.Len() ? pValue->m_aOptionTranslation : pValue->m_aOption; + aRet = aData.m_pParser->translateOption( pKey->getKey(), pValue->m_aOption ); } } diff --git a/vcl/unx/source/gdi/salprnpsp.cxx b/vcl/unx/source/gdi/salprnpsp.cxx index 2cf4e3baedd3..95a88bb55126 100644 --- a/vcl/unx/source/gdi/salprnpsp.cxx +++ b/vcl/unx/source/gdi/salprnpsp.cxx @@ -810,7 +810,7 @@ String PspSalInfoPrinter::GetPaperBinName( const ImplJobSetup* pJobSetup, ULONG { const PPDValue* pValue = pKey->getValue( nPaperBin ); if( pValue ) - aRet = pValue->m_aOptionTranslation.Len() ? pValue->m_aOptionTranslation : pValue->m_aOption; + aRet = aData.m_pParser->translateOption( pKey->getKey(), pValue->m_aOption ); } } diff --git a/vcl/unx/source/printer/ppdparser.cxx b/vcl/unx/source/printer/ppdparser.cxx index 705dcf8ccad7..a70a5ac7f6c8 100644 --- a/vcl/unx/source/printer/ppdparser.cxx +++ b/vcl/unx/source/printer/ppdparser.cxx @@ -39,6 +39,7 @@ #include "vcl/ppdparser.hxx" #include "vcl/strhelper.hxx" #include "vcl/helper.hxx" +#include "vcl/svapp.hxx" #include "cupsmgr.hxx" #include "tools/debug.hxx" #include "tools/urlobj.hxx" @@ -51,6 +52,202 @@ #include "rtl/strbuf.hxx" #include "rtl/ustrbuf.hxx" +#include "com/sun/star/lang/Locale.hpp" + +namespace psp +{ + class PPDTranslator + { + struct LocaleEqual + { + bool operator()(const com::sun::star::lang::Locale& i_rLeft, + const com::sun::star::lang::Locale& i_rRight) const + { + return i_rLeft.Language.equals( i_rRight.Language ) && + i_rLeft.Country.equals( i_rRight.Country ) && + i_rLeft.Variant.equals( i_rRight.Variant ); + } + }; + + struct LocaleHash + { + size_t operator()(const com::sun::star::lang::Locale& rLocale) const + { return + (size_t)rLocale.Language.hashCode() + ^ (size_t)rLocale.Country.hashCode() + ^ (size_t)rLocale.Variant.hashCode() + ; + } + }; + + typedef std::hash_map< com::sun::star::lang::Locale, rtl::OUString, LocaleHash, LocaleEqual > translation_map; + typedef std::hash_map< rtl::OUString, translation_map, rtl::OUStringHash > key_translation_map; + + key_translation_map m_aTranslations; + public: + PPDTranslator() {} + ~PPDTranslator() {} + + + void insertValue( + const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const rtl::OUString& i_rTranslation, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() + ); + + void insertOption( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rTranslation, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) + { + insertValue( i_rKey, i_rOption, rtl::OUString(), i_rTranslation, i_rLocale ); + } + + void insertKey( const rtl::OUString& i_rKey, + const rtl::OUString& i_rTranslation, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) + { + insertValue( i_rKey, rtl::OUString(), rtl::OUString(), i_rTranslation, i_rLocale ); + } + + rtl::OUString translateValue( + const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() + ) const; + + rtl::OUString translateOption( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) const + { + return translateValue( i_rKey, i_rOption, rtl::OUString(), i_rLocale ); + } + + rtl::OUString translateKey( const rtl::OUString& i_rKey, + const com::sun::star::lang::Locale& i_rLocale = com::sun::star::lang::Locale() ) const + { + return translateValue( i_rKey, rtl::OUString(), rtl::OUString(), i_rLocale ); + } + }; + + static com::sun::star::lang::Locale normalizeInputLocale( + const com::sun::star::lang::Locale& i_rLocale, + bool bInsertDefault = false + ) + { + com::sun::star::lang::Locale aLoc( i_rLocale ); + if( bInsertDefault && aLoc.Language.getLength() == 0 ) + { + // empty locale requested, fill in application UI locale + aLoc = Application::GetSettings().GetUILocale(); + + #if OSL_DEBUG_LEVEL > 1 + static const char* pEnvLocale = getenv( "SAL_PPDPARSER_LOCALE" ); + if( pEnvLocale && *pEnvLocale ) + { + rtl::OString aStr( pEnvLocale ); + sal_Int32 nLen = aStr.getLength(); + aLoc.Language = rtl::OStringToOUString( aStr.copy( 0, nLen > 2 ? 2 : nLen ), RTL_TEXTENCODING_MS_1252 ); + if( nLen >=5 && aStr.getStr()[2] == '_' ) + aLoc.Country = rtl::OStringToOUString( aStr.copy( 3, 2 ), RTL_TEXTENCODING_MS_1252 ); + else + aLoc.Country = rtl::OUString(); + aLoc.Variant = rtl::OUString(); + } + #endif + } + aLoc.Language = aLoc.Language.toAsciiLowerCase(); + aLoc.Country = aLoc.Country.toAsciiUpperCase(); + aLoc.Variant = aLoc.Variant.toAsciiUpperCase(); + + return aLoc; + } + + void PPDTranslator::insertValue( + const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const rtl::OUString& i_rTranslation, + const com::sun::star::lang::Locale& i_rLocale + ) + { + rtl::OUStringBuffer aKey( i_rKey.getLength() + i_rOption.getLength() + i_rValue.getLength() + 2 ); + aKey.append( i_rKey ); + if( i_rOption.getLength() || i_rValue.getLength() ) + { + aKey.append( sal_Unicode( ':' ) ); + aKey.append( i_rOption ); + } + if( i_rValue.getLength() ) + { + aKey.append( sal_Unicode( ':' ) ); + aKey.append( i_rValue ); + } + if( aKey.getLength() && i_rTranslation.getLength() ) + { + rtl::OUString aK( aKey.makeStringAndClear() ); + com::sun::star::lang::Locale aLoc; + aLoc.Language = i_rLocale.Language.toAsciiLowerCase(); + aLoc.Country = i_rLocale.Country.toAsciiUpperCase(); + aLoc.Variant = i_rLocale.Variant.toAsciiUpperCase(); + m_aTranslations[ aK ][ aLoc ] = i_rTranslation; + } + } + + rtl::OUString PPDTranslator::translateValue( + const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const com::sun::star::lang::Locale& i_rLocale + ) const + { + rtl::OUString aResult; + + rtl::OUStringBuffer aKey( i_rKey.getLength() + i_rOption.getLength() + i_rValue.getLength() + 2 ); + aKey.append( i_rKey ); + if( i_rOption.getLength() || i_rValue.getLength() ) + { + aKey.append( sal_Unicode( ':' ) ); + aKey.append( i_rOption ); + } + if( i_rValue.getLength() ) + { + aKey.append( sal_Unicode( ':' ) ); + aKey.append( i_rValue ); + } + if( aKey.getLength() ) + { + rtl::OUString aK( aKey.makeStringAndClear() ); + key_translation_map::const_iterator it = m_aTranslations.find( aK ); + if( it != m_aTranslations.end() ) + { + const translation_map& rMap( it->second ); + + com::sun::star::lang::Locale aLoc( normalizeInputLocale( i_rLocale, true ) ); + for( int nTry = 0; nTry < 4; nTry++ ) + { + translation_map::const_iterator tr = rMap.find( aLoc ); + if( tr != rMap.end() ) + { + aResult = tr->second; + break; + } + switch( nTry ) + { + case 0: aLoc.Variant = rtl::OUString();break; + case 1: aLoc.Country = rtl::OUString();break; + case 2: aLoc.Language = rtl::OUString();break; + } + } + } + } + return aResult; + } +} + using namespace psp; using namespace rtl; @@ -481,7 +678,8 @@ PPDParser::PPDParser( const String& rFile ) : m_pResolutions( NULL ), m_pDefaultDuplexType( NULL ), m_pDuplexTypes( NULL ), - m_pFontList( NULL ) + m_pFontList( NULL ), + m_pTranslator( new PPDTranslator() ) { // read in the file std::list< ByteString > aLines; @@ -648,6 +846,7 @@ PPDParser::~PPDParser() { for( PPDParser::hash_type::iterator it = m_aKeys.begin(); it != m_aKeys.end(); ++it ) delete it->second; + delete m_pTranslator; } void PPDParser::insertKey( const String& rKey, PPDKey* pKey ) @@ -687,11 +886,11 @@ static sal_uInt8 getNibble( sal_Char cChar ) return nRet; } -String PPDParser::handleTranslation( const ByteString& rString ) +String PPDParser::handleTranslation( const ByteString& i_rString, bool bIsGlobalized ) { - int nOrigLen = rString.Len(); + int nOrigLen = i_rString.Len(); OStringBuffer aTrans( nOrigLen ); - const sal_Char* pStr = rString.GetBuffer(); + const sal_Char* pStr = i_rString.GetBuffer(); const sal_Char* pEnd = pStr + nOrigLen; while( pStr < pEnd ) { @@ -710,14 +909,11 @@ String PPDParser::handleTranslation( const ByteString& rString ) else aTrans.append( *pStr++ ); } - return OStringToOUString( aTrans.makeStringAndClear(), m_aFileEncoding ); + return OStringToOUString( aTrans.makeStringAndClear(), bIsGlobalized ? RTL_TEXTENCODING_UTF8 : m_aFileEncoding ); } void PPDParser::parse( ::std::list< ByteString >& rLines ) { - PPDValue* pValue = NULL; - PPDKey* pKey = NULL; - std::list< ByteString >::iterator line = rLines.begin(); PPDParser::hash_type::const_iterator keyit; while( line != rLines.end() ) @@ -765,14 +961,25 @@ void PPDParser::parse( ::std::list< ByteString >& rLines ) } String aUniKey( aKey, RTL_TEXTENCODING_MS_1252 ); - keyit = m_aKeys.find( aUniKey ); - if( keyit == m_aKeys.end() ) + // handle CUPS extension for globalized PPDs + bool bIsGlobalizedLine = false; + com::sun::star::lang::Locale aTransLocale; + if( ( aUniKey.Len() > 3 && aUniKey.GetChar( 2 ) == '.' ) || + ( aUniKey.Len() > 5 && aUniKey.GetChar( 2 ) == '_' && aUniKey.GetChar( 5 ) == '.' ) ) { - pKey = new PPDKey( aUniKey ); - insertKey( aUniKey, pKey ); + if( aUniKey.GetChar( 2 ) == '.' ) + { + aTransLocale.Language = aUniKey.Copy( 0, 2 ); + aUniKey = aUniKey.Copy( 3 ); + } + else + { + aTransLocale.Language = aUniKey.Copy( 0, 2 ); + aTransLocale.Country = aUniKey.Copy( 3, 2 ); + aUniKey = aUniKey.Copy( 6 ); + } + bIsGlobalizedLine = true; } - else - pKey = keyit->second; String aOption; nPos = aCurrentLine.Search( ':' ); @@ -784,90 +991,125 @@ void PPDParser::parse( ::std::list< ByteString >& rLines ) if( nTransPos != STRING_NOTFOUND ) aOption.Erase( nTransPos ); } - pValue = pKey->insertValue( aOption ); - if( ! pValue ) - continue; - if( nPos == STRING_NOTFOUND ) + PPDValueType eType = eNo; + String aValue; + rtl::OUString aOptionTranslation; + rtl::OUString aValueTranslation; + if( nPos != STRING_NOTFOUND ) { - // have a single main keyword - pValue->m_eType = eNo; - if( bQuery ) - pKey->eraseValue( aOption ); - continue; - } - - // found a colon, there may be an option - ByteString aLine = aCurrentLine.Copy( 1, nPos-1 ); - aLine = WhitespaceToSpace( aLine ); - int nTransPos = aLine.Search( '/' ); - if( nTransPos != STRING_NOTFOUND ) - pValue->m_aOptionTranslation = handleTranslation( aLine.Copy( nTransPos+1 ) ); + // found a colon, there may be an option + ByteString aLine = aCurrentLine.Copy( 1, nPos-1 ); + aLine = WhitespaceToSpace( aLine ); + int nTransPos = aLine.Search( '/' ); + if( nTransPos != STRING_NOTFOUND ) + aOptionTranslation = handleTranslation( aLine.Copy( nTransPos+1 ), bIsGlobalizedLine ); - // read in more lines if necessary for multiline values - aLine = aCurrentLine.Copy( nPos+1 ); - if( aLine.Len() ) - { - while( ! ( aLine.GetTokenCount( '"' ) & 1 ) && - line != rLines.end() ) - // while there is an even number of tokens; that means - // an odd number of doubleqoutes + // read in more lines if necessary for multiline values + aLine = aCurrentLine.Copy( nPos+1 ); + if( aLine.Len() ) { - // copy the newlines also - aLine += '\n'; - aLine += *line; - ++line; + while( ! ( aLine.GetTokenCount( '"' ) & 1 ) && + line != rLines.end() ) + // while there is an even number of tokens; that means + // an odd number of doubleqoutes + { + // copy the newlines also + aLine += '\n'; + aLine += *line; + ++line; + } } - } - aLine = WhitespaceToSpace( aLine ); + aLine = WhitespaceToSpace( aLine ); - // #i100644# handle a missing value (actually a broken PPD) - if( ! aLine.Len() ) - { - pValue->m_aValue = String(); - pValue->m_aValueTranslation = String(); - if( pValue->m_aOption.Len() && - aKey.CompareTo( "JCL", 3 ) != COMPARE_EQUAL ) - pValue->m_eType = eInvocation; + // #i100644# handle a missing value (actually a broken PPD) + if( ! aLine.Len() ) + { + if( aOption.Len() && + aUniKey.CompareToAscii( "JCL", 3 ) != COMPARE_EQUAL ) + eType = eInvocation; + else + eType = eQuoted; + } + // check for invocation or quoted value + else if( aLine.GetChar(0) == '"' ) + { + aLine.Erase( 0, 1 ); + nTransPos = aLine.Search( '"' ); + aValue = String( aLine.Copy( 0, nTransPos ), RTL_TEXTENCODING_MS_1252 ); + // after the second doublequote can follow a / and a translation + aValueTranslation = handleTranslation( aLine.Copy( nTransPos+2 ), bIsGlobalizedLine ); + // check for quoted value + if( aOption.Len() && + aUniKey.CompareToAscii( "JCL", 3 ) != COMPARE_EQUAL ) + eType = eInvocation; + else + eType = eQuoted; + } + // check for symbol value + else if( aLine.GetChar(0) == '^' ) + { + aLine.Erase( 0, 1 ); + aValue = String( aLine, RTL_TEXTENCODING_MS_1252 ); + eType = eSymbol; + } else - pValue->m_eType = eQuoted; + { + // must be a string value then + // strictly this is false because string values + // can contain any whitespace which is reduced + // to one space by now + // who cares ... + nTransPos = aLine.Search( '/' ); + if( nTransPos == STRING_NOTFOUND ) + nTransPos = aLine.Len(); + aValue = String( aLine.Copy( 0, nTransPos ), RTL_TEXTENCODING_MS_1252 ); + aValueTranslation = handleTranslation( aLine.Copy( nTransPos+1 ), bIsGlobalizedLine ); + eType = eString; + } } - // check for invocation or quoted value - else if( aLine.GetChar(0) == '"' ) + + // handle globalized PPD entries + if( bIsGlobalizedLine ) { - aLine.Erase( 0, 1 ); - nTransPos = aLine.Search( '"' ); - pValue->m_aValue = String( aLine.Copy( 0, nTransPos ), RTL_TEXTENCODING_MS_1252 ); - // after the second doublequote can follow a / and a translation - pValue->m_aValueTranslation = handleTranslation( aLine.Copy( nTransPos+2 ) ); - // check for quoted value - if( pValue->m_aOption.Len() && - aKey.CompareTo( "JCL", 3 ) != COMPARE_EQUAL ) - pValue->m_eType = eInvocation; + // handle main key translations of form: + // *ll_CC.Translation MainKeyword/translated text: "" + if( aUniKey.EqualsAscii( "Translation" ) ) + { + m_pTranslator->insertKey( aOption, aOptionTranslation, aTransLocale ); + } + // handle options translations of for: + // *ll_CC.MainKeyword OptionKeyword/translated text: "" else - pValue->m_eType = eQuoted; + { + m_pTranslator->insertOption( aUniKey, aOption, aOptionTranslation, aTransLocale ); + } + continue; } - // check for symbol value - else if( aLine.GetChar(0) == '^' ) + + PPDKey* pKey = NULL; + keyit = m_aKeys.find( aUniKey ); + if( keyit == m_aKeys.end() ) { - aLine.Erase( 0, 1 ); - pValue->m_aValue = String( aLine, RTL_TEXTENCODING_MS_1252 ); - pValue->m_eType = eSymbol; + pKey = new PPDKey( aUniKey ); + insertKey( aUniKey, pKey ); } else - { - // must be a string value then - // strictly this is false because string values - // can contain any whitespace which is reduced - // to one space by now - // who cares ... - nTransPos = aLine.Search( '/' ); - if( nTransPos == STRING_NOTFOUND ) - nTransPos = aLine.Len(); - pValue->m_aValue = String( aLine.Copy( 0, nTransPos ), RTL_TEXTENCODING_MS_1252 ); - pValue->m_aValueTranslation = handleTranslation( aLine.Copy( nTransPos+1 ) ); - pValue->m_eType = eString; - } + pKey = keyit->second; + + if( eType == eNo && bQuery ) + continue; + + PPDValue* pValue = pKey->insertValue( aOption ); + if( ! pValue ) + continue; + pValue->m_eType = eType; + pValue->m_aValue = aValue; + + if( aOptionTranslation.getLength() ) + m_pTranslator->insertOption( aUniKey, aOption, aOptionTranslation, aTransLocale ); + if( aValueTranslation.getLength() ) + m_pTranslator->insertValue( aUniKey, aOption, aValue, aValueTranslation, aTransLocale ); // eventually update query and remove from option list if( bQuery && pKey->m_bQueryValue == FALSE ) @@ -893,7 +1135,7 @@ void PPDParser::parse( ::std::list< ByteString >& rLines ) keyit = m_aKeys.find( aKey ); if( keyit != m_aKeys.end() ) { - pKey = keyit->second; + PPDKey* pKey = keyit->second; const PPDValue* pDefValue = pKey->getValue( aOption ); if( pKey->m_pDefaultValue == NULL ) pKey->m_pDefaultValue = pDefValue; @@ -904,7 +1146,7 @@ void PPDParser::parse( ::std::list< ByteString >& rLines ) // do not exist otherwise // (example: DefaultResolution) // so invent that key here and have a default value - pKey = new PPDKey( aKey ); + PPDKey* pKey = new PPDKey( aKey ); PPDValue* pNewValue = pKey->insertValue( aOption ); pNewValue->m_eType = eInvocation; // or what ? insertKey( aKey, pKey ); @@ -929,7 +1171,7 @@ void PPDParser::parseOpenUI( const ByteString& rLine ) nPos = aKey.Search( '/' ); if( nPos != STRING_NOTFOUND ) { - aTranslation = handleTranslation( aKey.Copy( nPos + 1 ) ); + aTranslation = handleTranslation( aKey.Copy( nPos + 1 ), false ); aKey.Erase( nPos ); } aKey = GetCommandLineToken( 1, aKey ); @@ -947,7 +1189,7 @@ void PPDParser::parseOpenUI( const ByteString& rLine ) pKey = keyit->second; pKey->m_bUIOption = true; - pKey->m_aUITranslation = aTranslation; + m_pTranslator->insertKey( pKey->getKey(), aTranslation ); ByteString aValue = WhitespaceToSpace( rLine.GetToken( 1, ':' ) ); if( aValue.CompareIgnoreCaseToAscii( "boolean" ) == COMPARE_EQUAL ) @@ -1407,6 +1649,36 @@ const String& PPDParser::getFont( int nFont ) const return aEmptyString; } +rtl::OUString PPDParser::translateKey( const rtl::OUString& i_rKey, + const com::sun::star::lang::Locale& i_rLocale ) const +{ + rtl::OUString aResult( m_pTranslator->translateKey( i_rKey, i_rLocale ) ); + if( aResult.getLength() == 0 ) + aResult = i_rKey; + return aResult; +} + +rtl::OUString PPDParser::translateOption( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const com::sun::star::lang::Locale& i_rLocale ) const +{ + rtl::OUString aResult( m_pTranslator->translateOption( i_rKey, i_rOption, i_rLocale ) ); + if( aResult.getLength() == 0 ) + aResult = i_rOption; + return aResult; +} + +rtl::OUString PPDParser::translateValue( const rtl::OUString& i_rKey, + const rtl::OUString& i_rOption, + const rtl::OUString& i_rValue, + const com::sun::star::lang::Locale& i_rLocale ) const +{ + rtl::OUString aResult( m_pTranslator->translateValue( i_rKey, i_rOption, i_rValue, i_rLocale ) ); + if( aResult.getLength() == 0 ) + aResult = i_rValue; + return aResult; +} + /* * PPDKey */ -- cgit From 07a01d51fcb13156029cd2fd3c96605500773f11 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 16 Dec 2009 17:47:03 +0100 Subject: vcl108: #i107260# avoid waiting for an event that may never come --- vcl/unx/source/dtrans/X11_selection.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcl/unx/source/dtrans/X11_selection.cxx b/vcl/unx/source/dtrans/X11_selection.cxx index 07f2cfd5e087..e549d92d9c5f 100644 --- a/vcl/unx/source/dtrans/X11_selection.cxx +++ b/vcl/unx/source/dtrans/X11_selection.cxx @@ -3810,7 +3810,7 @@ void SelectionManager::shutdown() throw() */ aGuard.clear(); while (osl_isThreadRunning(m_aThread)) - Application::Yield(); + Application::Reschedule(); osl_joinWithThread( m_aThread ); osl_destroyThread( m_aThread ); m_aThread = NULL; -- cgit From 8939f29a75911f10371ba1d8bc70cc88e418e5bd Mon Sep 17 00:00:00 2001 From: sj Date: Wed, 16 Dec 2009 17:55:41 +0100 Subject: impress181: #i74384# fixed max value color handling --- goodies/source/filter.vcl/ipbm/ipbm.cxx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/goodies/source/filter.vcl/ipbm/ipbm.cxx b/goodies/source/filter.vcl/ipbm/ipbm.cxx index 227490fc9d8e..c0b0f6012116 100644 --- a/goodies/source/filter.vcl/ipbm/ipbm.cxx +++ b/goodies/source/filter.vcl/ipbm/ipbm.cxx @@ -106,7 +106,7 @@ BOOL PBMReader::ReadPBM( SvStream & rPBM, Graphic & rGraphic ) if ( ( mbStatus = ImplReadHeader() ) == FALSE ) return FALSE; - if ( mnWidth == 0 || mnHeight == 0 ) + if ( ( mnMaxVal == 0 ) || ( mnWidth == 0 ) || ( mnHeight == 0 ) ) return FALSE; // 0->PBM, 1->PGM, 2->PPM @@ -466,7 +466,9 @@ BOOL PBMReader::ImplReadBody() if ( nCount == 3 ) { nCount = 0; - mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( (BYTE)nRGB[ 0 ], (BYTE)nRGB[ 1 ], (BYTE)nRGB[ 2 ] ) ); + mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( static_cast< BYTE >( ( nRGB[ 0 ] * 255 ) / mnMaxVal ), + static_cast< BYTE >( ( nRGB[ 1 ] * 255 ) / mnMaxVal ), + static_cast< BYTE >( ( nRGB[ 2 ] * 255 ) / mnMaxVal ) ) ); nCount = 0; nRGB[ 0 ] = nRGB[ 1 ] = nRGB[ 2 ] = 0; if ( nWidth == mnWidth ) -- cgit From 932a2e676afda577c77710bf982f512b0ef76190 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Wed, 16 Dec 2009 19:57:15 +0100 Subject: vcl108: #i26535# make Ctrl-Tab work in TabDialogs if focus is not in TabControl hierarchy --- vcl/inc/vcl/tabctrl.hxx | 4 ++++ vcl/inc/vcl/tabdlg.hxx | 3 +++ vcl/source/control/tabctrl.cxx | 12 ++++++++++-- vcl/source/window/dlgctrl.cxx | 15 +++++++++++++++ vcl/source/window/tabdlg.cxx | 18 ++++++++++++++++++ 5 files changed, 50 insertions(+), 2 deletions(-) diff --git a/vcl/inc/vcl/tabctrl.hxx b/vcl/inc/vcl/tabctrl.hxx index 30edf6227a60..7bef14b1e725 100644 --- a/vcl/inc/vcl/tabctrl.hxx +++ b/vcl/inc/vcl/tabctrl.hxx @@ -96,6 +96,10 @@ private: SAL_DLLPRIVATE void ImplFreeLayoutData(); DECL_DLLPRIVATE_LINK( ImplScrollBtnHdl, PushButton* pBtn ); +public: + // just for dialog control + SAL_DLLPRIVATE bool ImplHandleNotifyEvent( NotifyEvent& rEvt ); + protected: using Window::ImplInit; SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle ); diff --git a/vcl/inc/vcl/tabdlg.hxx b/vcl/inc/vcl/tabdlg.hxx index 5ec2bcad5225..ad79ebec4549 100644 --- a/vcl/inc/vcl/tabdlg.hxx +++ b/vcl/inc/vcl/tabdlg.hxx @@ -36,6 +36,7 @@ #include class FixedLine; +class TabControl; // ---------------------- // - TabDialog - @@ -61,6 +62,8 @@ public: virtual void Resize(); virtual void StateChanged( StateChangedType nStateChange ); + SAL_DLLPRIVATE TabControl* ImplGetFirstTabControl() const; + void AdjustLayout(); void SetViewWindow( Window* pWindow ) { mpViewWindow = pWindow; } diff --git a/vcl/source/control/tabctrl.cxx b/vcl/source/control/tabctrl.cxx index 9a34629ddf8e..e4fa804e4177 100644 --- a/vcl/source/control/tabctrl.cxx +++ b/vcl/source/control/tabctrl.cxx @@ -1601,7 +1601,7 @@ long TabControl::PreNotify( NotifyEvent& rNEvt ) // ----------------------------------------------------------------------- -long TabControl::Notify( NotifyEvent& rNEvt ) +bool TabControl::ImplHandleNotifyEvent( NotifyEvent& rNEvt ) { if ( (rNEvt.GetType() == EVENT_KEYINPUT) && (GetPageCount() > 1) ) { @@ -1629,8 +1629,16 @@ long TabControl::Notify( NotifyEvent& rNEvt ) } } } + return false; +} + + +// ----------------------------------------------------------------------- + +long TabControl::Notify( NotifyEvent& rNEvt ) +{ - return Control::Notify( rNEvt ); + return ImplHandleNotifyEvent( rNEvt ) ? TRUE : Control::Notify( rNEvt ); } // ----------------------------------------------------------------------- diff --git a/vcl/source/window/dlgctrl.cxx b/vcl/source/window/dlgctrl.cxx index c6f64d74c5fc..a332c89dc9be 100644 --- a/vcl/source/window/dlgctrl.cxx +++ b/vcl/source/window/dlgctrl.cxx @@ -36,6 +36,7 @@ #include #include #include +#include #include #include @@ -888,6 +889,20 @@ BOOL Window::ImplDlgCtrl( const KeyEvent& rKEvt, BOOL bKeyInput ) return TRUE; } + // if we have come here (and therefore the strange "formular" logic above + // turned up no result, then let's try to find a customer for Ctrl-TAB + if ( nKeyCode == KEY_TAB && aKeyCode.IsMod1() && ! aKeyCode.IsMod2() ) + { + TabDialog* pDlg = dynamic_cast(this); + if( pDlg ) + { + TabControl* pTabCtrl = pDlg->ImplGetFirstTabControl(); + NotifyEvent aEvt( bKeyInput ? EVENT_KEYINPUT : EVENT_KEYUP, + pTabCtrl, &rKEvt ); + return pTabCtrl->ImplHandleNotifyEvent( aEvt ); + } + } + return FALSE; } diff --git a/vcl/source/window/tabdlg.cxx b/vcl/source/window/tabdlg.cxx index 95fb404d24af..217533c8d6b7 100644 --- a/vcl/source/window/tabdlg.cxx +++ b/vcl/source/window/tabdlg.cxx @@ -276,3 +276,21 @@ void TabDialog::AdjustLayout() { ImplPosControls(); } + +// ----------------------------------------------------------------------- + +TabControl* TabDialog::ImplGetFirstTabControl() const +{ + Window* pChild = GetWindow( WINDOW_FIRSTCHILD ); + while ( pChild ) + { + if ( pChild->IsVisible() && (pChild != mpViewWindow) ) + { + if ( pChild->GetType() == WINDOW_TABCONTROL ) + return (TabControl*)pChild; + } + pChild = pChild->GetWindow( WINDOW_NEXT ); + } + return NULL; +} + -- cgit From 723b53e66635c03bc4dc4bb0d945867c91672e12 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Thu, 17 Dec 2009 13:56:08 +0000 Subject: cmcfixes69: #i106157#: workaround graphite stl/stlport issues --- vcl/inc/vcl/graphite_adaptors.hxx | 5 +++-- vcl/inc/vcl/graphite_features.hxx | 3 ++- vcl/inc/vcl/graphite_layout.hxx | 2 ++ vcl/source/glyphs/graphite_adaptors.cxx | 2 +- vcl/source/glyphs/graphite_cache.cxx | 2 ++ vcl/source/glyphs/graphite_features.cxx | 6 +++--- vcl/source/glyphs/graphite_layout.cxx | 10 ++++++---- vcl/source/glyphs/graphite_textsrc.cxx | 10 +++++----- vcl/source/glyphs/graphite_textsrc.hxx | 4 +++- vcl/util/makefile2.pmk | 7 +++++++ 10 files changed, 34 insertions(+), 17 deletions(-) diff --git a/vcl/inc/vcl/graphite_adaptors.hxx b/vcl/inc/vcl/graphite_adaptors.hxx index 41ffa00b0f8f..9a0a42c01ce0 100644 --- a/vcl/inc/vcl/graphite_adaptors.hxx +++ b/vcl/inc/vcl/graphite_adaptors.hxx @@ -58,10 +58,11 @@ #include "vcl/dllapi.h" // Libraries +#include "pregraphitestl.h" #include #include #include - +#include "postgraphitestl.h" // Module type definitions and forward declarations. // @@ -121,7 +122,7 @@ public: const grutils::GrFeatureParser * features() const { return mpFeatures; }; private: - virtual void UniqueCacheInfo(std::wstring &, bool &, bool &); + virtual void UniqueCacheInfo(sil_std::wstring &, bool &, bool &); FreetypeServerFont& mrFont; FontProperties maFontProperties; diff --git a/vcl/inc/vcl/graphite_features.hxx b/vcl/inc/vcl/graphite_features.hxx index 6cfe5dfca0fd..d3cfd99e0fe4 100644 --- a/vcl/inc/vcl/graphite_features.hxx +++ b/vcl/inc/vcl/graphite_features.hxx @@ -32,10 +32,11 @@ // Parse a string of features specified as ; separated pairs. // e.g. // 1001=1&2002=2&fav1=0 - +#include "pregraphitestl.h" #include #include #include +#include "postgraphitestl.h" namespace grutils { diff --git a/vcl/inc/vcl/graphite_layout.hxx b/vcl/inc/vcl/graphite_layout.hxx index 2ec3bc4c2391..325f67e852ce 100644 --- a/vcl/inc/vcl/graphite_layout.hxx +++ b/vcl/inc/vcl/graphite_layout.hxx @@ -43,11 +43,13 @@ #include #include // Libraries +#include "pregraphitestl.h" #include #include #include #include #include +#include "postgraphitestl.h" // Platform #include #include diff --git a/vcl/source/glyphs/graphite_adaptors.cxx b/vcl/source/glyphs/graphite_adaptors.cxx index 34e2f5f5bbe3..6c9d97e356b1 100644 --- a/vcl/source/glyphs/graphite_adaptors.cxx +++ b/vcl/source/glyphs/graphite_adaptors.cxx @@ -171,7 +171,7 @@ GraphiteFontAdaptor::~GraphiteFontAdaptor() throw() mpFeatures = NULL; } -void GraphiteFontAdaptor::UniqueCacheInfo(std::wstring & face_name_out, bool & bold_out, bool & italic_out) +void GraphiteFontAdaptor::UniqueCacheInfo(sil_std::wstring & face_name_out, bool & bold_out, bool & italic_out) { face_name_out = maFontProperties.szFaceName; bold_out = maFontProperties.fBold; diff --git a/vcl/source/glyphs/graphite_cache.cxx b/vcl/source/glyphs/graphite_cache.cxx index 8c514c611d2c..a2c245e21774 100644 --- a/vcl/source/glyphs/graphite_cache.cxx +++ b/vcl/source/glyphs/graphite_cache.cxx @@ -36,8 +36,10 @@ #include #include +#include "pregraphitestl.h" #include #include +#include "postgraphitestl.h" #include #include diff --git a/vcl/source/glyphs/graphite_features.cxx b/vcl/source/glyphs/graphite_features.cxx index dae1bfc2866e..b26397aa43e5 100644 --- a/vcl/source/glyphs/graphite_features.cxx +++ b/vcl/source/glyphs/graphite_features.cxx @@ -91,7 +91,7 @@ GrFeatureParser::GrFeatureParser(gr::Font & font, const std::string features, co gr::isocode aLang = maLang; for (size_t i = pos; i < nFeatEnd; i++) aLang.rgch[i-pos] = features[i]; - std::pair aSupported + sil_std::pair aSupported = font.getSupportedLanguages(); gr::LanguageIterator iL = aSupported.first; while (iL != aSupported.second) @@ -142,7 +142,7 @@ void GrFeatureParser::setLang(gr::Font & font, const std::string & lang) if (lang[i] == '-') break; aLang.rgch[i] = lang[i]; } - std::pair aSupported + sil_std::pair aSupported = font.getSupportedLanguages(); gr::LanguageIterator iL = aSupported.first; while (iL != aSupported.second) @@ -189,7 +189,7 @@ bool GrFeatureParser::isValid(gr::Font & font, gr::FeatureSetting & setting) { return false; } - std::pair< gr::FeatureSettingIterator, gr::FeatureSettingIterator > + sil_std::pair< gr::FeatureSettingIterator, gr::FeatureSettingIterator > validValues = font.getFeatureSettings(i); gr::FeatureSettingIterator j = validValues.first; while (j != validValues.second) diff --git a/vcl/source/glyphs/graphite_layout.cxx b/vcl/source/glyphs/graphite_layout.cxx index 86dee2749efa..0ef8b8ec098f 100644 --- a/vcl/source/glyphs/graphite_layout.cxx +++ b/vcl/source/glyphs/graphite_layout.cxx @@ -66,11 +66,13 @@ #include // Graphite Libraries (must be after vcl headers on windows) +#include "pregraphitestl.h" #include #include #include #include #include +#include "postgraphitestl.h" #include #include @@ -105,8 +107,8 @@ FILE * grLog() namespace { - typedef std::pair glyph_range_t; - typedef std::pair glyph_set_range_t; + typedef sil_std::pair glyph_range_t; + typedef sil_std::pair glyph_set_range_t; inline long round(const float n) { return long(n + (n < 0 ? -0.5 : 0.5)); @@ -171,7 +173,7 @@ GraphiteLayout::Glyphs::fill_from(gr::Segment & rSegment, ImplLayoutArgs &rArgs, bool bRtl, long &rWidth, float fScaling, std::vector & rChar2Base, std::vector & rGlyph2Char, std::vector & rCharDxs) { // Create a glyph item for each of the glyph and append it to the base class glyph list. - typedef std::pair< gr::GlyphSetIterator, gr::GlyphSetIterator > GrGlyphSet; + typedef sil_std::pair< gr::GlyphSetIterator, gr::GlyphSetIterator > GrGlyphSet; int nChar = rArgs.mnEndCharPos - rArgs.mnMinCharPos; glyph_range_t iGlyphs = rSegment.glyphs(); int nGlyphs = iGlyphs.second - iGlyphs.first; @@ -586,7 +588,7 @@ public: sal_Int32 hashCode(const grutils::GrFeatureParser * mpFeatures) { // is this sufficient? - std::wstring aFace; + sil_std::wstring aFace; bool bBold; bool bItalic; UniqueCacheInfo(aFace, bBold, bItalic); diff --git a/vcl/source/glyphs/graphite_textsrc.cxx b/vcl/source/glyphs/graphite_textsrc.cxx index adc2ae99c4f8..cbbd386e734a 100644 --- a/vcl/source/glyphs/graphite_textsrc.cxx +++ b/vcl/source/glyphs/graphite_textsrc.cxx @@ -138,16 +138,16 @@ gr::isocode TextSourceAdaptor::getLanguage(gr::toffset) return unknown; } -std::pair TextSourceAdaptor::propertyRange(gr::toffset nCharIdx) +sil_std::pair TextSourceAdaptor::propertyRange(gr::toffset nCharIdx) { if (nCharIdx < unsigned(maLayoutArgs.mnMinCharPos)) - return std::make_pair(0, maLayoutArgs.mnMinCharPos); + return sil_std::make_pair(0, maLayoutArgs.mnMinCharPos); if (nCharIdx < mnEnd) - return std::make_pair(maLayoutArgs.mnMinCharPos, mnEnd); + return sil_std::make_pair(maLayoutArgs.mnMinCharPos, mnEnd); - return std::make_pair(mnEnd, maLayoutArgs.mnLength); + return sil_std::make_pair(mnEnd, maLayoutArgs.mnLength); } size_t TextSourceAdaptor::getFontFeatures(gr::toffset, gr::FeatureSetting * settings) @@ -159,7 +159,7 @@ size_t TextSourceAdaptor::getFontFeatures(gr::toffset, gr::FeatureSetting * sett bool TextSourceAdaptor::sameSegment(gr::toffset char_idx1, gr::toffset char_idx2) { - const std::pair + const sil_std::pair range1 = propertyRange(char_idx1), range2 = propertyRange(char_idx2); diff --git a/vcl/source/glyphs/graphite_textsrc.hxx b/vcl/source/glyphs/graphite_textsrc.hxx index 6f701988bb01..62d951c3f950 100644 --- a/vcl/source/glyphs/graphite_textsrc.hxx +++ b/vcl/source/glyphs/graphite_textsrc.hxx @@ -62,9 +62,11 @@ #include "vcl/dllapi.h" // Libraries +#include "pregraphitestl.h" #include #include #include +#include "postgraphitestl.h" // Module type definitions and forward declarations. // @@ -91,7 +93,7 @@ public: virtual float getVerticalOffset(gr::toffset ich); virtual gr::isocode getLanguage(gr::toffset ich); - virtual std::pair propertyRange(gr::toffset ich); + virtual sil_std::pair propertyRange(gr::toffset ich); virtual size_t getFontFeatures(gr::toffset ich, gr::FeatureSetting * prgfset); virtual bool sameSegment(gr::toffset ich1, gr::toffset ich2); diff --git a/vcl/util/makefile2.pmk b/vcl/util/makefile2.pmk index 63b2889bc15d..cb13e3b42743 100644 --- a/vcl/util/makefile2.pmk +++ b/vcl/util/makefile2.pmk @@ -36,3 +36,10 @@ VISIBILITY_HIDDEN=TRUE .IF "$(GUIBASE)"=="aqua" CFLAGSCXX+=$(OBJCXXFLAGS) .ENDIF # "$(GUIBASE)"=="aqua" + +#building with stlport, but graphite was not built with stlport +.IF "$(USE_SYSTEM_STL)"!="YES" +.IF "$(SYSTEM_GRAPHITE)"=="YES" +CDEFS += -DGRAPHITEADAPTSTL +.ENDIF +.ENDIF -- cgit From 8bbcf854cf7248384646de2b66f06c21bea227ca Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Thu, 17 Dec 2009 13:57:53 +0000 Subject: cmcfixes69: #i106157#: workaround graphite stl/stlport issues --- vcl/inc/postgraphitestl.h | 17 +++++++++++++++++ vcl/inc/pregraphitestl.h | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 vcl/inc/postgraphitestl.h create mode 100644 vcl/inc/pregraphitestl.h diff --git a/vcl/inc/postgraphitestl.h b/vcl/inc/postgraphitestl.h new file mode 100644 index 000000000000..8a8a0ca056ae --- /dev/null +++ b/vcl/inc/postgraphitestl.h @@ -0,0 +1,17 @@ +#ifdef std_was_redefined_as_stlport +// put things back the way they were +# define std std_was_redefined_as_stlport +# undef _STLP_DONT_REDEFINE_STD +# undef _STLP_WHOLE_NATIVE_STD +# undef _STLP_STRING +# undef _STLP_IOSTREAM +# undef _STLP_IOSFWD +# undef _STLP_IOMANIP +# undef _STLP_ALGORITHM +# undef _STLP_VECTOR +# undef _STLP_SET +# undef _STLP_MAP +// force config to be re-read +# undef _STLP_CONFIG_H +# include +#endif diff --git a/vcl/inc/pregraphitestl.h b/vcl/inc/pregraphitestl.h new file mode 100644 index 000000000000..043ae84d0b45 --- /dev/null +++ b/vcl/inc/pregraphitestl.h @@ -0,0 +1,29 @@ +#if defined(GRAPHITEADAPTSTL) && defined(std) +# define std_was_redefined_as_stlport std +# undef std +# undef _STLP_CONFIG_H +# undef _STLP_STRING +# undef _STLP_IOSTREAM +# undef _STLP_IOSFWD +# undef _STLP_IOMANIP +# undef _STLP_ALGORITHM +# undef _STLP_VECTOR +# undef _STLP_SET +# undef _STLP_MAP +# define _STLP_DONT_REDEFINE_STD 1 +# define _STLP_WHOLE_NATIVE_STD 1 +# include _STLP_NATIVE_HEADER(exception_defines.h) +# include _STLP_NATIVE_HEADER(memory) +# include _STLP_NATIVE_HEADER(exception) +# include _STLP_NATIVE_HEADER(iosfwd) +# include _STLP_NATIVE_HEADER(string) +# include _STLP_NATIVE_HEADER(streambuf) +# include _STLP_NATIVE_HEADER(ios) +# include _STLP_NATIVE_HEADER(locale) +# include _STLP_NATIVE_HEADER(stdexcept) +# include _STLP_NATIVE_HEADER(ostream) +# include _STLP_NATIVE_HEADER(istream) +# include _STLP_NATIVE_HEADER(iostream) +#endif +//sil_std resolves to the std that Graphite was built with +namespace sil_std = std; -- cgit From 817095aeb6e9293b649e0af48cb4fdc39a3f2ff4 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 17 Dec 2009 17:25:17 +0100 Subject: vcl108: #i107254# add toUnicode map entries mapping from one glyph to multiple unicodes --- vcl/source/gdi/pdfwriter_impl.cxx | 272 +++++++++++++++++++++++--------------- vcl/source/gdi/pdfwriter_impl.hxx | 14 +- 2 files changed, 173 insertions(+), 113 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index 8cf9c4f050fd..efec952ffbe2 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -2866,10 +2866,16 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont sal_Int32 nToUnicodeStream = 0; sal_uInt8 nEncoding[256]; sal_Ucs nEncodedCodes[256]; + std::vector aUnicodes; + aUnicodes.reserve( 256 ); + sal_Int32 pUnicodesPerGlyph[256]; + sal_Int32 pEncToUnicodeIndex[256]; if( pEncoding ) { - memset( nEncodedCodes, 0, sizeof(nEncodedCodes) ); - memset( nEncoding, 0, sizeof(nEncoding) ); + rtl_zeroMemory( nEncoding, sizeof(nEncoding) ); + rtl_zeroMemory( nEncodedCodes, sizeof(nEncodedCodes) ); + rtl_zeroMemory( pUnicodesPerGlyph, sizeof(pUnicodesPerGlyph) ); + rtl_zeroMemory( pEncToUnicodeIndex, sizeof(pEncToUnicodeIndex) ); for( Ucs2SIntMap::const_iterator it = pEncoding->begin(); it != pEncoding->end(); ++it ) { if( it->second != -1 ) @@ -2877,6 +2883,9 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont sal_Int32 nCode = (sal_Int32)(it->second & 0x000000ff); nEncoding[ nCode ] = static_cast( nCode ); nEncodedCodes[ nCode ] = it->first; + pEncToUnicodeIndex[ nCode ] = static_cast(aUnicodes.size()); + aUnicodes.push_back( it->first ); + pUnicodesPerGlyph[ nCode ] = 1; } } } @@ -3299,7 +3308,7 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont if( nFontDescriptor ) { if( pEncoding ) - nToUnicodeStream = createToUnicodeCMap( nEncoding, nEncodedCodes, sizeof(nEncoding)/sizeof(nEncoding[0]) ); + nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, sizeof(nEncoding)/sizeof(nEncoding[0]) ); // write font object sal_Int32 nObject = createObject(); @@ -3363,12 +3372,16 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont aLine.append( " 0 obj\n" "<::iterator str_it = enc_it->m_aEncVector.begin(); str_it != enc_it->m_aEncVector.end(); ++str_it ) { String aStr( str_it->m_aUnicode ); aEncWidths[nEncoded] = pRef->GetTextWidth( aStr ); nEncodedCodes[nEncoded] = str_it->m_aUnicode; nEncoding[nEncoded] = sal::static_int_cast(nEncoded); + pEncToUnicodeIndex[nEncoded] = static_cast(aUnicodes.size()); + aUnicodes.push_back( nEncodedCodes[nEncoded] ); + pUnicodesPerGlyph[nEncoded] = 1; aLine.append( " /" ); aLine.append( str_it->m_aName ); @@ -3383,7 +3396,7 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) goto streamend; - nToUnicodeStream = createToUnicodeCMap( nEncoding, nEncodedCodes, nEncoded ); + nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, nEncoded ); nObject = createObject(); if( ! updateObject( nObject ) ) @@ -3448,11 +3461,15 @@ static void appendSubsetName( int nSubsetID, const OUString& rPSName, OStringBuf appendName( rPSName, rBuffer ); } -sal_Int32 PDFWriterImpl::createToUnicodeCMap( sal_uInt8* pEncoding, sal_Ucs* pUnicodes, int nGlyphs ) +sal_Int32 PDFWriterImpl::createToUnicodeCMap( sal_uInt8* pEncoding, + sal_Ucs* pUnicodes, + sal_Int32* pUnicodesPerGlyph, + sal_Int32* pEncToUnicodeIndex, + int nGlyphs ) { int nMapped = 0, n = 0; for( n = 0; n < nGlyphs; n++ ) - if( pUnicodes[n] ) + if( pUnicodes[pEncToUnicodeIndex[n]] && pUnicodesPerGlyph[n] ) nMapped++; if( nMapped == 0 ) @@ -3480,7 +3497,7 @@ sal_Int32 PDFWriterImpl::createToUnicodeCMap( sal_uInt8* pEncoding, sal_Ucs* pUn int nCount = 0; for( n = 0; n < nGlyphs; n++ ) { - if( pUnicodes[n] ) + if( pUnicodes[pEncToUnicodeIndex[n]] && pUnicodesPerGlyph[n] ) { if( (nCount % 100) == 0 ) { @@ -3492,9 +3509,13 @@ sal_Int32 PDFWriterImpl::createToUnicodeCMap( sal_uInt8* pEncoding, sal_Ucs* pUn aContents.append( '<' ); appendHex( (sal_Int8)pEncoding[n], aContents ); aContents.append( "> <" ); - // TODO: handle unicodes>U+FFFF - appendHex( (sal_Int8)(pUnicodes[n] / 256), aContents ); - appendHex( (sal_Int8)(pUnicodes[n] & 255), aContents ); + // TODO: handle unicodes>U+FFFF + sal_Int32 nIndex = pEncToUnicodeIndex[n]; + for( sal_Int32 j = 0; j < pUnicodesPerGlyph[n]; j++ ) + { + appendHex( (sal_Int8)(pUnicodes[nIndex + j] / 256), aContents ); + appendHex( (sal_Int8)(pUnicodes[nIndex + j] & 255), aContents ); + } aContents.append( ">\n" ); nCount++; } @@ -3654,14 +3675,18 @@ bool PDFWriterImpl::emitFonts() sal_Int32 pGlyphIDs[ 256 ]; sal_Int32 pWidths[ 256 ]; sal_uInt8 pEncoding[ 256 ]; - sal_Ucs pUnicodes[ 256 ]; + sal_Int32 pEncToUnicodeIndex[ 256 ]; + sal_Int32 pUnicodesPerGlyph[ 256 ]; + std::vector aUnicodes; + aUnicodes.reserve( 256 ); int nGlyphs = 1; // fill arrays and prepare encoding index map sal_Int32 nToUnicodeStream = 0; - memset( pGlyphIDs, 0, sizeof( pGlyphIDs ) ); - memset( pEncoding, 0, sizeof( pEncoding ) ); - memset( pUnicodes, 0, sizeof( pUnicodes ) ); + rtl_zeroMemory( pGlyphIDs, sizeof( pGlyphIDs ) ); + rtl_zeroMemory( pEncoding, sizeof( pEncoding ) ); + rtl_zeroMemory( pUnicodesPerGlyph, sizeof( pUnicodesPerGlyph ) ); + rtl_zeroMemory( pEncToUnicodeIndex, sizeof( pEncToUnicodeIndex ) ); for( FontEmitMapping::iterator fit = lit->m_aMapping.begin(); fit != lit->m_aMapping.end();++fit ) { sal_uInt8 nEnc = fit->second.m_nSubsetGlyphID; @@ -3671,8 +3696,11 @@ bool PDFWriterImpl::emitFonts() pGlyphIDs[ nEnc ] = fit->first; pEncoding[ nEnc ] = nEnc; - pUnicodes[ nEnc ] = fit->second.m_aUnicode; - if( pUnicodes[ nEnc ] ) + pEncToUnicodeIndex[ nEnc ] = static_cast(aUnicodes.size()); + pUnicodesPerGlyph[ nEnc ] = fit->second.m_nUnicodes; + for( sal_Int32 n = 0; n < fit->second.m_nUnicodes; n++ ) + aUnicodes.push_back( fit->second.m_aUnicodes[n] ); + if( fit->second.m_aUnicodes[0] ) nToUnicodeStream = 1; if( nGlyphs < 256 ) nGlyphs++; @@ -3693,92 +3721,92 @@ bool PDFWriterImpl::emitFonts() CHECK_RETURN( (osl_File_E_None == osl_getFilePos( aFontFile, &nLength1 ) ) ); CHECK_RETURN( (osl_File_E_None == osl_setFilePos( aFontFile, osl_Pos_Absolut, 0 ) ) ); -#if OSL_DEBUG_LEVEL > 1 + #if OSL_DEBUG_LEVEL > 1 { OStringBuffer aLine1( " PDFWriterImpl::emitFonts" ); emitComment( aLine1.getStr() ); } -#endif + #endif sal_Int32 nFontStream = createObject(); sal_Int32 nStreamLengthObject = createObject(); CHECK_RETURN( updateObject( nFontStream ) ); aLine.setLength( 0 ); aLine.append( nFontStream ); aLine.append( " 0 obj\n" - "<>\n" - "stream\n" ); - CHECK_RETURN( writeBuffer( aLine.getStr(), aLine.getLength() ) ); - CHECK_RETURN( (osl_File_E_None == osl_getFilePos( m_aFile, &nStartPos ) ) ); + #ifndef DEBUG_DISABLE_PDFCOMPRESSION + "/Filter/FlateDecode" + #endif + "/Length1 " ); - // copy font file - beginCompression(); - checkAndEnableStreamEncryption( nFontStream ); - sal_Bool bEOF = sal_False; - do + sal_uInt64 nStartPos = 0; + if( aSubsetInfo.m_nFontType == FontSubsetInfo::SFNT_TTF ) { - char buf[8192]; - sal_uInt64 nRead; - CHECK_RETURN( (osl_File_E_None == osl_readFile( aFontFile, buf, sizeof( buf ), &nRead ) ) ); - CHECK_RETURN( writeBuffer( buf, nRead ) ); - CHECK_RETURN( (osl_File_E_None == osl_isEndOfFile( aFontFile, &bEOF ) ) ); - } while( ! bEOF ); - } - else if( (aSubsetInfo.m_nFontType & FontSubsetInfo::CFF_FONT) != 0 ) - { - // TODO: implement - DBG_ERROR( "PDFWriterImpl does not support CFF-font subsets yet!" ); - } - else if( (aSubsetInfo.m_nFontType & FontSubsetInfo::TYPE1_PFB) != 0 ) // TODO: also support PFA? - { - unsigned char* pBuffer = new unsigned char[ (int)nLength1 ]; - - sal_uInt64 nBytesRead = 0; - CHECK_RETURN( (osl_File_E_None == osl_readFile( aFontFile, pBuffer, nLength1, &nBytesRead ) ) ); - DBG_ASSERT( nBytesRead==nLength1, "PDF-FontSubset read incomplete!" ); - CHECK_RETURN( (osl_File_E_None == osl_setFilePos( aFontFile, osl_Pos_Absolut, 0 ) ) ); - // get the PFB-segment lengths - ThreeInts aSegmentLengths = {0,0,0}; - getPfbSegmentLengths( pBuffer, (int)nBytesRead, aSegmentLengths ); - // the lengths below are mandatory for PDF-exported Type1 fonts - // because the PFB segment headers get stripped! WhyOhWhy. - aLine.append( (sal_Int32)aSegmentLengths[0] ); - aLine.append( "/Length2 " ); - aLine.append( (sal_Int32)aSegmentLengths[1] ); - aLine.append( "/Length3 " ); - aLine.append( (sal_Int32)aSegmentLengths[2] ); - - aLine.append( ">>\n" - "stream\n" ); - CHECK_RETURN( writeBuffer( aLine.getStr(), aLine.getLength() ) ); - CHECK_RETURN( (osl_File_E_None == osl_getFilePos( m_aFile, &nStartPos ) ) ); - - // emit PFB-sections without section headers - beginCompression(); - checkAndEnableStreamEncryption( nFontStream ); - CHECK_RETURN( writeBuffer( pBuffer+ 6, aSegmentLengths[0] ) ); - CHECK_RETURN( writeBuffer( pBuffer+12 + aSegmentLengths[0], aSegmentLengths[1] ) ); - CHECK_RETURN( writeBuffer( pBuffer+18 + aSegmentLengths[0] + aSegmentLengths[1], aSegmentLengths[2] ) ); - - delete[] pBuffer; - } - else - { - fprintf( stderr, "PDF: CreateFontSubset result in not yet supported format=%d\n",aSubsetInfo.m_nFontType); - aLine.append( "0 >>\nstream\n" ); - } + aLine.append( (sal_Int32)nLength1 ); + + aLine.append( ">>\n" + "stream\n" ); + CHECK_RETURN( writeBuffer( aLine.getStr(), aLine.getLength() ) ); + CHECK_RETURN( (osl_File_E_None == osl_getFilePos( m_aFile, &nStartPos ) ) ); + + // copy font file + beginCompression(); + checkAndEnableStreamEncryption( nFontStream ); + sal_Bool bEOF = sal_False; + do + { + char buf[8192]; + sal_uInt64 nRead; + CHECK_RETURN( (osl_File_E_None == osl_readFile( aFontFile, buf, sizeof( buf ), &nRead ) ) ); + CHECK_RETURN( writeBuffer( buf, nRead ) ); + CHECK_RETURN( (osl_File_E_None == osl_isEndOfFile( aFontFile, &bEOF ) ) ); + } while( ! bEOF ); + } + else if( (aSubsetInfo.m_nFontType & FontSubsetInfo::CFF_FONT) != 0 ) + { + // TODO: implement + DBG_ERROR( "PDFWriterImpl does not support CFF-font subsets yet!" ); + } + else if( (aSubsetInfo.m_nFontType & FontSubsetInfo::TYPE1_PFB) != 0 ) // TODO: also support PFA? + { + unsigned char* pBuffer = new unsigned char[ (int)nLength1 ]; + + sal_uInt64 nBytesRead = 0; + CHECK_RETURN( (osl_File_E_None == osl_readFile( aFontFile, pBuffer, nLength1, &nBytesRead ) ) ); + DBG_ASSERT( nBytesRead==nLength1, "PDF-FontSubset read incomplete!" ); + CHECK_RETURN( (osl_File_E_None == osl_setFilePos( aFontFile, osl_Pos_Absolut, 0 ) ) ); + // get the PFB-segment lengths + ThreeInts aSegmentLengths = {0,0,0}; + getPfbSegmentLengths( pBuffer, (int)nBytesRead, aSegmentLengths ); + // the lengths below are mandatory for PDF-exported Type1 fonts + // because the PFB segment headers get stripped! WhyOhWhy. + aLine.append( (sal_Int32)aSegmentLengths[0] ); + aLine.append( "/Length2 " ); + aLine.append( (sal_Int32)aSegmentLengths[1] ); + aLine.append( "/Length3 " ); + aLine.append( (sal_Int32)aSegmentLengths[2] ); + + aLine.append( ">>\n" + "stream\n" ); + CHECK_RETURN( writeBuffer( aLine.getStr(), aLine.getLength() ) ); + CHECK_RETURN( (osl_File_E_None == osl_getFilePos( m_aFile, &nStartPos ) ) ); + + // emit PFB-sections without section headers + beginCompression(); + checkAndEnableStreamEncryption( nFontStream ); + CHECK_RETURN( writeBuffer( pBuffer+ 6, aSegmentLengths[0] ) ); + CHECK_RETURN( writeBuffer( pBuffer+12 + aSegmentLengths[0], aSegmentLengths[1] ) ); + CHECK_RETURN( writeBuffer( pBuffer+18 + aSegmentLengths[0] + aSegmentLengths[1], aSegmentLengths[2] ) ); + + delete[] pBuffer; + } + else + { + fprintf( stderr, "PDF: CreateFontSubset result in not yet supported format=%d\n",aSubsetInfo.m_nFontType); + aLine.append( "0 >>\nstream\n" ); + } endCompression(); disableStreamEncryption(); @@ -3805,7 +3833,7 @@ bool PDFWriterImpl::emitFonts() sal_Int32 nFontDescriptor = emitFontDescriptor( it->first, aSubsetInfo, lit->m_nFontID, nFontStream ); if( nToUnicodeStream ) - nToUnicodeStream = createToUnicodeCMap( pEncoding, pUnicodes, nGlyphs ); + nToUnicodeStream = createToUnicodeCMap( pEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, nGlyphs ); sal_Int32 nFontObject = createObject(); CHECK_RETURN( updateObject( nFontObject ) ); @@ -3814,22 +3842,22 @@ bool PDFWriterImpl::emitFonts() aLine.append( " 0 obj\n" ); aLine.append( ((aSubsetInfo.m_nFontType & FontSubsetInfo::ANY_TYPE1) != 0) ? - "<m_nFontID, aSubsetInfo.m_aPSName, aLine ); aLine.append( "\n" - "/FirstChar 0\n" - "/LastChar " ); + "/FirstChar 0\n" + "/LastChar " ); aLine.append( (sal_Int32)(nGlyphs-1) ); aLine.append( "\n" - "/Widths[" ); + "/Widths[" ); for( int i = 0; i < nGlyphs; i++ ) { aLine.append( pWidths[ i ] ); aLine.append( ((i & 15) == 15) ? "\n" : " " ); } aLine.append( "]\n" - "/FontDescriptor " ); + "/FontDescriptor " ); aLine.append( nFontDescriptor ); aLine.append( " 0 R\n" ); if( nToUnicodeStream ) @@ -3839,7 +3867,7 @@ bool PDFWriterImpl::emitFonts() aLine.append( " 0 R\n" ); } aLine.append( ">>\n" - "endobj\n\n" ); + "endobj\n\n" ); CHECK_RETURN( writeBuffer( aLine.getStr(), aLine.getLength() ) ); aFontIDToObject[ lit->m_nFontID ] = nFontObject; @@ -3877,7 +3905,7 @@ bool PDFWriterImpl::emitFonts() OStringBuffer aFontDict( 1024 ); aFontDict.append( getFontDictObject() ); aFontDict.append( " 0 obj\n" - "<<" ); + "<<" ); int ni = 0; for( std::map< sal_Int32, sal_Int32 >::iterator mit = aFontIDToObject.begin(); mit != aFontIDToObject.end(); ++mit ) { @@ -3886,12 +3914,12 @@ bool PDFWriterImpl::emitFonts() aFontDict.append( ' ' ); aFontDict.append( mit->second ); aFontDict.append( " 0 R" ); - if( ((++ni) & 7) == 0 ) - aFontDict.append( '\n' ); + if( ((++ni) & 7) == 0 ) + aFontDict.append( '\n' ); } // emit builtin font for widget apperances / variable text for( std::map< sal_Int32, sal_Int32 >::iterator it = m_aBuiltinFontToObjectMap.begin(); - it != m_aBuiltinFontToObjectMap.end(); ++it ) + it != m_aBuiltinFontToObjectMap.end(); ++it ) { ImplPdfBuiltinFontData aData(m_aBuiltinFonts[it->first]); it->second = emitBuiltinFont( &aData, it->second ); @@ -6389,12 +6417,14 @@ void PDFWriterImpl::registerGlyphs( int nGlyphs, sal_GlyphId* pGlyphs, sal_Int32* pGlyphWidths, sal_Ucs* pUnicodes, + sal_Int32* pUnicodesPerGlyph, sal_uInt8* pMappedGlyphs, sal_Int32* pMappedFontObjects, const ImplFontData* pFallbackFonts[] ) { const ImplFontData* pDevFont = m_pReferenceDevice->mpFontEntry->maFontSelData.mpFontData; - for( int i = 0; i < nGlyphs; i++ ) + sal_Ucs* pCurUnicode = pUnicodes; + for( int i = 0; i < nGlyphs; pCurUnicode += pUnicodesPerGlyph[i] , i++ ) { const int nFontGlyphId = pGlyphs[i] & (GF_IDXMASK | GF_ISCHAR | GF_GSUB); const ImplFontData* pCurrentFont = pFallbackFonts[i] ? pFallbackFonts[i] : pDevFont; @@ -6450,7 +6480,9 @@ void PDFWriterImpl::registerGlyphs( int nGlyphs, // add new glyph to emitted font subset GlyphEmit& rNewGlyphEmit = rSubset.m_aSubsets.back().m_aMapping[ nFontGlyphId ]; rNewGlyphEmit.m_nSubsetGlyphID = nNewId; - rNewGlyphEmit.m_aUnicode = (pUnicodes ? pUnicodes[i] : 0); + rNewGlyphEmit.m_nUnicodes = pUnicodesPerGlyph[i]; + for( sal_Int32 n = 0; n < pUnicodesPerGlyph[i]; n++ ) + rNewGlyphEmit.m_aUnicodes[n] = pCurUnicode[n]; // add new glyph to font mapping Glyph& rNewGlyph = rSubset.m_aMapping[ nFontGlyphId ]; @@ -6487,7 +6519,7 @@ void PDFWriterImpl::registerGlyphs( int nGlyphs, Ucs2OStrMap::const_iterator nonenc_it; sal_Int32 nCurFontID = nFontID; - sal_Ucs cChar = pUnicodes[i]; + sal_Ucs cChar = *pCurUnicode; if( pEncoding ) { enc_it = pEncoding->find( cChar ); @@ -6549,7 +6581,7 @@ void PDFWriterImpl::registerGlyphs( int nGlyphs, pMappedGlyphs[ i ] = (sal_Int8)cChar; pMappedFontObjects[ i ] = nCurFontID; pGlyphWidths[ i ] = m_aFontCache.getGlyphWidth( pCurrentFont, - (pEncoding ? pUnicodes[i] : cChar) | GF_ISCHAR, + (pEncoding ? *pCurUnicode : cChar) | GF_ISCHAR, false, m_pReferenceDevice->mpGraphics ); } @@ -6829,7 +6861,9 @@ void PDFWriterImpl::drawLayout( SalLayout& rLayout, const String& rText, bool bT sal_Int32 pGlyphWidths[nMaxGlyphs]; sal_uInt8 pMappedGlyphs[nMaxGlyphs]; sal_Int32 pMappedFontObjects[nMaxGlyphs]; - sal_Ucs pUnicodes[nMaxGlyphs]; + std::vector aUnicodes; + aUnicodes.reserve( nMaxGlyphs ); + sal_Int32 pUnicodesPerGlyph[nMaxGlyphs]; int pCharPosAry[nMaxGlyphs]; sal_Int32 nAdvanceWidths[nMaxGlyphs]; const ImplFontData* pFallbackFonts[nMaxGlyphs]; @@ -6962,15 +6996,29 @@ void PDFWriterImpl::drawLayout( SalLayout& rLayout, const String& rText, bool bT Point aGNGlyphPos; while( (nGlyphs = rLayout.GetNextGlyphs( nTmpMaxGlyphs, pGlyphs, aGNGlyphPos, nIndex, nAdvanceWidths, pCharPosAry )) != 0 ) { + aUnicodes.clear(); for( int i = 0; i < nGlyphs; i++ ) { pFallbackFonts[i] = rLayout.GetFallbackFontData( pGlyphs[i] ); + // default case: 1 glyph is one unicode + pUnicodesPerGlyph[i] = 1; if( (pGlyphs[i] & GF_ISCHAR) ) - pUnicodes[i] = static_cast(pGlyphs[i] & GF_IDXMASK); + { + aUnicodes.push_back( static_cast(pGlyphs[i] & GF_IDXMASK) ); + } else if( pCharPosAry[i] >= nMinCharPos && pCharPosAry[i] <= nMaxCharPos ) { - pUnicodes[i] = rText.GetChar( sal::static_int_cast(pCharPosAry[i]) ); + int nChars = 1; + aUnicodes.push_back( rText.GetChar( sal::static_int_cast(pCharPosAry[i]) ) ); + pUnicodesPerGlyph[i] = 1; + // try to handle ligatures and such + if( i < nGlyphs-1 ) + { + pUnicodesPerGlyph[i] = nChars = pCharPosAry[i+1] - pCharPosAry[i]; + for( int n = 1; n < nChars; n++ ) + aUnicodes.push_back( rText.GetChar( sal::static_int_cast(pCharPosAry[i]+n) ) ); + } // #i36691# hack that is needed because currently the pGlyphs[] // argument is ignored for embeddable fonts and so the layout // engine's glyph work is ignored (i.e. char mirroring) @@ -6978,17 +7026,21 @@ void PDFWriterImpl::drawLayout( SalLayout& rLayout, const String& rText, bool bT // glyphid (i.e. FreeType's synthetic glyphid for a Type1 font) // back to unicode and then to embeddable font's encoding if( getReferenceDevice()->GetLayoutMode() & TEXT_LAYOUT_BIDI_RTL ) - pUnicodes[i] = static_cast(GetMirroredChar(pUnicodes[i])); + { + size_t nI = aUnicodes.size()-1; + for( int n = 0; n < nChars; n++, nI-- ) + aUnicodes[nI] = static_cast(GetMirroredChar(aUnicodes[nI])); + } } else - pUnicodes[i] = 0; + aUnicodes.push_back( 0 ); // note: in case of ctl one character may result // in multiple glyphs. The current SalLayout // implementations set -1 then to indicate that no direct // mapping is possible } - registerGlyphs( nGlyphs, pGlyphs, pGlyphWidths, pUnicodes, pMappedGlyphs, pMappedFontObjects, pFallbackFonts ); + registerGlyphs( nGlyphs, pGlyphs, pGlyphWidths, &aUnicodes[0], pUnicodesPerGlyph, pMappedGlyphs, pMappedFontObjects, pFallbackFonts ); for( int i = 0; i < nGlyphs; i++ ) { diff --git a/vcl/source/gdi/pdfwriter_impl.hxx b/vcl/source/gdi/pdfwriter_impl.hxx index 29de6d4f5971..c8b201a7bfb8 100644 --- a/vcl/source/gdi/pdfwriter_impl.hxx +++ b/vcl/source/gdi/pdfwriter_impl.hxx @@ -272,8 +272,16 @@ public: // font subsets struct GlyphEmit { - sal_Ucs m_aUnicode; + static const int nMaxUnicodes = 8; + // performance: actually this should probably a vector; + sal_Ucs m_aUnicodes[nMaxUnicodes]; + sal_Int32 m_nUnicodes; sal_uInt8 m_nSubsetGlyphID; + + GlyphEmit() : m_nUnicodes(0), m_nSubsetGlyphID(0) + { + rtl_zeroMemory( m_aUnicodes, sizeof( m_aUnicodes ) ); + } }; typedef std::map< sal_GlyphId, GlyphEmit > FontEmitMapping; struct FontEmit @@ -856,7 +864,7 @@ i12626 void appendLiteralStringEncrypt( rtl::OStringBuffer& rInString, const sal_Int32 nInObjectNumber, rtl::OStringBuffer& rOutBuffer ); /* creates fonts and subsets that will be emitted later */ - void registerGlyphs( int nGlyphs, sal_GlyphId* pGlyphs, sal_Int32* pGlpyhWidths, sal_Ucs* pUnicodes, sal_uInt8* pMappedGlyphs, sal_Int32* pMappedFontObjects, const ImplFontData* pFallbackFonts[] ); + void registerGlyphs( int nGlyphs, sal_GlyphId* pGlyphs, sal_Int32* pGlpyhWidths, sal_Ucs* pUnicodes, sal_Int32* pUnicodesPerGlyph, sal_uInt8* pMappedGlyphs, sal_Int32* pMappedFontObjects, const ImplFontData* pFallbackFonts[] ); /* emits a text object according to the passed layout */ /* TODO: remove rText as soon as SalLayout will change so that rText is not necessary anymore */ @@ -903,7 +911,7 @@ i12626 /* writes a font descriptor and returns its object id (or 0) */ sal_Int32 emitFontDescriptor( const ImplFontData*, FontSubsetInfo&, sal_Int32 nSubsetID, sal_Int32 nStream ); /* writes a ToUnicode cmap, returns the corresponding stream object */ - sal_Int32 createToUnicodeCMap( sal_uInt8* pEncoding, sal_Ucs* pUnicodes, int nGlyphs ); + sal_Int32 createToUnicodeCMap( sal_uInt8* pEncoding, sal_Ucs* pUnicodes, sal_Int32* pUnicodesPerGlyph, sal_Int32* pEncToUnicodeIndex, int nGlyphs ); /* get resource dict object number */ sal_Int32 getResourceDictObj() -- cgit From daf7906ef7974878d7097649e4fa7669bdd6d53b Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 17 Dec 2009 18:51:23 +0100 Subject: vcl108: #i106704# fix PFA case of Length3 --- vcl/source/gdi/pdfwriter_impl.cxx | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index efec952ffbe2..cf94797db4f9 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -2971,6 +2971,28 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont if( nIndex < 1 || nIndex <= nEndAsciiIndex ) goto streamend; + + // nLength3 is the rest of the file - excluding any section headers + // nIndex now points to the first of the 512 '0' characters marking the + // fixed content portion + sal_Int32 nLength3 = nFontLen - nIndex; + for( it = aSections.begin(); it != aSections.end(); ++it ) + { + if( *it >= nIndex ) + { + // special case: nIndex inside a section marker + if( nIndex >= (*it) && (*it)+5 > nIndex ) + nLength3 -= (*it)+5 - nIndex; + else + { + if( *it < nFontLen - 6 ) + nLength3 -= 6; + else // the last section 0x8003 is only 2 bytes after all + nLength3 -= (nFontLen - *it); + } + } + } + // there may be whitespace to ignore before the 512 '0' while( pFontData[nIndex] == '\r' || pFontData[nIndex] == '\n' ) { @@ -2985,20 +3007,6 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont } nEndBinaryIndex = nIndex; - // nLength3 is the rest of the file - excluding any section headers - sal_Int32 nLength3 = nFontLen - nIndex; - for( it = aSections.begin(); it != aSections.end(); ++it ) - { - if( *it >= nIndex ) - { - // special case: nIndex inside a section marker - if( nIndex >= *it ) - nLength3 -= (*it)+5 - nIndex; - else - nLength3 -= 5; - } - } - // search for beginning of binary section nBeginBinaryIndex = nEndAsciiIndex; do -- cgit From d408e96e7eaf89202a4a2f866708149cb01e8e87 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 17 Dec 2009 19:44:38 +0100 Subject: vcl108: #i106704# fix error handling, avoid memory leaks --- vcl/source/gdi/pdfwriter_impl.cxx | 955 ++++++++++++++++++-------------------- 1 file changed, 463 insertions(+), 492 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index cf94797db4f9..0564be3c1c1f 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -64,6 +64,8 @@ #include "implncvt.hxx" +#include + #include "cppuhelper/implbase1.hxx" #include @@ -2847,6 +2849,10 @@ static bool getPfbSegmentLengths( const unsigned char* pFontBytes, int nByteLen, return true; } +struct FontException : public std::exception +{ +}; + // TODO: always subset instead of embedding the full font => this method becomes obsolete then std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFontData* pFont, EmbedFont& rEmbed ) { @@ -2895,559 +2901,525 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont const unsigned char* pFontData = NULL; long nFontLen = 0; sal_Int32 nLength1, nLength2; - if( (pFontData = (const unsigned char*)m_pReferenceDevice->mpGraphics->GetEmbedFontData( pFont, nEncodedCodes, pWidths, aInfo, &nFontLen )) != NULL ) - { - if( (aInfo.m_nFontType & FontSubsetInfo::ANY_TYPE1) == 0 ) - goto streamend; - // see whether it is pfb or pfa; if it is a pfb, fill ranges - // of 6 bytes that are not part of the font program - std::list< int > aSections; - std::list< int >::const_iterator it; - int nIndex = 0; - while( pFontData[nIndex] == 0x80 && nIndex < nFontLen-1 ) - { - aSections.push_back( nIndex ); - if( pFontData[nIndex+1] == 0x03 ) - break; - sal_Int32 nBytes = + try + { + if( (pFontData = (const unsigned char*)m_pReferenceDevice->mpGraphics->GetEmbedFontData( pFont, nEncodedCodes, pWidths, aInfo, &nFontLen )) != NULL ) + { + if( (aInfo.m_nFontType & FontSubsetInfo::ANY_TYPE1) == 0 ) + throw FontException(); + // see whether it is pfb or pfa; if it is a pfb, fill ranges + // of 6 bytes that are not part of the font program + std::list< int > aSections; + std::list< int >::const_iterator it; + int nIndex = 0; + while( pFontData[nIndex] == 0x80 && nIndex < nFontLen-1 ) + { + aSections.push_back( nIndex ); + if( pFontData[nIndex+1] == 0x03 ) + break; + sal_Int32 nBytes = ((sal_Int32)pFontData[nIndex+2]) | ((sal_Int32)pFontData[nIndex+3]) << 8 | ((sal_Int32)pFontData[nIndex+4]) << 16 | ((sal_Int32)pFontData[nIndex+5]) << 24; - nIndex += nBytes+6; - } - - // search for eexec - // TODO: use getPfbSegmentLengths() if possible to skip the search thingies below - nIndex = 0; - int nEndAsciiIndex; - int nBeginBinaryIndex; - int nEndBinaryIndex; - do - { - while( nIndex < nFontLen-4 && - ( pFontData[nIndex] != 'e' || - pFontData[nIndex+1] != 'e' || - pFontData[nIndex+2] != 'x' || - pFontData[nIndex+3] != 'e' || - pFontData[nIndex+4] != 'c' - ) - ) - nIndex++; - // check whether we are in a excluded section - for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) - ; - } while( it != aSections.end() && nIndex < nFontLen-4 ); - // this should end the ascii part - if( nIndex > nFontLen-5 ) - goto streamend; - - nEndAsciiIndex = nIndex+4; - // now count backwards until we can account for 512 '0' - // which is the endmarker of the (hopefully) binary data - // do not count the pfb header sections - int nFound = 0; - nIndex = nFontLen-1; - while( nIndex > 0 && nFound < 512 ) - { - for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) - ; - if( it == aSections.end() ) - { - // inside the 512 '0' block there may only be whitespace - // according to T1 spec; probably it would be to simple - // if all fonts complied - if( pFontData[nIndex] == '0' ) - nFound++; - else if( nFound > 0 && - pFontData[nIndex] != '\r' && - pFontData[nIndex] != '\t' && - pFontData[nIndex] != '\n' && - pFontData[nIndex] != ' ' ) - break; + nIndex += nBytes+6; } - nIndex--; - } - if( nIndex < 1 || nIndex <= nEndAsciiIndex ) - goto streamend; - - // nLength3 is the rest of the file - excluding any section headers - // nIndex now points to the first of the 512 '0' characters marking the - // fixed content portion - sal_Int32 nLength3 = nFontLen - nIndex; - for( it = aSections.begin(); it != aSections.end(); ++it ) - { - if( *it >= nIndex ) - { - // special case: nIndex inside a section marker - if( nIndex >= (*it) && (*it)+5 > nIndex ) - nLength3 -= (*it)+5 - nIndex; - else - { - if( *it < nFontLen - 6 ) - nLength3 -= 6; - else // the last section 0x8003 is only 2 bytes after all - nLength3 -= (nFontLen - *it); - } - } - } - - // there may be whitespace to ignore before the 512 '0' - while( pFontData[nIndex] == '\r' || pFontData[nIndex] == '\n' ) - { - nIndex--; - for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) - ; - if( it != aSections.end() ) + // search for eexec + // TODO: use getPfbSegmentLengths() if possible to skip the search thingies below + nIndex = 0; + int nEndAsciiIndex; + int nBeginBinaryIndex; + int nEndBinaryIndex; + do { - nIndex = (*it)-1; - break; // this is surely a binary boundary, in ascii case it wouldn't matter - } - } - nEndBinaryIndex = nIndex; - - // search for beginning of binary section - nBeginBinaryIndex = nEndAsciiIndex; - do - { - nBeginBinaryIndex++; - for( it = aSections.begin(); it != aSections.end() && (nBeginBinaryIndex < *it || nBeginBinaryIndex > ((*it) + 5) ); ++it ) - ; - } while( nBeginBinaryIndex < nEndBinaryIndex && - ( pFontData[nBeginBinaryIndex] == '\r' || - pFontData[nBeginBinaryIndex] == '\n' || - it != aSections.end() ) ); - - // it seems to be vital to copy the exact whitespace between binary data - // and eexec, else a invalid font results. so make nEndAsciiIndex - // always immediate in front of nBeginBinaryIndex - nEndAsciiIndex = nBeginBinaryIndex-1; - for( it = aSections.begin(); it != aSections.end() && (nEndAsciiIndex < *it || nEndAsciiIndex > ((*it)+5)); ++it ) - ; - if( it != aSections.end() ) - nEndAsciiIndex = (*it)-1; - - nLength1 = nEndAsciiIndex+1; // including the last character - for( it = aSections.begin(); it != aSections.end() && *it < nEndAsciiIndex; ++it ) - nLength1 -= 6; // decrease by pfb section size - - // if the first four bytes are all ascii hex characters, then binary data - // has to be converted to real binary data - for( nIndex = 0; nIndex < 4 && - ( ( pFontData[ nBeginBinaryIndex+nIndex ] >= '0' && pFontData[ nBeginBinaryIndex+nIndex ] <= '9' ) || - ( pFontData[ nBeginBinaryIndex+nIndex ] >= 'a' && pFontData[ nBeginBinaryIndex+nIndex ] <= 'f' ) || - ( pFontData[ nBeginBinaryIndex+nIndex ] >= 'A' && pFontData[ nBeginBinaryIndex+nIndex ] <= 'F' ) - ); ++nIndex ) - ; - bool bConvertHexData = true; - if( nIndex < 4 ) - { - bConvertHexData = false; - nLength2 = nEndBinaryIndex - nBeginBinaryIndex + 1; // include the last byte - for( it = aSections.begin(); it != aSections.end(); ++it ) - if( *it > nBeginBinaryIndex && *it < nEndBinaryIndex ) - nLength2 -= 6; - } - else - { - // count the hex ascii characters to get nLength2 - nLength2 = 0; - int nNextSectionIndex = 0; - for( it = aSections.begin(); it != aSections.end() && *it < nBeginBinaryIndex; ++it ) - ; - if( it != aSections.end() ) - nNextSectionIndex = *it; - for( nIndex = nBeginBinaryIndex; nIndex <= nEndBinaryIndex; nIndex++ ) + while( nIndex < nFontLen-4 && + ( pFontData[nIndex] != 'e' || + pFontData[nIndex+1] != 'e' || + pFontData[nIndex+2] != 'x' || + pFontData[nIndex+3] != 'e' || + pFontData[nIndex+4] != 'c' + ) + ) + nIndex++; + // check whether we are in a excluded section + for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) + ; + } while( it != aSections.end() && nIndex < nFontLen-4 ); + // this should end the ascii part + if( nIndex > nFontLen-5 ) + throw FontException(); + + nEndAsciiIndex = nIndex+4; + // now count backwards until we can account for 512 '0' + // which is the endmarker of the (hopefully) binary data + // do not count the pfb header sections + int nFound = 0; + nIndex = nFontLen-1; + while( nIndex > 0 && nFound < 512 ) { - if( nIndex == nNextSectionIndex ) + for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) + ; + if( it == aSections.end() ) { - nIndex += 6; - ++it; - nNextSectionIndex = (it == aSections.end() ? 0 : *it ); + // inside the 512 '0' block there may only be whitespace + // according to T1 spec; probably it would be to simple + // if all fonts complied + if( pFontData[nIndex] == '0' ) + nFound++; + else if( nFound > 0 && + pFontData[nIndex] != '\r' && + pFontData[nIndex] != '\t' && + pFontData[nIndex] != '\n' && + pFontData[nIndex] != ' ' ) + break; } - if( ( pFontData[ nIndex ] >= '0' && pFontData[ nIndex ] <= '9' ) || - ( pFontData[ nIndex ] >= 'a' && pFontData[ nIndex ] <= 'f' ) || - ( pFontData[ nIndex ] >= 'A' && pFontData[ nIndex ] <= 'F' ) ) - nLength2++; + nIndex--; } - DBG_ASSERT( !(nLength2 & 1), "uneven number of hex chars in binary pfa section" ); - nLength2 /= 2; - } - // now we can actually write the font stream ! -#if OSL_DEBUG_LEVEL > 1 - { - OStringBuffer aLine( " PDFWriterImpl::emitEmbeddedFont" ); - emitComment( aLine.getStr() ); - } -#endif - OStringBuffer aLine( 512 ); - nStreamObject = createObject(); - if( !updateObject(nStreamObject)) - goto streamend; - sal_Int32 nStreamLengthObject = createObject(); - aLine.append( nStreamObject ); - aLine.append( " 0 obj\n" - "<>\n" - "stream\n" ); - if( !writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; + if( nIndex < 1 || nIndex <= nEndAsciiIndex ) + throw FontException(); - sal_uInt64 nBeginStreamPos = 0; - osl_getFilePos( m_aFile, &nBeginStreamPos ); - - beginCompression(); - checkAndEnableStreamEncryption( nStreamObject ); - - // write ascii section - if( aSections.begin() == aSections.end() ) - { - if( ! writeBuffer( pFontData, nEndAsciiIndex+1 ) ) - { - endCompression(); - disableStreamEncryption(); - goto streamend; - } - } - else - { - // first section always starts at 0 - it = aSections.begin(); - nIndex = (*it)+6; - ++it; - while( *it < nEndAsciiIndex ) + // nLength3 is the rest of the file - excluding any section headers + // nIndex now points to the first of the 512 '0' characters marking the + // fixed content portion + sal_Int32 nLength3 = nFontLen - nIndex; + for( it = aSections.begin(); it != aSections.end(); ++it ) { - if( ! writeBuffer( pFontData+nIndex, (*it)-nIndex ) ) + if( *it >= nIndex ) { - endCompression(); - disableStreamEncryption(); - goto streamend; + // special case: nIndex inside a section marker + if( nIndex >= (*it) && (*it)+5 > nIndex ) + nLength3 -= (*it)+5 - nIndex; + else + { + if( *it < nFontLen - 6 ) + nLength3 -= 6; + else // the last section 0x8003 is only 2 bytes after all + nLength3 -= (nFontLen - *it); + } } - nIndex = (*it)+6; - ++it; } - // write partial last section - if( ! writeBuffer( pFontData+nIndex, nEndAsciiIndex-nIndex+1 ) ) - { - endCompression(); - disableStreamEncryption(); - goto streamend; - } - } - // write binary section - if( ! bConvertHexData ) - { - if( aSections.begin() == aSections.end() ) + // there may be whitespace to ignore before the 512 '0' + while( pFontData[nIndex] == '\r' || pFontData[nIndex] == '\n' ) { - if( ! writeBuffer( pFontData+nBeginBinaryIndex, nFontLen-nBeginBinaryIndex ) ) + nIndex--; + for( it = aSections.begin(); it != aSections.end() && (nIndex < *it || nIndex > ((*it) + 5) ); ++it ) + ; + if( it != aSections.end() ) { - endCompression(); - disableStreamEncryption(); - goto streamend; + nIndex = (*it)-1; + break; // this is surely a binary boundary, in ascii case it wouldn't matter } } - else + nEndBinaryIndex = nIndex; + + // search for beginning of binary section + nBeginBinaryIndex = nEndAsciiIndex; + do { - for( it = aSections.begin(); *it < nBeginBinaryIndex; ++it ) + nBeginBinaryIndex++; + for( it = aSections.begin(); it != aSections.end() && (nBeginBinaryIndex < *it || nBeginBinaryIndex > ((*it) + 5) ); ++it ) ; - // write first partial section - if( ! writeBuffer( pFontData+nBeginBinaryIndex, (*it) - nBeginBinaryIndex ) ) - { - endCompression(); - disableStreamEncryption(); - goto streamend; - } - // write following sections - while( it != aSections.end() ) - { - nIndex = (*it)+6; - ++it; - if( nIndex < nFontLen ) // last section marker is usually the EOF which has only 2 bytes + } while( nBeginBinaryIndex < nEndBinaryIndex && + ( pFontData[nBeginBinaryIndex] == '\r' || + pFontData[nBeginBinaryIndex] == '\n' || + it != aSections.end() ) ); + + // it seems to be vital to copy the exact whitespace between binary data + // and eexec, else a invalid font results. so make nEndAsciiIndex + // always immediate in front of nBeginBinaryIndex + nEndAsciiIndex = nBeginBinaryIndex-1; + for( it = aSections.begin(); it != aSections.end() && (nEndAsciiIndex < *it || nEndAsciiIndex > ((*it)+5)); ++it ) + ; + if( it != aSections.end() ) + nEndAsciiIndex = (*it)-1; + + nLength1 = nEndAsciiIndex+1; // including the last character + for( it = aSections.begin(); it != aSections.end() && *it < nEndAsciiIndex; ++it ) + nLength1 -= 6; // decrease by pfb section size + + // if the first four bytes are all ascii hex characters, then binary data + // has to be converted to real binary data + for( nIndex = 0; nIndex < 4 && + ( ( pFontData[ nBeginBinaryIndex+nIndex ] >= '0' && pFontData[ nBeginBinaryIndex+nIndex ] <= '9' ) || + ( pFontData[ nBeginBinaryIndex+nIndex ] >= 'a' && pFontData[ nBeginBinaryIndex+nIndex ] <= 'f' ) || + ( pFontData[ nBeginBinaryIndex+nIndex ] >= 'A' && pFontData[ nBeginBinaryIndex+nIndex ] <= 'F' ) + ); ++nIndex ) + ; + bool bConvertHexData = true; + if( nIndex < 4 ) + { + bConvertHexData = false; + nLength2 = nEndBinaryIndex - nBeginBinaryIndex + 1; // include the last byte + for( it = aSections.begin(); it != aSections.end(); ++it ) + if( *it > nBeginBinaryIndex && *it < nEndBinaryIndex ) + nLength2 -= 6; + } + else { - sal_Int32 nSectionLen = (it == aSections.end()) ? nFontLen - nIndex : (*it) - nIndex; - if( ! writeBuffer( pFontData+nIndex, nSectionLen ) ) + // count the hex ascii characters to get nLength2 + nLength2 = 0; + int nNextSectionIndex = 0; + for( it = aSections.begin(); it != aSections.end() && *it < nBeginBinaryIndex; ++it ) + ; + if( it != aSections.end() ) + nNextSectionIndex = *it; + for( nIndex = nBeginBinaryIndex; nIndex <= nEndBinaryIndex; nIndex++ ) { - endCompression(); - disableStreamEncryption(); - goto streamend; + if( nIndex == nNextSectionIndex ) + { + nIndex += 6; + ++it; + nNextSectionIndex = (it == aSections.end() ? 0 : *it ); + } + if( ( pFontData[ nIndex ] >= '0' && pFontData[ nIndex ] <= '9' ) || + ( pFontData[ nIndex ] >= 'a' && pFontData[ nIndex ] <= 'f' ) || + ( pFontData[ nIndex ] >= 'A' && pFontData[ nIndex ] <= 'F' ) ) + nLength2++; } + DBG_ASSERT( !(nLength2 & 1), "uneven number of hex chars in binary pfa section" ); + nLength2 /= 2; } - } - } - } - else - { - unsigned char* pWriteBuffer = (unsigned char*)rtl_allocateMemory( nLength2 ); - memset( pWriteBuffer, 0, nLength2 ); - int nWriteIndex = 0; - int nNextSectionIndex = 0; - for( it = aSections.begin(); it != aSections.end() && *it < nBeginBinaryIndex; ++it ) - ; - if( it != aSections.end() ) - nNextSectionIndex = *it; - for( nIndex = nBeginBinaryIndex; nIndex <= nEndBinaryIndex; nIndex++ ) - { - if( nIndex == nNextSectionIndex ) - { - nIndex += 6; - ++it; - nNextSectionIndex = (it == aSections.end() ? nFontLen : *it ); - } - unsigned char cNibble = 0x80; - if( pFontData[ nIndex ] >= '0' && pFontData[ nIndex ] <= '9' ) - cNibble = pFontData[nIndex] - '0'; - else if( pFontData[ nIndex ] >= 'a' && pFontData[ nIndex ] <= 'f' ) - cNibble = pFontData[nIndex] - 'a' + 10; - else if( pFontData[ nIndex ] >= 'A' && pFontData[ nIndex ] <= 'F' ) - cNibble = pFontData[nIndex] - 'A' + 10; - if( cNibble != 0x80 ) - { - if( !(nWriteIndex & 1 ) ) - cNibble <<= 4; - pWriteBuffer[ nWriteIndex/2 ] |= cNibble; - nWriteIndex++; - } - } - if( ! writeBuffer( pWriteBuffer, nLength2 ) ) - { - endCompression(); - disableStreamEncryption(); - goto streamend; - } - rtl_freeMemory( pWriteBuffer ); + // now we can actually write the font stream ! + #if OSL_DEBUG_LEVEL > 1 + { + OStringBuffer aLine( " PDFWriterImpl::emitEmbeddedFont" ); + emitComment( aLine.getStr() ); + } + #endif + OStringBuffer aLine( 512 ); + nStreamObject = createObject(); + if( !updateObject(nStreamObject)) + throw FontException(); + sal_Int32 nStreamLengthObject = createObject(); + aLine.append( nStreamObject ); + aLine.append( " 0 obj\n" + "<>\n" + "stream\n" ); + if( !writeBuffer( aLine.getStr(), aLine.getLength() ) ) + throw FontException(); - if( aSections.empty() ) - { - if( ! writeBuffer( pFontData+nIndex, nFontLen-nIndex ) ) - { - endCompression(); - disableStreamEncryption(); - goto streamend; - } - } - else - { - // write rest of this section - if( nIndex < nNextSectionIndex ) - { - if( ! writeBuffer( pFontData+nIndex, nNextSectionIndex - nIndex ) ) + sal_uInt64 nBeginStreamPos = 0; + osl_getFilePos( m_aFile, &nBeginStreamPos ); + + beginCompression(); + checkAndEnableStreamEncryption( nStreamObject ); + + // write ascii section + if( aSections.begin() == aSections.end() ) { - endCompression(); - disableStreamEncryption(); - goto streamend; + if( ! writeBuffer( pFontData, nEndAsciiIndex+1 ) ) + throw FontException(); } - } - // write following sections - while( it != aSections.end() ) - { - nIndex = (*it)+6; - ++it; - if( nIndex < nFontLen ) // last section marker is usually the EOF which has only 2 bytes + else { - sal_Int32 nSectionLen = (it == aSections.end()) ? nFontLen - nIndex : (*it) - nIndex; - if( ! writeBuffer( pFontData+nIndex, nSectionLen ) ) + // first section always starts at 0 + it = aSections.begin(); + nIndex = (*it)+6; + ++it; + while( *it < nEndAsciiIndex ) { - endCompression(); - disableStreamEncryption(); - goto streamend; + if( ! writeBuffer( pFontData+nIndex, (*it)-nIndex ) ) + throw FontException(); + nIndex = (*it)+6; + ++it; } + // write partial last section + if( ! writeBuffer( pFontData+nIndex, nEndAsciiIndex-nIndex+1 ) ) + throw FontException(); } - } - } - } - endCompression(); - disableStreamEncryption(); - - sal_uInt64 nEndStreamPos = 0; - osl_getFilePos( m_aFile, &nEndStreamPos ); - - // and finally close the stream - aLine.setLength( 0 ); - aLine.append( "\nendstream\nendobj\n\n" ); - if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; + // write binary section + if( ! bConvertHexData ) + { + if( aSections.begin() == aSections.end() ) + { + if( ! writeBuffer( pFontData+nBeginBinaryIndex, nFontLen-nBeginBinaryIndex ) ) + throw FontException(); + } + else + { + for( it = aSections.begin(); *it < nBeginBinaryIndex; ++it ) + ; + // write first partial section + if( ! writeBuffer( pFontData+nBeginBinaryIndex, (*it) - nBeginBinaryIndex ) ) + throw FontException(); + // write following sections + while( it != aSections.end() ) + { + nIndex = (*it)+6; + ++it; + if( nIndex < nFontLen ) // last section marker is usually the EOF which has only 2 bytes + { + sal_Int32 nSectionLen = (it == aSections.end()) ? nFontLen - nIndex : (*it) - nIndex; + if( ! writeBuffer( pFontData+nIndex, nSectionLen ) ) + throw FontException(); + } + } + } + } + else + { + boost::shared_ptr pWriteBuffer( (unsigned char*)rtl_allocateMemory( nLength2 ), rtl_freeMemory ); + rtl_zeroMemory( pWriteBuffer.get(), nLength2 ); + int nWriteIndex = 0; + + int nNextSectionIndex = 0; + for( it = aSections.begin(); it != aSections.end() && *it < nBeginBinaryIndex; ++it ) + ; + if( it != aSections.end() ) + nNextSectionIndex = *it; + for( nIndex = nBeginBinaryIndex; nIndex <= nEndBinaryIndex; nIndex++ ) + { + if( nIndex == nNextSectionIndex ) + { + nIndex += 6; + ++it; + nNextSectionIndex = (it == aSections.end() ? nFontLen : *it ); + } + unsigned char cNibble = 0x80; + if( pFontData[ nIndex ] >= '0' && pFontData[ nIndex ] <= '9' ) + cNibble = pFontData[nIndex] - '0'; + else if( pFontData[ nIndex ] >= 'a' && pFontData[ nIndex ] <= 'f' ) + cNibble = pFontData[nIndex] - 'a' + 10; + else if( pFontData[ nIndex ] >= 'A' && pFontData[ nIndex ] <= 'F' ) + cNibble = pFontData[nIndex] - 'A' + 10; + if( cNibble != 0x80 ) + { + if( !(nWriteIndex & 1 ) ) + cNibble <<= 4; + pWriteBuffer.get()[ nWriteIndex/2 ] |= cNibble; + nWriteIndex++; + } + } + if( ! writeBuffer( pWriteBuffer.get(), nLength2 ) ) + throw FontException(); + if( aSections.empty() ) + { + if( ! writeBuffer( pFontData+nIndex, nFontLen-nIndex ) ) + throw FontException(); + } + else + { + // write rest of this section + if( nIndex < nNextSectionIndex ) + { + if( ! writeBuffer( pFontData+nIndex, nNextSectionIndex - nIndex ) ) + throw FontException(); + } + // write following sections + while( it != aSections.end() ) + { + nIndex = (*it)+6; + ++it; + if( nIndex < nFontLen ) // last section marker is usually the EOF which has only 2 bytes + { + sal_Int32 nSectionLen = (it == aSections.end()) ? nFontLen - nIndex : (*it) - nIndex; + if( ! writeBuffer( pFontData+nIndex, nSectionLen ) ) + throw FontException(); + } + } + } + } + endCompression(); + disableStreamEncryption(); - // write stream length object - aLine.setLength( 0 ); - if( ! updateObject( nStreamLengthObject ) ) - goto streamend; - aLine.append( nStreamLengthObject ); - aLine.append( " 0 obj\n" ); - aLine.append( (sal_Int64)(nEndStreamPos-nBeginStreamPos ) ); - aLine.append( "\nendobj\n\n" ); - if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; - } - else - { - rtl::OStringBuffer aErrorComment( 256 ); - aErrorComment.append( "GetEmbedFontData failed for font \"" ); - aErrorComment.append( OUStringToOString( pFont->GetFamilyName(), RTL_TEXTENCODING_UTF8 ) ); - aErrorComment.append( '\"' ); - if( pFont->GetSlant() == ITALIC_NORMAL ) - aErrorComment.append( " italic" ); - else if( pFont->GetSlant() == ITALIC_OBLIQUE ) - aErrorComment.append( " oblique" ); - aErrorComment.append( " weight=" ); - aErrorComment.append( sal_Int32(pFont->GetWeight()) ); - emitComment( aErrorComment.getStr() ); - } - - if( nStreamObject ) - // write font descriptor - nFontDescriptor = emitFontDescriptor( pFont, aInfo, 0, nStreamObject ); - if( nFontDescriptor ) - { - if( pEncoding ) - nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, sizeof(nEncoding)/sizeof(nEncoding[0]) ); + sal_uInt64 nEndStreamPos = 0; + osl_getFilePos( m_aFile, &nEndStreamPos ); - // write font object - sal_Int32 nObject = createObject(); - if( ! updateObject( nObject ) ) - goto streamend; + // and finally close the stream + aLine.setLength( 0 ); + aLine.append( "\nendstream\nendobj\n\n" ); + if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) + throw FontException(); - OStringBuffer aLine( 1024 ); - aLine.append( nObject ); - aLine.append( " 0 obj\n" - "<mbSymbolFlag && pEncoding == 0 ) - aLine.append( "/Encoding/WinAnsiEncoding\n" ); - if( nToUnicodeStream ) - { - aLine.append( "/ToUnicode " ); - aLine.append( nToUnicodeStream ); - aLine.append( " 0 R\n" ); + // write stream length object + aLine.setLength( 0 ); + if( ! updateObject( nStreamLengthObject ) ) + throw FontException(); + aLine.append( nStreamLengthObject ); + aLine.append( " 0 obj\n" ); + aLine.append( (sal_Int64)(nEndStreamPos-nBeginStreamPos ) ); + aLine.append( "\nendobj\n\n" ); + if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) + throw FontException(); } - aLine.append( "/FirstChar 0 /LastChar 255\n" - "/Widths[" ); - for( int i = 0; i < 256; i++ ) + else { - aLine.append( pWidths[i] ); - aLine.append( ((i&15) == 15) ? "\n" : " " ); - } - aLine.append( "]\n" - "/FontDescriptor " ); - aLine.append( nFontDescriptor ); - aLine.append( " 0 R>>\n" - "endobj\n\n" ); - if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; - - nFontObject = nObject; - - aRet[ rEmbed.m_nNormalFontID ] = nObject; + rtl::OStringBuffer aErrorComment( 256 ); + aErrorComment.append( "GetEmbedFontData failed for font \"" ); + aErrorComment.append( OUStringToOString( pFont->GetFamilyName(), RTL_TEXTENCODING_UTF8 ) ); + aErrorComment.append( '\"' ); + if( pFont->GetSlant() == ITALIC_NORMAL ) + aErrorComment.append( " italic" ); + else if( pFont->GetSlant() == ITALIC_OBLIQUE ) + aErrorComment.append( " oblique" ); + aErrorComment.append( " weight=" ); + aErrorComment.append( sal_Int32(pFont->GetWeight()) ); + emitComment( aErrorComment.getStr() ); + } + + if( nStreamObject ) + // write font descriptor + nFontDescriptor = emitFontDescriptor( pFont, aInfo, 0, nStreamObject ); - // write additional encodings - for( std::list< EmbedEncoding >::iterator enc_it = rEmbed.m_aExtendedEncodings.begin(); enc_it != rEmbed.m_aExtendedEncodings.end(); ++enc_it ) + if( nFontDescriptor ) { - sal_Int32 aEncWidths[ 256 ]; - // emit encoding dict - sal_Int32 nEncObject = createObject(); - if( ! updateObject( nEncObject ) ) - goto streamend; - - OutputDevice* pRef = getReferenceDevice(); - pRef->Push( PUSH_FONT | PUSH_MAPMODE ); - pRef->SetMapMode( MapMode( MAP_PIXEL ) ); - Font aFont( pFont->GetFamilyName(), pFont->GetStyleName(), Size( 0, 1000 ) ); - aFont.SetWeight( pFont->GetWeight() ); - aFont.SetItalic( pFont->GetSlant() ); - aFont.SetPitch( pFont->GetPitch() ); - pRef->SetFont( aFont ); - pRef->ImplNewFont(); - - aLine.setLength( 0 ); - aLine.append( nEncObject ); - aLine.append( " 0 obj\n" - "<::iterator str_it = enc_it->m_aEncVector.begin(); str_it != enc_it->m_aEncVector.end(); ++str_it ) - { - String aStr( str_it->m_aUnicode ); - aEncWidths[nEncoded] = pRef->GetTextWidth( aStr ); - nEncodedCodes[nEncoded] = str_it->m_aUnicode; - nEncoding[nEncoded] = sal::static_int_cast(nEncoded); - pEncToUnicodeIndex[nEncoded] = static_cast(aUnicodes.size()); - aUnicodes.push_back( nEncodedCodes[nEncoded] ); - pUnicodesPerGlyph[nEncoded] = 1; - - aLine.append( " /" ); - aLine.append( str_it->m_aName ); - if( !((++nEncoded) & 15) ) - aLine.append( "\n" ); - } - aLine.append( "]>>\n" - "endobj\n\n" ); - - pRef->Pop(); - - if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; - - nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, nEncoded ); + if( pEncoding ) + nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, sizeof(nEncoding)/sizeof(nEncoding[0]) ); - nObject = createObject(); + // write font object + sal_Int32 nObject = createObject(); if( ! updateObject( nObject ) ) - goto streamend; + throw FontException(); - aLine.setLength( 0 ); + OStringBuffer aLine( 1024 ); aLine.append( nObject ); aLine.append( " 0 obj\n" - "<mbSymbolFlag && pEncoding == 0 ) + aLine.append( "/Encoding/WinAnsiEncoding\n" ); if( nToUnicodeStream ) { aLine.append( "/ToUnicode " ); aLine.append( nToUnicodeStream ); aLine.append( " 0 R\n" ); } - aLine.append( "/FirstChar 0\n" - "/LastChar " ); - aLine.append( (sal_Int32)(nEncoded-1) ); - aLine.append( "\n" - "/Widths[" ); - for( int i = 0; i < nEncoded; i++ ) + aLine.append( "/FirstChar 0 /LastChar 255\n" + "/Widths[" ); + for( int i = 0; i < 256; i++ ) { - aLine.append( aEncWidths[i] ); + aLine.append( pWidths[i] ); aLine.append( ((i&15) == 15) ? "\n" : " " ); } - aLine.append( " ]\n" - "/FontDescriptor " ); + aLine.append( "]\n" + "/FontDescriptor " ); aLine.append( nFontDescriptor ); aLine.append( " 0 R>>\n" - "endobj\n\n" ); + "endobj\n\n" ); if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) - goto streamend; + throw FontException(); + + nFontObject = nObject; + + aRet[ rEmbed.m_nNormalFontID ] = nObject; + + // write additional encodings + for( std::list< EmbedEncoding >::iterator enc_it = rEmbed.m_aExtendedEncodings.begin(); enc_it != rEmbed.m_aExtendedEncodings.end(); ++enc_it ) + { + sal_Int32 aEncWidths[ 256 ]; + // emit encoding dict + sal_Int32 nEncObject = createObject(); + if( ! updateObject( nEncObject ) ) + throw FontException(); + + OutputDevice* pRef = getReferenceDevice(); + pRef->Push( PUSH_FONT | PUSH_MAPMODE ); + pRef->SetMapMode( MapMode( MAP_PIXEL ) ); + Font aFont( pFont->GetFamilyName(), pFont->GetStyleName(), Size( 0, 1000 ) ); + aFont.SetWeight( pFont->GetWeight() ); + aFont.SetItalic( pFont->GetSlant() ); + aFont.SetPitch( pFont->GetPitch() ); + pRef->SetFont( aFont ); + pRef->ImplNewFont(); + + aLine.setLength( 0 ); + aLine.append( nEncObject ); + aLine.append( " 0 obj\n" + "<::iterator str_it = enc_it->m_aEncVector.begin(); str_it != enc_it->m_aEncVector.end(); ++str_it ) + { + String aStr( str_it->m_aUnicode ); + aEncWidths[nEncoded] = pRef->GetTextWidth( aStr ); + nEncodedCodes[nEncoded] = str_it->m_aUnicode; + nEncoding[nEncoded] = sal::static_int_cast(nEncoded); + pEncToUnicodeIndex[nEncoded] = static_cast(aUnicodes.size()); + aUnicodes.push_back( nEncodedCodes[nEncoded] ); + pUnicodesPerGlyph[nEncoded] = 1; + + aLine.append( " /" ); + aLine.append( str_it->m_aName ); + if( !((++nEncoded) & 15) ) + aLine.append( "\n" ); + } + aLine.append( "]>>\n" + "endobj\n\n" ); - aRet[ enc_it->m_nFontID ] = nObject; + pRef->Pop(); + + if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) + throw FontException(); + + nToUnicodeStream = createToUnicodeCMap( nEncoding, &aUnicodes[0], pUnicodesPerGlyph, pEncToUnicodeIndex, nEncoded ); + + nObject = createObject(); + if( ! updateObject( nObject ) ) + throw FontException(); + + aLine.setLength( 0 ); + aLine.append( nObject ); + aLine.append( " 0 obj\n" + "<>\n" + "endobj\n\n" ); + if( ! writeBuffer( aLine.getStr(), aLine.getLength() ) ) + throw FontException(); + + aRet[ enc_it->m_nFontID ] = nObject; + } } } + catch( FontException& ) + { + // these do nothing in case there was no compression or encryption ongoing + endCompression(); + disableStreamEncryption(); + } - streamend: if( pFontData ) m_pReferenceDevice->mpGraphics->FreeEmbedFontData( pFontData, nFontLen ); @@ -9382,7 +9354,7 @@ bool PDFWriterImpl::writeBitmapObject( BitmapEmit& rObject, bool bMask ) sal_uInt64 nStartPos = 0; CHECK_RETURN( (osl_File_E_None == osl_getFilePos( m_aFile, &nStartPos )) ); - checkAndEnableStreamEncryption( rObject.m_nObject ); + checkAndEnableStreamEncryption( rObject.m_nObject ); beginCompression(); if( ! bTrueColor || pAccess->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_RGB ) { @@ -9396,19 +9368,18 @@ bool PDFWriterImpl::writeBitmapObject( BitmapEmit& rObject, bool bMask ) else { const int nScanLineBytes = pAccess->Width()*3; - sal_uInt8 *pCol = (sal_uInt8*)rtl_allocateMemory( nScanLineBytes ); + boost::shared_ptr pCol( (sal_uInt8*)rtl_allocateMemory( nScanLineBytes ), rtl_freeMemory ); for( int y = 0; y < pAccess->Height(); y++ ) { for( int x = 0; x < pAccess->Width(); x++ ) { BitmapColor aColor = pAccess->GetColor( y, x ); - pCol[3*x+0] = aColor.GetRed(); - pCol[3*x+1] = aColor.GetGreen(); - pCol[3*x+2] = aColor.GetBlue(); + pCol.get()[3*x+0] = aColor.GetRed(); + pCol.get()[3*x+1] = aColor.GetGreen(); + pCol.get()[3*x+2] = aColor.GetBlue(); } - CHECK_RETURN( writeBuffer( pCol, nScanLineBytes ) ); + CHECK_RETURN( writeBuffer( pCol.get(), nScanLineBytes ) ); } - rtl_freeMemory( pCol ); } endCompression(); disableStreamEncryption(); -- cgit From f4ccd00d3626347be13ca5919a07bb39b58729c5 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 18 Dec 2009 11:44:01 +0100 Subject: vcl108: #i107254# copy with arbitrary length ligatures --- vcl/source/gdi/pdfwriter_impl.cxx | 15 ++++++------ vcl/source/gdi/pdfwriter_impl.hxx | 49 ++++++++++++++++++++++++++++++++++----- 2 files changed, 50 insertions(+), 14 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index 0564be3c1c1f..7db8325bfedd 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -3669,7 +3669,7 @@ bool PDFWriterImpl::emitFonts() rtl_zeroMemory( pEncToUnicodeIndex, sizeof( pEncToUnicodeIndex ) ); for( FontEmitMapping::iterator fit = lit->m_aMapping.begin(); fit != lit->m_aMapping.end();++fit ) { - sal_uInt8 nEnc = fit->second.m_nSubsetGlyphID; + sal_uInt8 nEnc = fit->second.getGlyphId(); DBG_ASSERT( pGlyphIDs[nEnc] == 0 && pEncoding[nEnc] == 0, "duplicate glyph" ); DBG_ASSERT( nEnc <= lit->m_aMapping.size(), "invalid glyph encoding" ); @@ -3677,10 +3677,10 @@ bool PDFWriterImpl::emitFonts() pGlyphIDs[ nEnc ] = fit->first; pEncoding[ nEnc ] = nEnc; pEncToUnicodeIndex[ nEnc ] = static_cast(aUnicodes.size()); - pUnicodesPerGlyph[ nEnc ] = fit->second.m_nUnicodes; - for( sal_Int32 n = 0; n < fit->second.m_nUnicodes; n++ ) - aUnicodes.push_back( fit->second.m_aUnicodes[n] ); - if( fit->second.m_aUnicodes[0] ) + pUnicodesPerGlyph[ nEnc ] = fit->second.countCodes(); + for( sal_Int32 n = 0; n < pUnicodesPerGlyph[ nEnc ]; n++ ) + aUnicodes.push_back( fit->second.getCode( n ) ); + if( fit->second.getCode(0) ) nToUnicodeStream = 1; if( nGlyphs < 256 ) nGlyphs++; @@ -6459,10 +6459,9 @@ void PDFWriterImpl::registerGlyphs( int nGlyphs, // add new glyph to emitted font subset GlyphEmit& rNewGlyphEmit = rSubset.m_aSubsets.back().m_aMapping[ nFontGlyphId ]; - rNewGlyphEmit.m_nSubsetGlyphID = nNewId; - rNewGlyphEmit.m_nUnicodes = pUnicodesPerGlyph[i]; + rNewGlyphEmit.setGlyphId( nNewId ); for( sal_Int32 n = 0; n < pUnicodesPerGlyph[i]; n++ ) - rNewGlyphEmit.m_aUnicodes[n] = pCurUnicode[n]; + rNewGlyphEmit.addCode( pCurUnicode[n] ); // add new glyph to font mapping Glyph& rNewGlyph = rSubset.m_aMapping[ nFontGlyphId ]; diff --git a/vcl/source/gdi/pdfwriter_impl.hxx b/vcl/source/gdi/pdfwriter_impl.hxx index c8b201a7bfb8..68cf8a808303 100644 --- a/vcl/source/gdi/pdfwriter_impl.hxx +++ b/vcl/source/gdi/pdfwriter_impl.hxx @@ -52,6 +52,8 @@ #include #include +#include + class ImplFontSelectData; class ImplFontMetricData; class FontSubsetInfo; @@ -270,17 +272,52 @@ public: }; // font subsets - struct GlyphEmit + class GlyphEmit { - static const int nMaxUnicodes = 8; // performance: actually this should probably a vector; - sal_Ucs m_aUnicodes[nMaxUnicodes]; - sal_Int32 m_nUnicodes; - sal_uInt8 m_nSubsetGlyphID; + sal_Ucs m_aBufferedUnicodes[3]; + sal_Int32 m_nUnicodes; + sal_Int32 m_nMaxUnicodes; + boost::shared_array m_pUnicodes; + sal_uInt8 m_nSubsetGlyphID; + public: GlyphEmit() : m_nUnicodes(0), m_nSubsetGlyphID(0) { - rtl_zeroMemory( m_aUnicodes, sizeof( m_aUnicodes ) ); + rtl_zeroMemory( m_aBufferedUnicodes, sizeof( m_aBufferedUnicodes ) ); + m_nMaxUnicodes = sizeof(m_aBufferedUnicodes)/sizeof(m_aBufferedUnicodes[0]); + } + ~GlyphEmit() + { + } + + void setGlyphId( sal_uInt8 i_nId ) { m_nSubsetGlyphID = i_nId; } + sal_uInt8 getGlyphId() const { return m_nSubsetGlyphID; } + + void addCode( sal_Ucs i_cCode ) + { + if( m_nUnicodes == m_nMaxUnicodes ) + { + sal_Ucs* pNew = new sal_Ucs[ 2 * m_nMaxUnicodes]; + if( m_pUnicodes.get() ) + rtl_copyMemory( pNew, m_pUnicodes.get(), m_nMaxUnicodes * sizeof(sal_Ucs) ); + else + rtl_copyMemory( pNew, m_aBufferedUnicodes, m_nMaxUnicodes * sizeof(sal_Ucs) ); + m_pUnicodes.reset( pNew ); + m_nMaxUnicodes *= 2; + } + if( m_pUnicodes.get() ) + m_pUnicodes[ m_nUnicodes++ ] = i_cCode; + else + m_aBufferedUnicodes[ m_nUnicodes++ ] = i_cCode; + } + sal_Int32 countCodes() const { return m_nUnicodes; } + sal_Ucs getCode( sal_Int32 i_nIndex ) const + { + sal_Ucs nRet = 0; + if( i_nIndex < m_nUnicodes ) + nRet = m_pUnicodes.get() ? m_pUnicodes[ i_nIndex ] : m_aBufferedUnicodes[ i_nIndex ]; + return nRet; } }; typedef std::map< sal_GlyphId, GlyphEmit > FontEmitMapping; -- cgit From a0c826b44af446e44b7dc4e80919c1c7f00c2eee Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 18 Dec 2009 11:48:57 +0100 Subject: #vcl108: #i106704# use shared_array as is more appropriate --- vcl/source/gdi/pdfwriter_impl.cxx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index 7db8325bfedd..496ce037e1b3 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -64,8 +64,6 @@ #include "implncvt.hxx" -#include - #include "cppuhelper/implbase1.hxx" #include @@ -3175,7 +3173,7 @@ std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitEmbeddedFont( const ImplFont } else { - boost::shared_ptr pWriteBuffer( (unsigned char*)rtl_allocateMemory( nLength2 ), rtl_freeMemory ); + boost::shared_array pWriteBuffer( new unsigned char[ nLength2 ] ); rtl_zeroMemory( pWriteBuffer.get(), nLength2 ); int nWriteIndex = 0; @@ -9367,15 +9365,15 @@ bool PDFWriterImpl::writeBitmapObject( BitmapEmit& rObject, bool bMask ) else { const int nScanLineBytes = pAccess->Width()*3; - boost::shared_ptr pCol( (sal_uInt8*)rtl_allocateMemory( nScanLineBytes ), rtl_freeMemory ); + boost::shared_array pCol( new sal_uInt8[ nScanLineBytes ] ); for( int y = 0; y < pAccess->Height(); y++ ) { for( int x = 0; x < pAccess->Width(); x++ ) { BitmapColor aColor = pAccess->GetColor( y, x ); - pCol.get()[3*x+0] = aColor.GetRed(); - pCol.get()[3*x+1] = aColor.GetGreen(); - pCol.get()[3*x+2] = aColor.GetBlue(); + pCol[3*x+0] = aColor.GetRed(); + pCol[3*x+1] = aColor.GetGreen(); + pCol[3*x+2] = aColor.GetBlue(); } CHECK_RETURN( writeBuffer( pCol.get(), nScanLineBytes ) ); } -- cgit From 460919060e77525e3ac3e94054fc0f17fae5ba17 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 18 Dec 2009 15:29:59 +0100 Subject: vcl108: #i2446# add prominent entry style to listbox and combobox --- svtools/source/control/ctrlbox.cxx | 1 + vcl/inc/vcl/combobox.hxx | 4 ++++ vcl/inc/vcl/ilstbox.hxx | 10 ++++++++++ vcl/inc/vcl/lstbox.hxx | 4 ++++ vcl/inc/vcl/wintypes.hxx | 6 ++++++ vcl/source/control/combobox.cxx | 24 ++++++++++++++++++++++-- vcl/source/control/ilstbox.cxx | 27 +++++++++++++++++++-------- vcl/source/control/lstbox.cxx | 21 +++++++++++++++++++++ 8 files changed, 87 insertions(+), 10 deletions(-) diff --git a/svtools/source/control/ctrlbox.cxx b/svtools/source/control/ctrlbox.cxx index 097bba0e39f9..b4d8d0506917 100644 --- a/svtools/source/control/ctrlbox.cxx +++ b/svtools/source/control/ctrlbox.cxx @@ -1152,6 +1152,7 @@ void FontSizeBox::ImplInit() SetDecimalDigits( 1 ); SetMin( 20 ); SetMax( 9999 ); + SetProminentEntryType( PROMINENT_MIDDLE ); } // ----------------------------------------------------------------------- diff --git a/vcl/inc/vcl/combobox.hxx b/vcl/inc/vcl/combobox.hxx index d57d4b8a7372..cbceffaff6c0 100644 --- a/vcl/inc/vcl/combobox.hxx +++ b/vcl/inc/vcl/combobox.hxx @@ -192,8 +192,12 @@ public: void* GetEntryData( USHORT nPos ) const; void SetTopEntry( USHORT nPos ); + void ShowProminentEntry( USHORT nPos ); USHORT GetTopEntry() const; + void SetProminentEntryType( ProminentEntry eType ); + ProminentEntry GetProminentEntryType() const; + USHORT GetDisplayLineCount() const; USHORT GetSelectEntryCount() const; diff --git a/vcl/inc/vcl/ilstbox.hxx b/vcl/inc/vcl/ilstbox.hxx index 81dd32ef2705..f38825028080 100644 --- a/vcl/inc/vcl/ilstbox.hxx +++ b/vcl/inc/vcl/ilstbox.hxx @@ -227,6 +227,7 @@ private: long mnLeft; // Ausgabe ab Spalte long mnBorder; // Abstand Rahmen - Text long mnTextHeight; // Texthoehe + ProminentEntry meProminentType; // where is the "prominent" entry USHORT mnSelectModifier; // Modifiers @@ -309,6 +310,11 @@ public: void SetTopEntry( USHORT nTop ); USHORT GetTopEntry() const { return mnTop; } + // ShowProminentEntry will set the entry correspoding to nEntryPos + // either at top or in the middle depending on the chosen style + void ShowProminentEntry( USHORT nEntryPos ); + void SetProminentEntryType( ProminentEntry eType ) { meProminentType = eType; } + ProminentEntry GetProminentEntryType() const { return meProminentType; } using Window::IsVisible; BOOL IsVisible( USHORT nEntry ) const; @@ -443,9 +449,13 @@ public: void SetTopEntry( USHORT nTop ) { maLBWindow.SetTopEntry( nTop ); } USHORT GetTopEntry() const { return maLBWindow.GetTopEntry(); } + void ShowProminentEntry( USHORT nPos ) { maLBWindow.ShowProminentEntry( nPos ); } using Window::IsVisible; BOOL IsVisible( USHORT nEntry ) const { return maLBWindow.IsVisible( nEntry ); } + void SetProminentEntryType( ProminentEntry eType ) { maLBWindow.SetProminentEntryType( eType ); } + ProminentEntry GetProminentEntryType() const { return maLBWindow.GetProminentEntryType(); } + long GetLeftIndent() const { return maLBWindow.GetLeftIndent(); } void SetLeftIndent( USHORT n ) { maLBWindow.SetLeftIndent( n ); } void ScrollHorz( short nDiff ) { maLBWindow.ScrollHorz( nDiff ); } diff --git a/vcl/inc/vcl/lstbox.hxx b/vcl/inc/vcl/lstbox.hxx index 0bf281798674..806ff9bb3e0f 100644 --- a/vcl/inc/vcl/lstbox.hxx +++ b/vcl/inc/vcl/lstbox.hxx @@ -168,9 +168,13 @@ public: long GetEntryFlags( USHORT nPos ) const; void SetTopEntry( USHORT nPos ); + void ShowProminentEntry( USHORT nPos ); void SetTopEntryStr( const XubString& rStr ); USHORT GetTopEntry() const; + void SetProminentEntryType( ProminentEntry eType ); + ProminentEntry GetProminentEntryType() const; + void SaveValue() { mnSaveValue = GetSelectEntryPos(); } USHORT GetSavedValue() const { return mnSaveValue; } diff --git a/vcl/inc/vcl/wintypes.hxx b/vcl/inc/vcl/wintypes.hxx index 968f0e1d255f..1c32001a649b 100644 --- a/vcl/inc/vcl/wintypes.hxx +++ b/vcl/inc/vcl/wintypes.hxx @@ -333,5 +333,11 @@ typedef USHORT StandardButtonType; #define BUTTON_LESS ((StandardButtonType)10) #define BUTTON_COUNT 11 +// -------------------------------------------- +// - prominent place for ListBox window types - +// -------------------------------------------- + +enum ProminentEntry { PROMINENT_TOP, PROMINENT_MIDDLE }; + #endif // _SV_WINTYPES_HXX diff --git a/vcl/source/control/combobox.cxx b/vcl/source/control/combobox.cxx index 21707d0182f5..1eea72131b86 100644 --- a/vcl/source/control/combobox.cxx +++ b/vcl/source/control/combobox.cxx @@ -951,7 +951,7 @@ void ComboBox::ImplUpdateFloatSelection() if( nSelect != LISTBOX_ENTRY_NOTFOUND ) { if ( !mpImplLB->IsVisible( nSelect ) ) - mpImplLB->SetTopEntry( nSelect ); + mpImplLB->ShowProminentEntry( nSelect ); mpImplLB->SelectEntry( nSelect, bSelect ); } else @@ -959,7 +959,6 @@ void ComboBox::ImplUpdateFloatSelection() nSelect = mpImplLB->GetEntryList()->GetSelectEntryPos( 0 ); if( nSelect != LISTBOX_ENTRY_NOTFOUND ) mpImplLB->SelectEntry( nSelect, FALSE ); - // mpImplLB->SetTopEntry( 0 ); #92555# Ugly.... mpImplLB->ResetCurrentPos(); } } @@ -1440,6 +1439,13 @@ void ComboBox::SetTopEntry( USHORT nPos ) // ----------------------------------------------------------------------- +void ComboBox::ShowProminentEntry( USHORT nPos ) +{ + mpImplLB->ShowProminentEntry( nPos + mpImplLB->GetEntryList()->GetMRUCount() ); +} + +// ----------------------------------------------------------------------- + USHORT ComboBox::GetTopEntry() const { USHORT nPos = GetEntryCount() ? mpImplLB->GetTopEntry() : LISTBOX_ENTRY_NOTFOUND; @@ -1450,6 +1456,20 @@ USHORT ComboBox::GetTopEntry() const // ----------------------------------------------------------------------- +void ComboBox::SetProminentEntryType( ProminentEntry eType ) +{ + mpImplLB->SetProminentEntryType( eType ); +} + +// ----------------------------------------------------------------------- + +ProminentEntry ComboBox::GetProminentEntryType() const +{ + return mpImplLB->GetProminentEntryType(); +} + +// ----------------------------------------------------------------------- + Rectangle ComboBox::GetDropDownPosSizePixel() const { return mpFloatWin ? mpFloatWin->GetWindowExtentsRelative( const_cast(this) ) : Rectangle(); diff --git a/vcl/source/control/ilstbox.cxx b/vcl/source/control/ilstbox.cxx index a915d8e6b9e8..490651bd8b17 100644 --- a/vcl/source/control/ilstbox.cxx +++ b/vcl/source/control/ilstbox.cxx @@ -565,6 +565,7 @@ ImplListBoxWindow::ImplListBoxWindow( Window* pParent, WinBits nWinStyle ) : mnCurrentPos = LISTBOX_ENTRY_NOTFOUND; mnTrackingSaveSelection = LISTBOX_ENTRY_NOTFOUND; mnSeparatorPos = LISTBOX_ENTRY_NOTFOUND; + meProminentType = PROMINENT_TOP; SetLineColor(); SetTextFillColor(); @@ -1067,11 +1068,11 @@ void ImplListBoxWindow::SelectEntry( USHORT nPos, BOOL bSelect ) if ( !nVisibleEntries || !IsReallyVisible() || ( nPos < GetTopEntry() ) ) { Resize(); - SetTopEntry( nPos ); + ShowProminentEntry( nPos ); } else { - SetTopEntry( nPos-nVisibleEntries+1 ); + ShowProminentEntry( nPos ); } } } @@ -1702,11 +1703,7 @@ BOOL ImplListBoxWindow::ProcessKeyInput( const KeyEvent& rKEvt ) if ( nSelect != LISTBOX_ENTRY_NOTFOUND ) { - USHORT nCurVis = GetLastVisibleEntry() - mnTop + 1; - if( nSelect < mnTop ) - SetTopEntry( nSelect ); - else if( nSelect >= (mnTop + nCurVis) ) - SetTopEntry( nSelect - nCurVis + 1 ); + ShowProminentEntry( nSelect ); if ( mpEntryList->IsEntryPosSelected( nSelect ) ) nSelect = LISTBOX_ENTRY_NOTFOUND; @@ -2051,6 +2048,20 @@ void ImplListBoxWindow::SetTopEntry( USHORT nTop ) // ----------------------------------------------------------------------- +void ImplListBoxWindow::ShowProminentEntry( USHORT nEntryPos ) +{ + if( meProminentType == PROMINENT_MIDDLE ) + { + USHORT nPos = nEntryPos; + long nWHeight = PixelToLogic( GetSizePixel() ).Height(); + while( nEntryPos > 0 && mpEntryList->GetAddedHeight( nPos+1, nEntryPos ) < nWHeight/2 ) + nEntryPos--; + } + SetTopEntry( nEntryPos ); +} + +// ----------------------------------------------------------------------- + void ImplListBoxWindow::SetLeftIndent( long n ) { ScrollHorz( n - mnLeft ); @@ -3204,7 +3215,7 @@ void ImplListBoxFloatingWindow::StartFloat( BOOL bStartTracking ) StartPopupMode( aRect, FLOATWIN_POPUPMODE_DOWN ); if( nPos != LISTBOX_ENTRY_NOTFOUND ) - mpImplLB->SetTopEntry( nPos ); + mpImplLB->ShowProminentEntry( nPos ); if( bStartTracking ) mpImplLB->GetMainWindow()->EnableMouseMoveSelect( TRUE ); diff --git a/vcl/source/control/lstbox.cxx b/vcl/source/control/lstbox.cxx index ceabbe4ab166..37ce438fa79e 100644 --- a/vcl/source/control/lstbox.cxx +++ b/vcl/source/control/lstbox.cxx @@ -1209,6 +1209,13 @@ void ListBox::SetTopEntry( USHORT nPos ) // ----------------------------------------------------------------------- +void ListBox::ShowProminentEntry( USHORT nPos ) +{ + mpImplLB->ShowProminentEntry( nPos + mpImplLB->GetEntryList()->GetMRUCount() ); +} + +// ----------------------------------------------------------------------- + USHORT ListBox::GetTopEntry() const { USHORT nPos = GetEntryCount() ? mpImplLB->GetTopEntry() : LISTBOX_ENTRY_NOTFOUND; @@ -1219,6 +1226,20 @@ USHORT ListBox::GetTopEntry() const // ----------------------------------------------------------------------- +void ListBox::SetProminentEntryType( ProminentEntry eType ) +{ + mpImplLB->SetProminentEntryType( eType ); +} + +// ----------------------------------------------------------------------- + +ProminentEntry ListBox::GetProminentEntryType() const +{ + return mpImplLB->GetProminentEntryType(); +} + +// ----------------------------------------------------------------------- + BOOL ListBox::IsTravelSelect() const { return mpImplLB->IsTravelSelect(); -- cgit From 45e8e0fbee40f9a8d91f4c559c8bbb16dd7b3f36 Mon Sep 17 00:00:00 2001 From: sj Date: Mon, 21 Dec 2009 17:44:36 +0100 Subject: impress181: #i87410#: now writing greyscale jpgs if possible --- svtools/source/filter.vcl/jpeg/jpeg.cxx | 39 +++++++++++++++++++++++++++++---- svtools/source/filter.vcl/jpeg/jpeg.h | 2 +- svtools/source/filter.vcl/jpeg/jpegc.c | 14 +++++++++--- 3 files changed, 47 insertions(+), 8 deletions(-) diff --git a/svtools/source/filter.vcl/jpeg/jpeg.cxx b/svtools/source/filter.vcl/jpeg/jpeg.cxx index 81d07ccd5e79..ee2b2baebee0 100644 --- a/svtools/source/filter.vcl/jpeg/jpeg.cxx +++ b/svtools/source/filter.vcl/jpeg/jpeg.cxx @@ -656,10 +656,14 @@ void* JPEGWriter::GetScanline( long nY ) aColor = pAcc->GetPaletteColor( (BYTE) pAcc->GetPixel( nY, nX ) ); #ifndef SYSTEM_JPEG *pTmp++ = aColor.GetBlue(); + if ( bGreys ) + continue; *pTmp++ = aColor.GetGreen(); *pTmp++ = aColor.GetRed(); #else *pTmp++ = aColor.GetRed(); + if ( bGreys ) + continue; *pTmp++ = aColor.GetGreen(); *pTmp++ = aColor.GetBlue(); #endif @@ -672,10 +676,14 @@ void* JPEGWriter::GetScanline( long nY ) aColor = pAcc->GetPixel( nY, nX ); #ifndef SYSTEM_JPEG *pTmp++ = aColor.GetBlue(); + if ( bGreys ) + continue; *pTmp++ = aColor.GetGreen(); *pTmp++ = aColor.GetRed(); #else *pTmp++ = aColor.GetRed(); + if ( bGreys ) + continue; *pTmp++ = aColor.GetGreen(); *pTmp++ = aColor.GetBlue(); #endif @@ -711,20 +719,43 @@ BOOL JPEGWriter::Write( const Graphic& rGraphic ) pAcc = aGraphicBmp.AcquireReadAccess(); + if ( !bGreys ) // bitmap was not explicitely converted into greyscale, + { // check if source is greyscale only + + sal_Bool bIsGrey = sal_True; + + long nWidth = pAcc->Width(); + for ( long nY = 0; bIsGrey && ( nY < pAcc->Height() ); nY++ ) + { + BitmapColor aColor; + for( long nX = 0L; bIsGrey && ( nX < nWidth ); nX++ ) + { + aColor = pAcc->HasPalette() ? pAcc->GetPaletteColor( (BYTE) pAcc->GetPixel( nY, nX ) ) + : pAcc->GetPixel( nY, nX ); + bIsGrey = ( aColor.GetRed() == aColor.GetGreen() ) && ( aColor.GetRed() == aColor.GetBlue() ); + } + } + if ( bIsGrey ) + bGreys = sal_True; + } + if( pAcc ) { + if ( bGreys ) + bNative = ( pAcc->GetScanlineFormat() == BMP_FORMAT_8BIT_PAL ); + else #ifndef SYSTEM_JPEG - bNative = ( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_BGR ); + bNative = ( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_BGR ); #else - bNative = ( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_RGB ); + bNative = ( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_RGB ); #endif if( !bNative ) - pBuffer = new BYTE[ AlignedWidth4Bytes( pAcc->Width() * 24L ) ]; + pBuffer = new BYTE[ AlignedWidth4Bytes( bGreys ? pAcc->Width() * 8L : pAcc->Width() * 24L ) ]; JPEGCallbackStruct aCallbackData; aCallbackData.xStatusIndicator = xStatusIndicator; - bRet = (BOOL) WriteJPEG( this, &rOStm, pAcc->Width(), pAcc->Height(), nQuality, &aCallbackData ); + bRet = (BOOL) WriteJPEG( this, &rOStm, pAcc->Width(), pAcc->Height(), bGreys, nQuality, &aCallbackData ); delete[] pBuffer; pBuffer = NULL; diff --git a/svtools/source/filter.vcl/jpeg/jpeg.h b/svtools/source/filter.vcl/jpeg/jpeg.h index eaeaa503b5e9..4d5aafe413bb 100644 --- a/svtools/source/filter.vcl/jpeg/jpeg.h +++ b/svtools/source/filter.vcl/jpeg/jpeg.h @@ -64,7 +64,7 @@ void* JPEGMalloc( size_t size ); void JPEGFree( void *ptr ); long JPEGCallback( void* pCallbackData, long nPercent ); -long WriteJPEG( void* pJPEGWriter, void* pOStm, long nWidth, long nHeight, +long WriteJPEG( void* pJPEGWriter, void* pOStm, long nWidth, long nHeight, long bGreyScale, long nQualityPercent, void* pCallbackData ); void* GetScanline( void* pJPEGWriter, long nY ); diff --git a/svtools/source/filter.vcl/jpeg/jpegc.c b/svtools/source/filter.vcl/jpeg/jpegc.c index 84394d945f79..0525877f2614 100644 --- a/svtools/source/filter.vcl/jpeg/jpegc.c +++ b/svtools/source/filter.vcl/jpeg/jpegc.c @@ -182,7 +182,7 @@ Exit: } long WriteJPEG( void* pJPEGWriter, void* pOStm, - long nWidth, long nHeight, + long nWidth, long nHeight, long bGreys, long nQualityPercent, void* pCallbackData ) { struct jpeg_compress_struct cinfo; @@ -208,8 +208,16 @@ long WriteJPEG( void* pJPEGWriter, void* pOStm, cinfo.image_width = (JDIMENSION) nWidth; cinfo.image_height = (JDIMENSION) nHeight; - cinfo.input_components = 3; - cinfo.in_color_space = JCS_RGB; + if ( bGreys ) + { + cinfo.input_components = 1; + cinfo.in_color_space = JCS_GRAYSCALE; + } + else + { + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + } jpeg_set_defaults( &cinfo ); jpeg_set_quality( &cinfo, (int) nQualityPercent, FALSE ); -- cgit From bffdf143d5924fd277000fad4a7e7108d6d8f041 Mon Sep 17 00:00:00 2001 From: Christian Lippka Date: Mon, 28 Dec 2009 15:02:47 +0000 Subject: #i107965# report rectangles with 0 or negative width or height as empty --- vcl/source/gdi/outdev3.cxx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/vcl/source/gdi/outdev3.cxx b/vcl/source/gdi/outdev3.cxx index 51aad0790a26..e39ca248567f 100644 --- a/vcl/source/gdi/outdev3.cxx +++ b/vcl/source/gdi/outdev3.cxx @@ -7479,7 +7479,7 @@ BOOL OutputDevice::GetTextBoundRect( Rectangle& rRect, { bRet = pSalLayout->GetBoundRect( *mpGraphics, aPixelRect ); - if( bRet ) + if( bRet && (aPixelRect.GetWidth() > 0) || (aPixelRect.GetHeight() > 0) ) { int nWidthFactor = pSalLayout->GetUnitsPerPixel(); @@ -7601,6 +7601,12 @@ BOOL OutputDevice::GetTextBoundRect( Rectangle& rRect, aBmp.ReleaseAccess( pAcc ); + if( (nRight <= nLeft) || (nBottom <= nTop) ) + { + rRect.SetEmpty(); + return TRUE; + } + if( nTop <= nBottom ) { Size aSize( nRight - nLeft + 1, nBottom - nTop + 1 ); -- cgit From 6a556771abe12e1ac41fd1d39583ee62d46fa082 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Mon, 4 Jan 2010 12:55:58 +0000 Subject: exchgcmtdoc2: #i72096#: fix imagemagick convert usage under windows --- goodies/source/filter.vcl/ieps/ieps.cxx | 68 ++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 13 deletions(-) diff --git a/goodies/source/filter.vcl/ieps/ieps.cxx b/goodies/source/filter.vcl/ieps/ieps.cxx index f315ee864310..742985904ce8 100644 --- a/goodies/source/filter.vcl/ieps/ieps.cxx +++ b/goodies/source/filter.vcl/ieps/ieps.cxx @@ -164,12 +164,54 @@ static void MakeAsMeta(Graphic &rGraphic) rGraphic = aMtf; } +static oslProcessError runProcessWithPathSearch(const rtl::OUString &rProgName, + rtl_uString* pArgs[], sal_uInt32 nArgs, oslProcess *pProcess, + oslFileHandle *pIn, oslFileHandle *pOut, oslFileHandle *pErr) +{ +#ifdef WNT + /* + * ooo#72096 + * On Window the underlying SearchPath searches in order of... + * The directory from which the application loaded. + * The current directory. + * The Windows system directory. + * The Windows directory. + * The directories that are listed in the PATH environment variable. + * + * Because one of our programs is called "convert" and there is a convert + * in the windows system directory, we want to explicitly search the PATH + * to avoid picking up on that one if ImageMagick's convert preceeds it in + * PATH. + * + */ + rtl::OUString url; + rtl::OUString path(_wgetenv(L"PATH")); + + oslFileError err = osl_searchFileURL(rProgName.pData, path.pData, &url.pData); + if (err != osl_File_E_None) + return osl_Process_E_NotFound; + return osl_executeProcess_WithRedirectedIO(url.pData, + pArgs, nArgs, osl_Process_HIDDEN, + osl_getCurrentSecurity(), 0, 0, 0, pProcess, pIn, pOut, pErr); +#else + return osl_executeProcess_WithRedirectedIO(rProgName.pData, + pArgs, nArgs, osl_Process_SEARCHPATH | osl_Process_HIDDEN, + osl_getCurrentSecurity(), 0, 0, 0, pProcess, pIn, pOut, pErr); +#endif +} + +#if defined(WNT) || defined(OS2) +# define EXESUFFIX ".exe" +#else +# define EXESUFFIX "" +#endif + static bool RenderAsEMF(const sal_uInt8* pBuf, sal_uInt32 nBytesRead, Graphic &rGraphic) { TempFile aTemp; aTemp.EnableKillingFile(); rtl::OUString fileName = - rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("pstoedit")); + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("pstoedit"EXESUFFIX)); rtl::OUString arg1 = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("-f")); rtl::OUString arg2 = @@ -186,10 +228,10 @@ static bool RenderAsEMF(const sal_uInt8* pBuf, sal_uInt32 nBytesRead, Graphic &r oslFileHandle pIn = NULL; oslFileHandle pOut = NULL; oslFileHandle pErr = NULL; - oslProcessError eErr = osl_executeProcess_WithRedirectedIO(fileName.pData, - args, sizeof(args)/sizeof(rtl_uString *), - osl_Process_SEARCHPATH | osl_Process_HIDDEN, - osl_getCurrentSecurity(), 0, 0, 0, &aProcess, &pIn, &pOut, &pErr); + oslProcessError eErr = runProcessWithPathSearch(fileName, + args, sizeof(args)/sizeof(rtl_uString *), + &aProcess, &pIn, &pOut, &pErr); + if (eErr!=osl_Process_E_None) return false; @@ -222,15 +264,15 @@ static bool RenderAsEMF(const sal_uInt8* pBuf, sal_uInt32 nBytesRead, Graphic &r } static bool RenderAsPNGThroughHelper(const sal_uInt8* pBuf, sal_uInt32 nBytesRead, - Graphic &rGraphic, rtl::OUString &rProgName, rtl_uString **pArgs, size_t nArgs) + Graphic &rGraphic, rtl::OUString &rProgName, rtl_uString *pArgs[], size_t nArgs) { oslProcess aProcess; oslFileHandle pIn = NULL; oslFileHandle pOut = NULL; oslFileHandle pErr = NULL; - oslProcessError eErr = osl_executeProcess_WithRedirectedIO(rProgName.pData, - pArgs, nArgs, osl_Process_SEARCHPATH | osl_Process_HIDDEN, - osl_getCurrentSecurity(), 0, 0, 0, &aProcess, &pIn, &pOut, &pErr); + oslProcessError eErr = runProcessWithPathSearch(rProgName, + pArgs, nArgs, + &aProcess, &pIn, &pOut, &pErr); if (eErr!=osl_Process_E_None) return false; @@ -251,7 +293,7 @@ static bool RenderAsPNGThroughHelper(const sal_uInt8* pBuf, sal_uInt32 nBytesRea aMemStm.Seek(0); if ( - eFileErr == osl_File_E_None && + aMemStm.GetSize() && GraphicConverter::Import(aMemStm, rGraphic, CVT_PNG) == ERRCODE_NONE ) { @@ -270,7 +312,7 @@ static bool RenderAsPNGThroughConvert(const sal_uInt8* pBuf, sal_uInt32 nBytesRe Graphic &rGraphic) { rtl::OUString fileName = - rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("convert")); + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("convert"EXESUFFIX)); // density in pixel/inch rtl::OUString arg1 = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("-density")); // since the preview is also used for PDF-Export & printing on non-PS-printers, @@ -293,10 +335,10 @@ static bool RenderAsPNGThroughGS(const sal_uInt8* pBuf, sal_uInt32 nBytesRead, { #ifdef WNT rtl::OUString fileName = - rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("gswin32c")); + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("gswin32c"EXESUFFIX)); #else rtl::OUString fileName = - rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("gs")); + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("gs"EXESUFFIX)); #endif rtl::OUString arg1 = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("-q")); -- cgit From 4e27c4d83c008af5a9d9bc1b6dd8ed9f2dad25b6 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 4 Jan 2010 15:03:09 +0100 Subject: clean up merge in copied file --- vcl/inc/vcl/wintypes.hxx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/vcl/inc/vcl/wintypes.hxx b/vcl/inc/vcl/wintypes.hxx index 52484c80eff4..9e84648fb6a8 100644 --- a/vcl/inc/vcl/wintypes.hxx +++ b/vcl/inc/vcl/wintypes.hxx @@ -32,11 +32,5 @@ #include -// -------------------------------------------- -// - prominent place for ListBox window types - -// -------------------------------------------- - -enum ProminentEntry { PROMINENT_TOP, PROMINENT_MIDDLE }; - #endif // _SV_WINTYPES_HXX -- cgit From 7ef41abc062018776247294bde7e56e2b46489bd Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Mon, 4 Jan 2010 15:08:47 +0100 Subject: fix a merge accident --- vcl/source/gdi/pdfwriter_impl.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/vcl/source/gdi/pdfwriter_impl.cxx b/vcl/source/gdi/pdfwriter_impl.cxx index 3b0d6fd2cb8d..a220f193945a 100644 --- a/vcl/source/gdi/pdfwriter_impl.cxx +++ b/vcl/source/gdi/pdfwriter_impl.cxx @@ -2817,6 +2817,7 @@ sal_Int32 PDFWriterImpl::emitBuiltinFont( const ImplFontData* pFont, sal_Int32 n } std::map< sal_Int32, sal_Int32 > PDFWriterImpl::emitSystemFont( const ImplFontData* pFont, EmbedFont& rEmbed ) +{ std::map< sal_Int32, sal_Int32 > aRet; if( isBuiltinFont( pFont ) ) { -- cgit From a8dc64c99b23c3e7e73aa13bbde8a6f03f14b6e1 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Mon, 4 Jan 2010 15:12:01 +0000 Subject: cmcfixes69: #i106157#: workaround more graphite stl/stlport issues --- vcl/inc/pregraphitestl.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vcl/inc/pregraphitestl.h b/vcl/inc/pregraphitestl.h index 043ae84d0b45..84bede349d4f 100644 --- a/vcl/inc/pregraphitestl.h +++ b/vcl/inc/pregraphitestl.h @@ -12,7 +12,9 @@ # undef _STLP_MAP # define _STLP_DONT_REDEFINE_STD 1 # define _STLP_WHOLE_NATIVE_STD 1 +# pragma GCC visibility push(default) # include _STLP_NATIVE_HEADER(exception_defines.h) +# include _STLP_NATIVE_HEADER(limits) # include _STLP_NATIVE_HEADER(memory) # include _STLP_NATIVE_HEADER(exception) # include _STLP_NATIVE_HEADER(iosfwd) @@ -24,6 +26,7 @@ # include _STLP_NATIVE_HEADER(ostream) # include _STLP_NATIVE_HEADER(istream) # include _STLP_NATIVE_HEADER(iostream) +# pragma GCC visibility pop #endif //sil_std resolves to the std that Graphite was built with namespace sil_std = std; -- cgit From 5ea66a47f68665b5fd16b02188b85f64db2e3866 Mon Sep 17 00:00:00 2001 From: Christian Lippka Date: Tue, 5 Jan 2010 10:42:47 +0100 Subject: fixed compile error on linux --- svtools/source/filter.vcl/wmf/winwmf.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/svtools/source/filter.vcl/wmf/winwmf.cxx b/svtools/source/filter.vcl/wmf/winwmf.cxx index 54629383a4f8..f9ae46e98e12 100644 --- a/svtools/source/filter.vcl/wmf/winwmf.cxx +++ b/svtools/source/filter.vcl/wmf/winwmf.cxx @@ -918,7 +918,7 @@ void WMFReader::ReadRecordParams( USHORT nFunc ) } } } - else if ( nNewMagic == 0x43464D57 && nLen >= 34 && ( nLen + 10 <= nRecSize * 2 )) + else if ( (nNewMagic == static_cast< sal_uInt32 >(0x43464D57)) && (nLen >= 34) && ( (sal_Int32)(nLen + 10) <= (sal_Int32)(nRecSize * 2) )) { sal_uInt32 nComType, nVersion, nFlags, nComRecCount, nCurRecSize, nRemainingSize, nEMFTotalSize; -- cgit From 8a82c9892f39d69d77937f4691c90a079a059bdf Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 5 Jan 2010 11:18:23 +0100 Subject: vcl108: #i107878# reenable accidentally lost environment variable SAL_USE_VCLPLUGIN --- vcl/unx/source/plugadapt/salplug.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vcl/unx/source/plugadapt/salplug.cxx b/vcl/unx/source/plugadapt/salplug.cxx index f1c63b8abee7..08820b2cb7f9 100644 --- a/vcl/unx/source/plugadapt/salplug.cxx +++ b/vcl/unx/source/plugadapt/salplug.cxx @@ -219,8 +219,10 @@ SalInstance *CreateSalInstance() if( !(pUsePlugin && *pUsePlugin) ) pInst = check_headless_plugin(); + else + pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) ); - if( ! pInst && !(pUsePlugin && *pUsePlugin) ) + if( ! pInst ) pInst = autodetect_plugin(); // fallback to gen -- cgit From 33e343aba54517201820c54ad01a9cf410d1d3c3 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Tue, 5 Jan 2010 13:56:08 +0100 Subject: vcl108: #i107875# fix an assertion with debug stdc++ lib (thanks dtardon) --- vcl/inc/vcl/vclevent.hxx | 5 ++++- vcl/source/app/vclevent.cxx | 3 +-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/vcl/inc/vcl/vclevent.hxx b/vcl/inc/vcl/vclevent.hxx index 74971f62c5a6..19f6ed8a98b9 100644 --- a/vcl/inc/vcl/vclevent.hxx +++ b/vcl/inc/vcl/vclevent.hxx @@ -262,7 +262,10 @@ class VCL_DLLPUBLIC VclEventListeners2 : public vcl::DeletionNotifier std::list< Link >::iterator m_aIt; bool m_bWasInvalidated; - ListenerIt() : m_bWasInvalidated( false ) {} + ListenerIt(const std::list::iterator& rIt) + : m_aIt(rIt) + , m_bWasInvalidated( false ) + {} }; std::vector< ListenerIt > m_aIterators; diff --git a/vcl/source/app/vclevent.cxx b/vcl/source/app/vclevent.cxx index 704d68c5bc7f..66c104da59d5 100644 --- a/vcl/source/app/vclevent.cxx +++ b/vcl/source/app/vclevent.cxx @@ -118,9 +118,8 @@ void VclEventListeners2::callListeners( VclSimpleEvent* i_pEvent ) { vcl::DeletionListener aDel( this ); - m_aIterators.push_back( ListenerIt() ); + m_aIterators.push_back(ListenerIt(m_aListeners.begin())); size_t nIndex = m_aIterators.size() - 1; - m_aIterators[ nIndex ].m_aIt = m_aListeners.begin(); while( ! aDel.isDeleted() && m_aIterators[ nIndex ].m_aIt != m_aListeners.end() ) { m_aIterators[ nIndex ].m_aIt->Call( i_pEvent ); -- cgit From d6e84e058f1bbdc4b774ff30e4f41689e0099bd6 Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Tue, 5 Jan 2010 15:50:35 +0100 Subject: whitespace cleanup. --- ucbhelper/inc/ucbhelper/content.hxx | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/ucbhelper/inc/ucbhelper/content.hxx b/ucbhelper/inc/ucbhelper/content.hxx index 03cfa0bc8290..1e8f32107241 100644 --- a/ucbhelper/inc/ucbhelper/content.hxx +++ b/ucbhelper/inc/ucbhelper/content.hxx @@ -106,14 +106,14 @@ class UCBHELPER_DLLPUBLIC Content protected: ::com::sun::star::uno::Any createCursorAny( const ::com::sun::star::uno::Sequence< rtl::OUString >& rPropertyNames, - ResultSetInclude eMode ) + ResultSetInclude eMode ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); ::com::sun::star::uno::Any createCursorAny( const ::com::sun::star::uno::Sequence< sal_Int32 >& rPropertyHandles, - ResultSetInclude eMode ) + ResultSetInclude eMode ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); @@ -148,7 +148,7 @@ public: * errors. */ Content( const ::com::sun::star::uno::Reference< - ::com::sun::star::ucb::XContentIdentifier >& rId, + ::com::sun::star::ucb::XContentIdentifier >& rId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& rEnv ) throw ( ::com::sun::star::ucb::ContentCreationException, @@ -163,7 +163,7 @@ public: * errors. */ Content( const ::com::sun::star::uno::Reference< - ::com::sun::star::ucb::XContent >& rContent, + ::com::sun::star::ucb::XContent >& rContent, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& rEnv ) throw ( ::com::sun::star::ucb::ContentCreationException, @@ -221,7 +221,7 @@ public: */ static sal_Bool create( const ::com::sun::star::uno::Reference< - ::com::sun::star::ucb::XContentIdentifier >& rId, + ::com::sun::star::ucb::XContentIdentifier >& rId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& rEnv, Content& rContent ); @@ -241,7 +241,7 @@ public: */ static sal_Bool create( const ::com::sun::star::uno::Reference< - ::com::sun::star::ucb::XContent >& xContent, + ::com::sun::star::ucb::XContent >& xContent, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& rEnv, Content& rContent ); @@ -501,7 +501,7 @@ public: setPropertyValues( const ::com::sun::star::uno::Sequence< rtl::OUString >& rPropertyNames, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rValues ) + ::com::sun::star::uno::Any >& rValues ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); @@ -539,7 +539,7 @@ public: setPropertyValues( const ::com::sun::star::uno::Sequence< sal_Int32 >& nPropertyHandles, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rValues ) + ::com::sun::star::uno::Any >& rValues ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); @@ -655,8 +655,8 @@ public: ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XDynamicResultSet > createDynamicCursor( const ::com::sun::star::uno::Sequence< rtl::OUString >& rPropertyNames, - ResultSetInclude eMode - = INCLUDE_FOLDERS_AND_DOCUMENTS ) + ResultSetInclude eMode + = INCLUDE_FOLDERS_AND_DOCUMENTS ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); @@ -678,8 +678,8 @@ public: ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XDynamicResultSet > createDynamicCursor( const ::com::sun::star::uno::Sequence< sal_Int32 >& rPropertyHandles, - ResultSetInclude eMode - = INCLUDE_FOLDERS_AND_DOCUMENTS ) + ResultSetInclude eMode + = INCLUDE_FOLDERS_AND_DOCUMENTS ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); @@ -846,9 +846,9 @@ public: sal_Bool insertNewContent( const ::rtl::OUString& rContentType, const ::com::sun::star::uno::Sequence< - rtl::OUString >& rPropertyNames, + rtl::OUString >& rPropertyNames, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rPropertyValues, + ::com::sun::star::uno::Any >& rPropertyValues, Content& rNewContent ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, @@ -880,7 +880,7 @@ public: const ::com::sun::star::uno::Sequence< sal_Int32 >& nPropertyHandles, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rPropertyValues, + ::com::sun::star::uno::Any >& rPropertyValues, Content& rNewContent ) throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, @@ -913,9 +913,9 @@ public: sal_Bool insertNewContent( const ::rtl::OUString& rContentType, const ::com::sun::star::uno::Sequence< - rtl::OUString >& rPropertyNames, + rtl::OUString >& rPropertyNames, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rPropertyValues, + ::com::sun::star::uno::Any >& rPropertyValues, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rStream, Content& rNewContent ) @@ -952,7 +952,7 @@ public: const ::com::sun::star::uno::Sequence< sal_Int32 >& nPropertyHandles, const ::com::sun::star::uno::Sequence< - ::com::sun::star::uno::Any >& rPropertyValues, + ::com::sun::star::uno::Any >& rPropertyValues, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rStream, Content& rNewContent ) -- cgit From caa8fc85e4757f2cc70a54c8190f995d963eac35 Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Tue, 5 Jan 2010 15:57:12 +0100 Subject: whitespace cleanup. --- ucbhelper/source/client/content.cxx | 64 ++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/ucbhelper/source/client/content.cxx b/ucbhelper/source/client/content.cxx index c82a0bc19b77..e3b98ed24d81 100644 --- a/ucbhelper/source/client/content.cxx +++ b/ucbhelper/source/client/content.cxx @@ -149,7 +149,7 @@ void EmptyInputStream::closeInput() //========================================================================= class ContentEventListener_Impl : public cppu::OWeakObject, - public XContentEventListener + public XContentEventListener { Content_Impl& m_rContent; @@ -157,7 +157,7 @@ public: ContentEventListener_Impl( Content_Impl& rContent ) : m_rContent( rContent ) {} - // XInterface + // XInterface XINTERFACE_DECL() // XContentEventListener @@ -184,8 +184,8 @@ friend class ContentEventListener_Impl; mutable rtl::OUString m_aURL; Reference< XMultiServiceFactory > m_xSMgr; Reference< XContent > m_xContent; - Reference< XCommandProcessor > m_xCommandProcessor; - Reference< XCommandEnvironment > m_xEnv; + Reference< XCommandProcessor > m_xCommandProcessor; + Reference< XCommandEnvironment > m_xEnv; Reference< XContentEventListener > m_xContentEventListener; mutable osl::Mutex m_aMutex; sal_Int32 m_nCommandId; @@ -587,7 +587,7 @@ Any Content::getPropertyValue( sal_Int32 nPropertyHandle ) //========================================================================= Any Content::setPropertyValue( const rtl::OUString& rName, - const Any& rValue ) + const Any& rValue ) throw( CommandAbortedException, RuntimeException, Exception ) { Sequence< rtl::OUString > aNames( 1 ); @@ -602,7 +602,7 @@ Any Content::setPropertyValue( const rtl::OUString& rName, //========================================================================= Any Content::setPropertyValue( const sal_Int32 nPropertyHandle, - const Any& rValue ) + const Any& rValue ) throw( CommandAbortedException, RuntimeException, Exception ) { Sequence< sal_Int32 > aHandles( 1 ); @@ -674,8 +674,8 @@ Reference< XRow > Content::getPropertyValuesInterface( rProp.Name = pNames[ n ]; rProp.Handle = -1; // n/a -// rProp.Type = -// rProp.Attributes = ; +// rProp.Type = +// rProp.Attributes = ; } Command aCommand; @@ -707,8 +707,8 @@ Reference< XRow > Content::getPropertyValuesInterface( rProp.Name = rtl::OUString(); // n/a rProp.Handle = pHandles[ n ]; -// rProp.Type = -// rProp.Attributes = ; +// rProp.Type = +// rProp.Attributes = ; } Command aCommand; @@ -726,7 +726,7 @@ Reference< XRow > Content::getPropertyValuesInterface( //========================================================================= Sequence< Any > Content::setPropertyValues( const Sequence< rtl::OUString >& rPropertyNames, - const Sequence< Any >& rValues ) + const Sequence< Any >& rValues ) throw( CommandAbortedException, RuntimeException, Exception ) { if ( rPropertyNames.getLength() != rValues.getLength() ) @@ -756,7 +756,7 @@ Sequence< Any > Content::setPropertyValues( rProp.Name = pNames[ n ]; rProp.Handle = -1; // n/a rProp.Value = pValues[ n ]; -// rProp.State = ; +// rProp.State = ; } Command aCommand; @@ -774,7 +774,7 @@ Sequence< Any > Content::setPropertyValues( //========================================================================= Sequence< Any > Content::setPropertyValues( const Sequence< sal_Int32 >& nPropertyHandles, - const Sequence< Any >& rValues ) + const Sequence< Any >& rValues ) throw( CommandAbortedException, RuntimeException, Exception ) { if ( nPropertyHandles.getLength() != rValues.getLength() ) @@ -804,7 +804,7 @@ Sequence< Any > Content::setPropertyValues( rProp.Name = rtl::OUString(); // n/a rProp.Handle = pHandles[ n ]; rProp.Value = pValues[ n ]; -// rProp.State = ; +// rProp.State = ; } Command aCommand; @@ -934,7 +934,7 @@ Reference< XResultSet > Content::createCursor( OSL_ENSURE( aResult.is(), "Content::createCursor - no cursor!" ); - if ( !aResult.is() ) + if ( !aResult.is() ) { // Former, the open command directly returned a XResultSet. aCursorAny >>= aResult; @@ -964,7 +964,7 @@ Reference< XResultSet > Content::createCursor( OSL_ENSURE( aResult.is(), "Content::createCursor - no cursor!" ); - if ( !aResult.is() ) + if ( !aResult.is() ) { // Former, the open command directly returned a XResultSet. aCursorAny >>= aResult; @@ -1008,7 +1008,7 @@ Reference< XDynamicResultSet > Content::createDynamicCursor( //========================================================================= Reference< XDynamicResultSet > Content::createSortedDynamicCursor( const Sequence< rtl::OUString >& rPropertyNames, - const ::com::sun::star::uno::Sequence< ::com::sun::star::ucb::NumberedSortingInfo >& rSortInfo, + const Sequence< NumberedSortingInfo >& rSortInfo, Reference< XAnyCompareFactory > rAnyCompareFactory, ResultSetInclude eMode ) throw( CommandAbortedException, RuntimeException, Exception ) @@ -1043,7 +1043,7 @@ Reference< XDynamicResultSet > Content::createSortedDynamicCursor( //========================================================================= Reference< XDynamicResultSet > Content::createSortedDynamicCursor( const Sequence< sal_Int32 >& rPropertyHandles, - const ::com::sun::star::uno::Sequence< ::com::sun::star::ucb::NumberedSortingInfo >& rSortInfo, + const Sequence< NumberedSortingInfo >& rSortInfo, Reference< XAnyCompareFactory > rAnyCompareFactory, ResultSetInclude eMode ) throw( CommandAbortedException, RuntimeException, Exception ) @@ -1078,7 +1078,7 @@ Reference< XDynamicResultSet > Content::createSortedDynamicCursor( //========================================================================= Reference< XResultSet > Content::createSortedCursor( const Sequence< rtl::OUString >& rPropertyNames, - const ::com::sun::star::uno::Sequence< ::com::sun::star::ucb::NumberedSortingInfo >& rSortInfo, + const Sequence< NumberedSortingInfo >& rSortInfo, Reference< XAnyCompareFactory > rAnyCompareFactory, ResultSetInclude eMode ) throw( CommandAbortedException, RuntimeException, Exception ) @@ -1132,7 +1132,7 @@ Reference< XResultSet > Content::createSortedCursor( //========================================================================= Reference< XResultSet > Content::createSortedCursor( const Sequence< sal_Int32 >& rPropertyHandles, - const ::com::sun::star::uno::Sequence< ::com::sun::star::ucb::NumberedSortingInfo >& rSortInfo, + const Sequence< NumberedSortingInfo >& rSortInfo, Reference< XAnyCompareFactory > rAnyCompareFactory, ResultSetInclude eMode ) throw( CommandAbortedException, RuntimeException, Exception ) @@ -1331,7 +1331,7 @@ sal_Bool Content::openStream( const Reference< XOutputStream >& rStream ) //========================================================================= void Content::writeStream( const Reference< XInputStream >& rStream, - sal_Bool bReplaceExisting ) + sal_Bool bReplaceExisting ) throw( CommandAbortedException, RuntimeException, Exception ) { InsertCommandArgument aArg; @@ -1352,8 +1352,8 @@ void Content::writeStream( const Reference< XInputStream >& rStream, sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, const Sequence< rtl::OUString >& rPropertyNames, - const Sequence< Any >& rPropertyValues, - Content& rNewContent ) + const Sequence< Any >& rPropertyValues, + Content& rNewContent ) throw( CommandAbortedException, RuntimeException, Exception ) { return insertNewContent( rContentType, @@ -1367,8 +1367,8 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, const Sequence< sal_Int32 >& nPropertyHandles, - const Sequence< Any >& rPropertyValues, - Content& rNewContent ) + const Sequence< Any >& rPropertyValues, + Content& rNewContent ) throw( CommandAbortedException, RuntimeException, Exception ) { return insertNewContent( rContentType, @@ -1382,9 +1382,9 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, const Sequence< rtl::OUString >& rPropertyNames, - const Sequence< Any >& rPropertyValues, + const Sequence< Any >& rPropertyValues, const Reference< XInputStream >& rData, - Content& rNewContent ) + Content& rNewContent ) throw( CommandAbortedException, RuntimeException, Exception ) { if ( rContentType.getLength() == 0 ) @@ -1423,9 +1423,9 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, const Sequence< sal_Int32 >& nPropertyHandles, - const Sequence< Any >& rPropertyValues, + const Sequence< Any >& rPropertyValues, const Reference< XInputStream >& rData, - Content& rNewContent ) + Content& rNewContent ) throw( CommandAbortedException, RuntimeException, Exception ) { if ( rContentType.getLength() == 0 ) @@ -1464,7 +1464,7 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, sal_Bool Content::transferContent( const Content& rSourceContent, InsertOperation eOperation, const rtl::OUString & rTitle, - const sal_Int32 nNameClashAction ) + const sal_Int32 nNameClashAction ) throw( CommandAbortedException, RuntimeException, Exception ) { ContentBroker* pBroker = ContentBroker::get(); @@ -1578,8 +1578,8 @@ sal_Bool Content::isDocument() //========================================================================= Content_Impl::Content_Impl( const Reference< XMultiServiceFactory >& rSMgr, - const Reference< XContent >& rContent, - const Reference< XCommandEnvironment >& rEnv ) + const Reference< XContent >& rContent, + const Reference< XCommandEnvironment >& rEnv ) : m_xSMgr( rSMgr ), m_xContent( rContent ), m_xEnv( rEnv ), -- cgit -- cgit From 4d4395e6290e3057ff67e519bbd583ee30460b51 Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Tue, 5 Jan 2010 17:22:07 +0100 Subject: whitespace cleanup. --- ucbhelper/workben/ucbexplorer/ucbexplorer.cxx | 56 +++++++++++++-------------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx b/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx index 51490ed40296..276476d9e21f 100644 --- a/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx +++ b/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx @@ -38,9 +38,7 @@ #include #include #include -#ifndef _COM_SUN_STAR_UCB_XCOMMMANDINFO_HPP_ #include -#endif #include #include #include @@ -57,9 +55,7 @@ #include #include #include -#ifndef _SV_BUTTON_HXX #include -#endif #include #include #include @@ -89,8 +85,8 @@ class TestDataSink : public cppu::OWeakObject, public XActiveDataSink uno::Reference< XInputStream > m_xStream; public: -// TestDataSink() {} -// virtual ~TestDataSink(); +// TestDataSink() {} +// virtual ~TestDataSink(); // XInterface methods virtual Any SAL_CALL queryInterface( const Type & rType ) @@ -230,7 +226,7 @@ Any SAL_CALL TestDataSink::queryInterface( const Type & rType ) { Any aRet = cppu::queryInterface( rType, - static_cast< XActiveDataSink * >( this ) ); + static_cast< XActiveDataSink * >( this ) ); return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ); } @@ -457,7 +453,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, if ( aSourceURL.getLength() == 0 ) { DBG_ERROR( "UcbExplorerListBoxEntry::createNewContent - " - "No document data URL!" ); + "No document data URL!" ); return FALSE; } @@ -469,7 +465,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, if ( pBroker ) { uno::Reference< XInteractionHandler > xInteractionHandler( - pBroker->getServiceManager()->createInstance( + pBroker->getServiceManager()->createInstance( OUString::createFromAscii( "com.sun.star.task.InteractionHandler" ) ), UNO_QUERY ); @@ -478,7 +474,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, /* = new ProgressHandler( *pBroker ) */ ; xEnv = new ::ucb::CommandEnvironment( xInteractionHandler, - xProgressHandler ); + xProgressHandler ); } ::ucb::Content aSourceContent( aSourceURL, xEnv ); @@ -491,7 +487,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, catch ( ContentCreationException const & ) { DBG_ERROR( "UcbExplorerListBoxEntry::createNewContent - " - "No content for document data!" ); + "No content for document data!" ); return FALSE; } catch ( CommandAbortedException const & ) @@ -516,7 +512,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, // Create new content. - ULONG n = Application::ReleaseSolarMutex(); + ULONG n = Application::ReleaseSolarMutex(); BOOL bRet = sal_False; try @@ -580,13 +576,13 @@ void UcbExplorerTreeListBox::RequestingChilds( SvLBoxEntry* pParent ) { case UcbExplorerListBoxEntry::FOLDER: { - ULONG n = Application::ReleaseSolarMutex(); + ULONG n = Application::ReleaseSolarMutex(); try { Sequence< OUString > aPropertyNames( 0 ); -// OUString* pNames = aPropertyNames.getArray(); -// pNames[ 0 ] = OUString::createFromAscii( "Title" ); +// OUString* pNames = aPropertyNames.getArray(); +// pNames[ 0 ] = OUString::createFromAscii( "Title" ); uno::Reference< XResultSet > xResultSet = pEntry->m_aContent.createCursor( @@ -651,9 +647,9 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) PopupMenu* pMenu = new PopupMenu( ResId( MENU_POPUP ) ); PopupMenu* pNewMenu = 0; -// pMenu->SetSelectHdl( LINK( this, -// SfxCommonTemplateDialog_Impl, -// MenuSelectHdl ) ); +// pMenu->SetSelectHdl( LINK( this, +// SfxCommonTemplateDialog_Impl, +// MenuSelectHdl ) ); ////////////////////////////////////////////////////////////// // Configure "New" @@ -721,7 +717,7 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) { pMenu->EnableItem( MENU_DELETE, pEntry->m_aContent - .getCommands()->hasCommandByName( + .getCommands()->hasCommandByName( OUString::createFromAscii( "delete" ) ) ); } @@ -743,8 +739,8 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) USHORT nSelected = pMenu->Execute( this, rPos ); switch ( nSelected ) { -// case MENU_NEW: -// break; +// case MENU_NEW: +// break; case MENU_RENAME: { @@ -884,7 +880,7 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) { // New-menu entry selected. - ::ucb::Content aNewContent; + ::ucb::Content aNewContent; if ( pEntry->createNewContent( aInfo.getConstArray()[ nSelected - 20001 ], aNewContent ) ) @@ -910,8 +906,8 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) //========================================================================= UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( - ::ucb::Content& rContent, - SvLBoxEntry* pParent ) + ::ucb::Content& rContent, + SvLBoxEntry* pParent ) { try { @@ -921,7 +917,7 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( if ( !aTitle.getLength() ) aTitle = OUString::createFromAscii( "/" ); - UcbExplorerListBoxEntry* pEntry = 0; + UcbExplorerListBoxEntry* pEntry = 0; if ( rContent.isFolder() ) { @@ -995,8 +991,8 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( //========================================================================= UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( - const String& rURL, - SvLBoxEntry* pParent ) + const String& rURL, + SvLBoxEntry* pParent ) { try { @@ -1006,7 +1002,7 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( if ( pBroker ) { uno::Reference< XInteractionHandler > xInteractionHandler( - pBroker->getServiceManager()->createInstance( + pBroker->getServiceManager()->createInstance( OUString::createFromAscii( "com.sun.star.task.InteractionHandler" ) ), UNO_QUERY ); @@ -1015,7 +1011,7 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( /* = new ProgressHandler( *pBroker ) */ ; xEnv = new ::ucb::CommandEnvironment( xInteractionHandler, - xProgressHandler ); + xProgressHandler ); } ::ucb::Content aContent( rURL, xEnv ); @@ -1105,7 +1101,7 @@ void MyApp::Main() comphelper::setProcessServiceFactory( xFac ); - unO::Reference< XComponent > xComponent( xFac, UNO_QUERY ); + unO::Reference< XComponent > xComponent( xFac, UNO_QUERY ); ////////////////////////////////////////////////////////////////////// // Create UCB. -- cgit From f8a276a66211d0fe08e1c9ad5204d5fe0a0fc038 Mon Sep 17 00:00:00 2001 From: Philipp Lohmann Date: Tue, 5 Jan 2010 17:11:23 +0000 Subject: #i108068# always release solar mutex before calling into UNO --- vcl/source/helper/xconnection.cxx | 36 ++++++++++++++++++++++++++++++++---- vcl/unx/source/app/saldisp.cxx | 6 +----- vcl/unx/source/plugadapt/salplug.cxx | 4 +++- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/vcl/source/helper/xconnection.cxx b/vcl/source/helper/xconnection.cxx index 477ff5fb9902..489e3cf9340e 100644 --- a/vcl/source/helper/xconnection.cxx +++ b/vcl/source/helper/xconnection.cxx @@ -30,10 +30,31 @@ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" -#include -#include -#include -#include + +#include "svsys.h" +#include "vcl/xconnection.hxx" +#include "vcl/svdata.hxx" +#include "vcl/salinst.hxx" +#include "vcl/svapp.hxx" + +namespace vcl +{ + class SolarMutexReleaser + { + ULONG mnReleased; + public: + SolarMutexReleaser() + { + mnReleased = Application::ReleaseSolarMutex(); + } + + ~SolarMutexReleaser() + { + if( mnReleased ) + Application::AcquireSolarMutex( mnReleased ); + } + }; +} using namespace rtl; using namespace osl; @@ -41,6 +62,7 @@ using namespace vcl; using namespace com::sun::star::uno; using namespace com::sun::star::awt; + DisplayConnection::DisplayConnection() { ImplSVData* pSVData = ImplGetSVData(); @@ -108,6 +130,8 @@ Any SAL_CALL DisplayConnection::getIdentifier() throw() void DisplayConnection::dispatchDowningEvent() { + SolarMutexReleaser aRel; + MutexGuard aGuard( m_aMutex ); Any aEvent; std::list< Reference< XEventHandler > > aLocalList( m_aHandlers ); @@ -117,6 +141,8 @@ void DisplayConnection::dispatchDowningEvent() bool DisplayConnection::dispatchEvent( void* pThis, void* pData, int nBytes ) { + SolarMutexReleaser aRel; + DisplayConnection* This = (DisplayConnection*)pThis; MutexGuard aGuard( This->m_aMutex ); @@ -131,6 +157,8 @@ bool DisplayConnection::dispatchEvent( void* pThis, void* pData, int nBytes ) bool DisplayConnection::dispatchErrorEvent( void* pThis, void* pData, int nBytes ) { + SolarMutexReleaser aRel; + DisplayConnection* This = (DisplayConnection*)pThis; MutexGuard aGuard( This->m_aMutex ); diff --git a/vcl/unx/source/app/saldisp.cxx b/vcl/unx/source/app/saldisp.cxx index cfd568ac9b6c..558ae3714358 100644 --- a/vcl/unx/source/app/saldisp.cxx +++ b/vcl/unx/source/app/saldisp.cxx @@ -2304,11 +2304,7 @@ long SalX11Display::Dispatch( XEvent *pEvent ) return 0; SalInstance* pInstance = GetSalData()->m_pInstance; - if( pInstance->GetEventCallback() ) - { - YieldMutexReleaser aReleaser; - pInstance->CallEventCallback( pEvent, sizeof( XEvent ) ); - } + pInstance->CallEventCallback( pEvent, sizeof( XEvent ) ); switch( pEvent->type ) { diff --git a/vcl/unx/source/plugadapt/salplug.cxx b/vcl/unx/source/plugadapt/salplug.cxx index f1c63b8abee7..08820b2cb7f9 100644 --- a/vcl/unx/source/plugadapt/salplug.cxx +++ b/vcl/unx/source/plugadapt/salplug.cxx @@ -219,8 +219,10 @@ SalInstance *CreateSalInstance() if( !(pUsePlugin && *pUsePlugin) ) pInst = check_headless_plugin(); + else + pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) ); - if( ! pInst && !(pUsePlugin && *pUsePlugin) ) + if( ! pInst ) pInst = autodetect_plugin(); // fallback to gen -- cgit From c062cc0b89a8832c7ad507e79fe56de10b09f659 Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Tue, 5 Jan 2010 18:17:29 +0100 Subject: whitespace cleanup. --- ucbhelper/workben/ucbexplorer/ucbexplorer.src | 9 --------- 1 file changed, 9 deletions(-) diff --git a/ucbhelper/workben/ucbexplorer/ucbexplorer.src b/ucbhelper/workben/ucbexplorer/ucbexplorer.src index 14d4b8ee8770..355732741d6d 100644 --- a/ucbhelper/workben/ucbexplorer/ucbexplorer.src +++ b/ucbhelper/workben/ucbexplorer/ucbexplorer.src @@ -27,15 +27,6 @@ * for a copy of the LGPLv3 License. * ************************************************************************/ -//========================================================================= -// -// UCB Explorer ( resources ) -// -// (C) 2000 StarOffice Entwicklungs GmbH, Hamburg, Germany -// -// $Author: rt $ $Date: 2008-04-10 16:20:05 $Revision$ -// -//========================================================================= #include "ucbexplorer.hrc" -- cgit From a7d20f1e3f23a94ff2e389b815ff35b72843ab9d Mon Sep 17 00:00:00 2001 From: "Frank Schoenheit [fs]" Date: Wed, 6 Jan 2010 08:23:28 +0100 Subject: use proper delete operator --- transex3/source/inireader.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/transex3/source/inireader.cxx b/transex3/source/inireader.cxx index 0985e788452d..1ff34fad8e95 100644 --- a/transex3/source/inireader.cxx +++ b/transex3/source/inireader.cxx @@ -120,7 +120,7 @@ void INIreader::toStlString( const UnicodeString& str , string& stl_str) char* buffer = new char[ str.length()*3 ]; str.extract( 0 , str.length() , buffer ); stl_str = string( buffer ); - delete buffer; + delete[] buffer; } void INIreader::trim( string& str ) -- cgit From 59a8c29ca861dbe23fcc41cb13dfc6a19f088bd4 Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Wed, 6 Jan 2010 10:40:02 +0100 Subject: compiles again, but not yet working. --- ucbhelper/workben/ucbexplorer/ucbexplorer.cxx | 142 ++++++++++++++------------ ucbhelper/workben/ucbexplorer/ucbexplorer.src | 2 + 2 files changed, 77 insertions(+), 67 deletions(-) diff --git a/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx b/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx index 276476d9e21f..9a41c55ccfd8 100644 --- a/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx +++ b/ucbhelper/workben/ucbexplorer/ucbexplorer.cxx @@ -40,8 +40,8 @@ #include #include #include -#include #include +#include #include #include "rtl/ref.hxx" @@ -124,7 +124,8 @@ private: DECL_LINK( NameHdl, Edit * ); public: - StringInputDialog( const String& rTitle, + StringInputDialog( ResMgr& rResMgr, + const String& rTitle, const String& rDefaultText, String* pGroupName = 0 ); String GetValue() const { return m_aNameEdit.GetText(); } @@ -143,15 +144,15 @@ class UcbExplorerListBoxEntry : public SvLBoxEntry enum EntryType { FOLDER, DOCUMENT, LINK }; - ::ucb::Content m_aContent; - EntryType m_eType; + ::ucbhelper::Content m_aContent; + EntryType m_eType; public: UcbExplorerListBoxEntry(); virtual ~UcbExplorerListBoxEntry(); BOOL createNewContent( const ContentInfo& rInfo, - ::ucb::Content& rNewContent ); + ::ucbhelper::Content& rNewContent ); }; //========================================================================= @@ -172,13 +173,13 @@ private: virtual void RequestingChilds( SvLBoxEntry* pParent ); public: - UcbExplorerTreeListBox( Window* pParent, WinBits nWinStyle = 0 ); + UcbExplorerTreeListBox( ResMgr & rResMgr, Window* pParent, WinBits nWinStyle = 0 ); virtual ~UcbExplorerTreeListBox(); virtual void Command( const CommandEvent& rCEvt ); UcbExplorerListBoxEntry* - InsertEntry( ::ucb::Content& rContent, SvLBoxEntry* pParent ); + InsertEntry( ::ucbhelper::Content& rContent, SvLBoxEntry* pParent ); UcbExplorerListBoxEntry* InsertEntry( const String& rURL, SvLBoxEntry* pParent = 0 ); }; @@ -196,7 +197,7 @@ class UcbExplorerWindow : public WorkWindow UcbExplorerTreeListBox m_aTree; public: - UcbExplorerWindow( Window *pParent, WinBits nWinStyle ); + UcbExplorerWindow( ResMgr & rResMgr, Window *pParent, WinBits nWinStyle ); virtual ~UcbExplorerWindow(); virtual void Resize(); @@ -269,16 +270,17 @@ uno::Reference< XInputStream > SAL_CALL TestDataSink::getInputStream() // //========================================================================= -StringInputDialog::StringInputDialog( const String& rTitle, +StringInputDialog::StringInputDialog( ResMgr& rResMgr, + const String& rTitle, const String& rDefaultText, String* pGroupName ) -: ModalDialog( 0, ResId( DLG_STRINGINPUT ) ), - m_aNameText ( this, ResId( FT_STRINGINPUT_DLG_NAME ) ), - m_aNameEdit ( this, ResId( ED_STRINGINPUT_DLG_NAME ) ), - m_aNameGroup( this, ResId( GB_STRINGINPUT_DLG_NAME ) ), - m_aOKBtn ( this, ResId( BT_STRINGINPUT_DLG_OK ) ), - m_aCancelBtn( this, ResId( BT_STRINGINPUT_DLG_CANCEL ) ), - m_aHelpBtn ( this, ResId( BT_STRINGINPUT_DLG_HELP ) ) + : ModalDialog( 0, ResId( DLG_STRINGINPUT, rResMgr ) ), + m_aNameText ( this, ResId( FT_STRINGINPUT_DLG_NAME, rResMgr ) ), + m_aNameEdit ( this, ResId( ED_STRINGINPUT_DLG_NAME, rResMgr ) ), + m_aNameGroup( this, ResId( GB_STRINGINPUT_DLG_NAME, rResMgr ) ), + m_aOKBtn ( this, ResId( BT_STRINGINPUT_DLG_OK, rResMgr ) ), + m_aCancelBtn( this, ResId( BT_STRINGINPUT_DLG_CANCEL, rResMgr ) ), + m_aHelpBtn ( this, ResId( BT_STRINGINPUT_DLG_HELP, rResMgr ) ) { FreeResource(); SetText( rTitle ); @@ -339,7 +341,7 @@ UcbExplorerListBoxEntry::~UcbExplorerListBoxEntry() //========================================================================= BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, - ::ucb::Content& rNewContent ) + ::ucbhelper::Content& rNewContent ) { sal_Int32 nCount = rInfo.Properties.getLength(); Sequence< Any > aPropValues( nCount ); @@ -354,7 +356,10 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, for ( sal_Int32 n = 0; n < nCount; ++n ) { const OUString& rName = pProps[ n ].Name; - StringInputDialog* pDlg = new StringInputDialog( rName, rName ); + + std::auto_ptr< ResMgr > xManager( + ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( ucbexplorer ) ) ); + StringInputDialog* pDlg = new StringInputDialog( *xManager.get(), rName, rName ); USHORT nRet = pDlg->Execute(); if ( nRet == RET_OK ) { @@ -440,7 +445,10 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, // Let the user specify the URL of a content containing the // data to supply to the new content. + std::auto_ptr< ResMgr > xManager( + ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( ucbexplorer ) ) ); StringInputDialog* pDlg = new StringInputDialog( + *xManager.get(), OUString::createFromAscii( "Document Data Source URL" ), OUString() ); @@ -461,7 +469,7 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, { uno::Reference< XCommandEnvironment > xEnv; - ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); + ::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get(); if ( pBroker ) { uno::Reference< XInteractionHandler > xInteractionHandler( @@ -473,15 +481,15 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, uno::Reference< XProgressHandler > xProgressHandler /* = new ProgressHandler( *pBroker ) */ ; - xEnv = new ::ucb::CommandEnvironment( xInteractionHandler, - xProgressHandler ); + xEnv = new ::ucbhelper::CommandEnvironment( xInteractionHandler, + xProgressHandler ); } - ::ucb::Content aSourceContent( aSourceURL, xEnv ); + ::ucbhelper::Content aSourceContent( aSourceURL, xEnv ); // Get source data. rtl::Reference< TestDataSink > xSourceData = new TestDataSink; - aSourceContent.openStream( xSourceData.getBodyPtr() ); + aSourceContent.openStream( xSourceData.get() ); xData = xSourceData->getInputStream(); } catch ( ContentCreationException const & ) @@ -541,13 +549,14 @@ BOOL UcbExplorerListBoxEntry::createNewContent( const ContentInfo& rInfo, // //========================================================================= -UcbExplorerTreeListBox::UcbExplorerTreeListBox( - Window* pParent, WinBits nWinStyle ) +UcbExplorerTreeListBox::UcbExplorerTreeListBox( ResMgr & rResMgr, + Window* pParent, + WinBits nWinStyle ) : SvTreeListBox( pParent, nWinStyle ), - m_aFolderClosed( ResId( BMP_FOLDER_CLOSED ) ), - m_aFolderOpened( ResId( BMP_FOLDER_OPENED ) ), - m_aDocument( ResId( BMP_DOCUMENT ) ), - m_aLink( ResId( BMP_LINK ) ) + m_aFolderClosed( ResId( BMP_FOLDER_CLOSED, rResMgr ) ), + m_aFolderOpened( ResId( BMP_FOLDER_OPENED, rResMgr ) ), + m_aDocument( ResId( BMP_DOCUMENT, rResMgr ) ), + m_aLink( ResId( BMP_LINK, rResMgr ) ) { } @@ -587,7 +596,7 @@ void UcbExplorerTreeListBox::RequestingChilds( SvLBoxEntry* pParent ) uno::Reference< XResultSet > xResultSet = pEntry->m_aContent.createCursor( aPropertyNames, - ::ucb::INCLUDE_FOLDERS_AND_DOCUMENTS ); + ::ucbhelper::INCLUDE_FOLDERS_AND_DOCUMENTS ); uno::Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY ); @@ -644,7 +653,9 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) GetEntry( rPos, TRUE ) ); if ( pEntry ) { - PopupMenu* pMenu = new PopupMenu( ResId( MENU_POPUP ) ); + std::auto_ptr< ResMgr > xManager( + ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( ucbexplorer ) ) ); + PopupMenu* pMenu = new PopupMenu( ResId( MENU_POPUP, *xManager.get() ) ); PopupMenu* pNewMenu = 0; // pMenu->SetSelectHdl( LINK( this, @@ -655,25 +666,19 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) // Configure "New" ////////////////////////////////////////////////////////////// - uno::Reference< XContentCreator > xCreator( - pEntry->m_aContent.get(), UNO_QUERY ); - Sequence< ContentInfo > aInfo; - BOOL bCanCreate = xCreator.is(); - if ( bCanCreate ) - { - aInfo = xCreator->queryCreatableContentsInfo(); - const ContentInfo* pInfo = aInfo.getConstArray(); - sal_Int32 nCount = aInfo.getLength(); - bCanCreate = ( nCount > 0 ); + Sequence< ContentInfo > aInfo + = pEntry->m_aContent.queryCreatableContentsInfo(); + const ContentInfo* pInfo = aInfo.getConstArray(); + sal_Int32 nCount = aInfo.getLength(); + BOOL bCanCreate = ( nCount > 0 ); - pNewMenu = new PopupMenu; - pMenu->SetPopupMenu( MENU_NEW, pNewMenu ); + pNewMenu = new PopupMenu; + pMenu->SetPopupMenu( MENU_NEW, pNewMenu ); - for ( sal_Int32 n = 0; n < nCount; ++n ) - { - const ContentInfo& rInfo = pInfo[ n ]; - pNewMenu->InsertItem( 20000 + n + 1, rInfo.Type ); - } + for ( sal_Int32 n = 0; n < nCount; ++n ) + { + const ContentInfo& rInfo = pInfo[ n ]; + pNewMenu->InsertItem( 20000 + n + 1, rInfo.Type ); } pMenu->EnableItem( MENU_NEW, bCanCreate ); @@ -763,8 +768,11 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) { } + std::auto_ptr< ResMgr > xManager( + ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( ucbexplorer ) ) ); StringInputDialog* pDlg = new StringInputDialog( + *xManager.get(), OUString::createFromAscii( "Title" ), aNewTitle ); @@ -880,7 +888,7 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) { // New-menu entry selected. - ::ucb::Content aNewContent; + ::ucbhelper::Content aNewContent; if ( pEntry->createNewContent( aInfo.getConstArray()[ nSelected - 20001 ], aNewContent ) ) @@ -906,7 +914,7 @@ void UcbExplorerTreeListBox::Command( const CommandEvent& rCEvt ) //========================================================================= UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( - ::ucb::Content& rContent, + ::ucbhelper::Content& rContent, SvLBoxEntry* pParent ) { try @@ -998,7 +1006,7 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( { uno::Reference< XCommandEnvironment > xEnv; - ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); + ::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get(); if ( pBroker ) { uno::Reference< XInteractionHandler > xInteractionHandler( @@ -1010,11 +1018,11 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( uno::Reference< XProgressHandler > xProgressHandler /* = new ProgressHandler( *pBroker ) */ ; - xEnv = new ::ucb::CommandEnvironment( xInteractionHandler, - xProgressHandler ); + xEnv = new ::ucbhelper::CommandEnvironment( xInteractionHandler, + xProgressHandler ); } - ::ucb::Content aContent( rURL, xEnv ); + ::ucbhelper::Content aContent( rURL, xEnv ); return InsertEntry( aContent, pParent ); } catch ( ContentCreationException const & ) @@ -1030,9 +1038,9 @@ UcbExplorerListBoxEntry* UcbExplorerTreeListBox::InsertEntry( // //========================================================================= -UcbExplorerWindow::UcbExplorerWindow( Window *pParent, WinBits nWinStyle ) +UcbExplorerWindow::UcbExplorerWindow( ResMgr & rResMgr, Window *pParent, WinBits nWinStyle ) : WorkWindow( pParent, nWinStyle ), - m_aTree( this, WB_HSCROLL ) + m_aTree( rResMgr, this, WB_HSCROLL ) { Font aTreeFont( m_aTree.GetFont() ); aTreeFont.SetName( String( RTL_CONSTASCII_USTRINGPARAM("Courier") ) ); @@ -1101,7 +1109,7 @@ void MyApp::Main() comphelper::setProcessServiceFactory( xFac ); - unO::Reference< XComponent > xComponent( xFac, UNO_QUERY ); + uno::Reference< XComponent > xComponent( xFac, UNO_QUERY ); ////////////////////////////////////////////////////////////////////// // Create UCB. @@ -1112,16 +1120,16 @@ void MyApp::Main() Sequence< Any > aArgs( 2 ); aArgs[ 0 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY1_LOCAL ); aArgs[ 1 ] <<= OUString::createFromAscii( UCB_CONFIGURATION_KEY2_OFFICE ); - sal_Bool bSuccess = ::ucb::ContentBroker::initialize( xFac, aArgs ); + sal_Bool bSuccess = ::ucbhelper::ContentBroker::initialize( xFac, aArgs ); #else // Init UCB (Use provided configuration data) - ::ucb::ContentProviderDataList aProviders; + ::ucbhelper::ContentProviderDataList aProviders; aProviders.push_back( - ::ucb::ContentProviderData( + ::ucbhelper::ContentProviderData( OUString::createFromAscii( "com.sun.star.ucb.FileContentProvider" ), OUString::createFromAscii( "file" ), OUString() ) ); - sal_Bool bSuccess = ::ucb::ContentBroker::initialize( xFac, aProviders ); + sal_Bool bSuccess = ::ucbhelper::ContentBroker::initialize( xFac, aProviders ); #endif if ( !bSuccess ) @@ -1134,12 +1142,12 @@ void MyApp::Main() // Create/init/show app window. ////////////////////////////////////////////////////////////////////// - ResMgr* pMgr = ResMgr::CreateResMgr( CREATEVERSIONRESMGR( ucbexplorer ) ); - Resource::SetResManager( pMgr ); + std::auto_ptr< ResMgr > xManager( + ResMgr::CreateResMgr( CREATEVERSIONRESMGR_NAME( ucbexplorer ) ) ); - UcbExplorerWindow aAppWin( 0, WB_APP | WB_STDWORK ); + UcbExplorerWindow aAppWin( *xManager.get(), 0, WB_APP | WB_STDWORK ); - MenuBar aMBMain( ResId( MENU_MAIN ) ); + MenuBar aMBMain( ResId( MENU_MAIN, *xManager.get() ) ); // Check for command line params #if 0 @@ -1154,7 +1162,7 @@ void MyApp::Main() aRootURL = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "vnd.sun.star.hier:/" ) ); - String aTitle( ResId( TEXT_TITLEBAR ) ); + String aTitle( ResId( TEXT_TITLEBAR, *xManager.get() ) ); aTitle.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " - " ) ); aTitle += aRootURL; @@ -1179,7 +1187,7 @@ void MyApp::Main() // m_aTree holds UCB contents! aAppWin.m_aTree.Clear(); - ::ucb::ContentBroker::deinitialize(); + ::ucbhelper::ContentBroker::deinitialize(); if ( xComponent.is() ) xComponent->dispose(); diff --git a/ucbhelper/workben/ucbexplorer/ucbexplorer.src b/ucbhelper/workben/ucbexplorer/ucbexplorer.src index 355732741d6d..1449897341d5 100644 --- a/ucbhelper/workben/ucbexplorer/ucbexplorer.src +++ b/ucbhelper/workben/ucbexplorer/ucbexplorer.src @@ -82,6 +82,7 @@ Menu MENU_POPUP }; }; +/* Bitmap BMP_FOLDER_CLOSED { File = "bmp/fldclose.bmp" ; @@ -98,6 +99,7 @@ Bitmap BMP_LINK { File = "bmp/link.bmp" ; }; +*/ ModalDialog DLG_STRINGINPUT { -- cgit From cdb860118873e199e1f011d9a328a38d2e14d34c Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Wed, 6 Jan 2010 10:48:26 +0100 Subject: whitespace cleanup. --- sot/source/sdstor/ucbstorage.cxx | 52 +++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/sot/source/sdstor/ucbstorage.cxx b/sot/source/sdstor/ucbstorage.cxx index d7e797c681f3..e671012fc560 100644 --- a/sot/source/sdstor/ucbstorage.cxx +++ b/sot/source/sdstor/ucbstorage.cxx @@ -43,9 +43,7 @@ #include #include #include -#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HDL_ #include -#endif #include #include #include @@ -55,9 +53,7 @@ #include #include #include -#ifndef _COM_SUN_STAR_UCB_INTERACTIVEIODEXCEPTION_HPP_ #include -#endif #include #include @@ -113,11 +109,11 @@ public: virtual void SAL_CALL seek( sal_Int64 _nLocation ) throw ( IllegalArgumentException, IOException, RuntimeException); virtual sal_Int64 SAL_CALL getPosition( ) throw ( IOException, RuntimeException); virtual sal_Int64 SAL_CALL getLength( ) throw ( IOException, RuntimeException); - virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead) throw( NotConnectedException, BufferSizeExceededException, RuntimeException ); - virtual sal_Int32 SAL_CALL readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( NotConnectedException, BufferSizeExceededException, RuntimeException ); - virtual void SAL_CALL skipBytes(sal_Int32 nBytesToSkip) throw( NotConnectedException, BufferSizeExceededException, RuntimeException); - virtual sal_Int32 SAL_CALL available() throw( NotConnectedException, RuntimeException ); - virtual void SAL_CALL closeInput() throw( NotConnectedException, RuntimeException ); + virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead) throw( NotConnectedException, BufferSizeExceededException, RuntimeException ); + virtual sal_Int32 SAL_CALL readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( NotConnectedException, BufferSizeExceededException, RuntimeException ); + virtual void SAL_CALL skipBytes(sal_Int32 nBytesToSkip) throw( NotConnectedException, BufferSizeExceededException, RuntimeException); + virtual sal_Int32 SAL_CALL available() throw( NotConnectedException, RuntimeException ); + virtual void SAL_CALL closeInput() throw( NotConnectedException, RuntimeException ); protected: void checkConnected(); @@ -540,7 +536,7 @@ public: // this means that the root storage does an autocommit when its external // reference is destroyed BOOL m_bIsRoot; // marks this storage as root storages that manages all oommits and reverts - BOOL m_bDirty; // ??? + BOOL m_bDirty; // ??? BOOL m_bIsLinked; BOOL m_bListCreated; ULONG m_nFormat; @@ -575,12 +571,12 @@ public: ReadContent(); if ( m_nMode & STREAM_WRITE ) { - m_nError = nError; - if ( m_pAntiImpl ) - { - m_pAntiImpl->ResetError(); - m_pAntiImpl->SetError( nError ); - } + m_nError = nError; + if ( m_pAntiImpl ) + { + m_pAntiImpl->ResetError(); + m_pAntiImpl->SetError( nError ); + } } return m_aChildrenList; @@ -867,7 +863,7 @@ BOOL UCBStorageStream_Impl::Init() // usually means that stream could not be opened } - if( m_rSource.is() ) + if( m_rSource.is() ) { m_pStream->Seek( STREAM_SEEK_TO_END ); @@ -894,7 +890,7 @@ BOOL UCBStorageStream_Impl::Init() { // if the new file is edited than no source exist m_bSourceRead = FALSE; - //SetError( SVSTREAM_CANNOT_MAKE ); + //SetError( SVSTREAM_CANNOT_MAKE ); } } @@ -1107,7 +1103,7 @@ ULONG UCBStorageStream_Impl::SeekPos( ULONG nPos ) else { // the temp stream pointer points to the end now - aResult = m_pStream->Tell(); + aResult = m_pStream->Tell(); if( aResult < nPos ) { @@ -1886,7 +1882,7 @@ void UCBStorage_Impl::Init() { if ( !pStream->GetError() ) { - ::utl::OInputStreamWrapper* pHelper = new ::utl::OInputStreamWrapper( *pStream ); + ::utl::OInputStreamWrapper* pHelper = new ::utl::OInputStreamWrapper( *pStream ); com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > xInputStream( pHelper ); // create a manifest reader object that will read in the manifest from the stream @@ -2042,8 +2038,8 @@ void UCBStorage_Impl::ReadContent() if ( m_bRepairPackage ) { xComEnv = new ::ucbhelper::CommandEnvironment( Reference< ::com::sun::star::task::XInteractionHandler >(), - m_xProgressHandler ); - aName += String( RTL_CONSTASCII_USTRINGPARAM( "?repairpackage" ) ); + m_xProgressHandler ); + aName += String( RTL_CONSTASCII_USTRINGPARAM( "?repairpackage" ) ); } ::ucbhelper::Content aContent( aName, xComEnv ); @@ -2639,7 +2635,7 @@ BOOL UCBStorage_Impl::Revert() } else if ( pElement->m_xStorage.Is() ) { - pElement->m_xStorage->m_bCommited = sal_False; + pElement->m_xStorage->m_bCommited = sal_False; pElement->m_xStorage->Revert(); } @@ -2655,7 +2651,7 @@ BOOL UCBStorage_Impl::Revert() const String& UCBStorage::GetName() const { - return pImp->m_aName; // pImp->m_aURL ?! + return pImp->m_aName; // pImp->m_aURL ?! } BOOL UCBStorage::IsRoot() const @@ -2893,7 +2889,7 @@ BOOL UCBStorage::CopyTo( const String& rElemName, BaseStorage* pDest, const Stri else { // for copying no optimization is usefull, because in every case the stream data must be copied - UCBStorageElement_Impl* pElement = FindElement_Impl( rElemName ); + UCBStorageElement_Impl* pElement = FindElement_Impl( rElemName ); if ( pElement ) return CopyStorageElement_Impl( *pElement, pDest, rNew ); else @@ -3256,10 +3252,10 @@ BOOL UCBStorage::MoveTo( const String& rEleName, BaseStorage* pNewSt, const Stri { // because the element is moved, not copied, a special optimization is possible : // first copy the UCBStorageElement; flag old element as "Removed" and new as "Inserted", - // clear original name/type of the new element - // if moved element is open: copy content, but change absolute URL ( and those of all children of the element! ), + // clear original name/type of the new element + // if moved element is open: copy content, but change absolute URL ( and those of all children of the element! ), // clear original name/type of new content, keep the old original stream/storage, but forget its working streams, - // close original UCBContent and original stream, only the TempFile and its stream may remain unchanged, but now + // close original UCBContent and original stream, only the TempFile and its stream may remain unchanged, but now // belong to the new content // if original and editable stream are identical ( readonly element ), it has to be copied to the editable // stream of the destination object -- cgit From 31a763ce50ce977168ba7806077465130c89b26a Mon Sep 17 00:00:00 2001 From: Kai Sommerfeld Date: Wed, 6 Jan 2010 16:46:36 +0100 Subject: #i61429# - Adapted UCB clients to deprecated XContentCreator interface. --- sot/source/sdstor/ucbstorage.cxx | 7 +-- ucbhelper/inc/ucbhelper/content.hxx | 67 +++++++++++++------- ucbhelper/source/client/content.cxx | 107 +++++++++++++++++++++++++------- unotools/source/ucbhelper/ucbhelper.cxx | 16 +---- 4 files changed, 133 insertions(+), 64 deletions(-) diff --git a/sot/source/sdstor/ucbstorage.cxx b/sot/source/sdstor/ucbstorage.cxx index e671012fc560..274f7d4a4c1a 100644 --- a/sot/source/sdstor/ucbstorage.cxx +++ b/sot/source/sdstor/ucbstorage.cxx @@ -48,7 +48,7 @@ #include #include #include -#include +#include #include #include #include @@ -2277,13 +2277,10 @@ BOOL UCBStorage_Impl::Insert( ::ucbhelper::Content *pContent ) // a new substorage is inserted into a UCBStorage ( given by the parameter pContent ) // it must be inserted with a title and a type BOOL bRet = FALSE; - Reference< XContentCreator > xCreator = Reference< XContentCreator >( pContent->get(), UNO_QUERY ); - if ( !xCreator.is() ) - return sal_False; try { - Sequence< ContentInfo > aInfo = xCreator->queryCreatableContentsInfo(); + Sequence< ContentInfo > aInfo = pContent->queryCreatableContentsInfo(); sal_Int32 nCount = aInfo.getLength(); if ( nCount == 0 ) return sal_False; diff --git a/ucbhelper/inc/ucbhelper/content.hxx b/ucbhelper/inc/ucbhelper/content.hxx index 1e8f32107241..fde86609e850 100644 --- a/ucbhelper/inc/ucbhelper/content.hxx +++ b/ucbhelper/inc/ucbhelper/content.hxx @@ -60,6 +60,7 @@ namespace com { namespace sun { namespace star { namespace ucb { class XContentIdentifier; class XDynamicResultSet; class XAnyCompareFactory; + struct ContentInfo; struct NumberedSortingInfo; } } } } @@ -70,7 +71,7 @@ namespace ucbhelper /** * These are the possible values for the parameter eMode of method - * ucb::Content::createCursor. + * ucbhelper::Content::createCursor. */ enum ResultSetInclude { @@ -81,7 +82,7 @@ enum ResultSetInclude /** * These are the possible values for the parameter eOperation of method - * ucb::Content::insertNewContent. + * ucbhelper::Content::insertNewContent. */ enum InsertOperation { @@ -821,16 +822,31 @@ public: throw( ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException, ::com::sun::star::uno::Exception ); + + /** + * This method returns the different types of contents this content + * can create. + * + * @return the content types or an empty sequence if no contents can be + * created by this content. + */ + ::com::sun::star::uno::Sequence< ::com::sun::star::ucb::ContentInfo > + queryCreatableContentsInfo() + throw( ::com::sun::star::ucb::CommandAbortedException, + ::com::sun::star::uno::RuntimeException, + ::com::sun::star::uno::Exception ); + /** * This method creates, initializes and inserts ( commits ) a new content * (i.e. it could be used to create a new file system folder). - * Internally this method does a XContentCreator::createNewContent(...)- - * XCommandProcessor::execute( "setPropertyValues", ... )- - * XCommandProcessor::execute( "insert", ... ) calling sequence. + * Internally this method does a + * XCommandProcessor::execute( "createNewContent", ... ); + * XCommandProcessor::execute( "setPropertyValues", ... ); + * XCommandProcessor::execute( "insert", ... ); calling sequence. * * @param rContentType is the type for the new UCB content. Each content - * provider implementation may introduce own types for its contnt - * objects. + * provider implementation may introduce own types for its content + * objects (See queryCreatableContentsInfo()). * @param rPropertyNames is a sequence of names of properties for that * values are to set at the new content before it will be inserted * ( commited ). @@ -856,13 +872,14 @@ public: /** * This method creates, initializes and inserts ( commits ) a new content * (i.e. it could be used to create a new file system folder). - * Internally this method does a XContentCreator::createNewContent(...)- - * XCommandProcessor::execute( "setPropertyValues", ... )- - * XCommandProcessor::execute( "insert", ... ) calling sequence. + * Internally this method does a + * XCommandProcessor::execute( "createNewContent", ... ); + * XCommandProcessor::execute( "setPropertyValues", ... ); + * XCommandProcessor::execute( "insert", ... ); calling sequence. * * @param rContentType is the type for the new UCB content. Each content - * provider implementation may introduce own types for its contnt - * objects. + * provider implementation may introduce own types for its content + * objects (See queryCreatableContentsInfo()). * @param nPropertyHandes is a sequence of handles of properties for that * values are to set at the new content before it will be inserted * ( commited ). @@ -888,14 +905,15 @@ public: /** * This method creates, initializes and inserts (commits) a new content * inside this (the target folder) content. For example, it can be used to - * create a new file system folder. - * Internally this method does a XContentCreator::createNewContent(...)- - * XCommandProcessor::execute( "setPropertyValues", ... )- - * XCommandProcessor::execute( "insert", ... ) calling sequence. + * create a new file system file. + * Internally this method does a + * XCommandProcessor::execute( "createNewContent", ... ); + * XCommandProcessor::execute( "setPropertyValues", ... ); + * XCommandProcessor::execute( "insert", ... ); calling sequence. * * @param rContentType is the type for the new UCB content. Each content - * provider implementation may introduce own types for its contnt - * objects. + * provider implementation may introduce own types for its content + * objects (See queryCreatableContentsInfo()). * @param rPropertyNames is a sequence of names of properties for that * values are to set at the new content before it will be inserted * ( commited ). @@ -925,14 +943,15 @@ public: /** * This method creates, initializes and inserts (commits) a new content * inside this (the target folder) content. For example, it can be used to - * create a new file system folder. - * Internally this method does a XContentCreator::createNewContent(...)- - * XCommandProcessor::execute( "setPropertyValues", ... )- - * XCommandProcessor::execute( "insert", ... ) calling sequence. + * create a new file system file. + * Internally this method does a + * XCommandProcessor::execute( "createNewContent", ... ); + * XCommandProcessor::execute( "setPropertyValues", ... ); + * XCommandProcessor::execute( "insert", ... ); calling sequence. * * @param rContentType is the type for the new UCB content. Each content - * provider implementation may introduce own types for its contnt - * objects. + * provider implementation may introduce own types for its content + * objects (See queryCreatableContentsInfo()). * @param nPropertyHandes is a sequence of handles of properties for that * values are to set at the new content before it will be inserted * ( commited ). diff --git a/ucbhelper/source/client/content.cxx b/ucbhelper/source/client/content.cxx index e3b98ed24d81..28eef297e85f 100644 --- a/ucbhelper/source/client/content.cxx +++ b/ucbhelper/source/client/content.cxx @@ -73,9 +73,7 @@ #include #include #include -#ifndef _UCBHELPER_INTERACTIONREQUEST_HXX #include -#endif #include using namespace com::sun::star::container; @@ -210,6 +208,7 @@ public: Any executeCommand( const Command& rCommand ); void abortCommand(); + inline const Reference< XCommandEnvironment >& getEnvironment() const; inline void setEnvironment( const Reference< XCommandEnvironment >& xNewEnv ); @@ -1348,6 +1347,26 @@ void Content::writeStream( const Reference< XInputStream >& rStream, m_xImpl->inserted(); } +//========================================================================= +Sequence< ContentInfo > Content::queryCreatableContentsInfo() + throw( CommandAbortedException, RuntimeException, Exception ) +{ + // First, try it using "CreatableContentsInfo" property -> the "new" way. + Sequence< ContentInfo > aInfo; + if ( getPropertyValue( + rtl::OUString::createFromAscii( "CreatableContentsInfo" ) ) + >>= aInfo ) + return aInfo; + + // Second, try it using XContentCreator interface -> the "old" way (not + // providing the chance to supply an XCommandEnvironment. + Reference< XContentCreator > xCreator( m_xImpl->getContent(), UNO_QUERY ); + if ( xCreator.is() ) + aInfo = xCreator->queryCreatableContentsInfo(); + + return aInfo; +} + //========================================================================= sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, const Sequence< rtl::OUString >& @@ -1390,21 +1409,43 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, if ( rContentType.getLength() == 0 ) return sal_False; - Reference< XContentCreator > xCreator( m_xImpl->getContent(), UNO_QUERY ); - - OSL_ENSURE( xCreator.is(), - "Content::insertNewContent - Not a XContentCreator!" ); - - if ( !xCreator.is() ) - return sal_False; - + // First, try it using "createNewContent" command -> the "new" way. ContentInfo aInfo; aInfo.Type = rContentType; aInfo.Attributes = 0; - Reference< XContent > xNew = xCreator->createNewContent( aInfo ); + Command aCommand; + aCommand.Name = rtl::OUString::createFromAscii( "createNewContent" ); + aCommand.Handle = -1; // n/a + aCommand.Argument <<= aInfo; + + Reference< XContent > xNew; + try + { + m_xImpl->executeCommand( aCommand ) >>= xNew; + } + catch ( RuntimeException const & ) + { + throw; + } + catch ( Exception const & ) + { + } + if ( !xNew.is() ) - return sal_False; + { + // Second, try it using XContentCreator interface -> the "old" + // way (not providing the chance to supply an XCommandEnvironment. + Reference< XContentCreator > xCreator( m_xImpl->getContent(), UNO_QUERY ); + + if ( !xCreator.is() ) + return sal_False; + + xNew = xCreator->createNewContent( aInfo ); + + if ( !xNew.is() ) + return sal_False; + } Content aNewContent( xNew, m_xImpl->getEnvironment() ); aNewContent.setPropertyValues( rPropertyNames, rPropertyValues ); @@ -1431,21 +1472,43 @@ sal_Bool Content::insertNewContent( const rtl::OUString& rContentType, if ( rContentType.getLength() == 0 ) return sal_False; - Reference< XContentCreator > xCreator( m_xImpl->getContent(), UNO_QUERY ); - - OSL_ENSURE( xCreator.is(), - "Content::insertNewContent - Not a XContentCreator!" ); - - if ( !xCreator.is() ) - return sal_False; - + // First, try it using "createNewContent" command -> the "new" way. ContentInfo aInfo; aInfo.Type = rContentType; aInfo.Attributes = 0; - Reference< XContent > xNew = xCreator->createNewContent( aInfo ); + Command aCommand; + aCommand.Name = rtl::OUString::createFromAscii( "createNewContent" ); + aCommand.Handle = -1; // n/a + aCommand.Argument <<= aInfo; + + Reference< XContent > xNew; + try + { + m_xImpl->executeCommand( aCommand ) >>= xNew; + } + catch ( RuntimeException const & ) + { + throw; + } + catch ( Exception const & ) + { + } + if ( !xNew.is() ) - return sal_False; + { + // Second, try it using XContentCreator interface -> the "old" + // way (not providing the chance to supply an XCommandEnvironment. + Reference< XContentCreator > xCreator( m_xImpl->getContent(), UNO_QUERY ); + + if ( !xCreator.is() ) + return sal_False; + + xNew = xCreator->createNewContent( aInfo ); + + if ( !xNew.is() ) + return sal_False; + } Content aNewContent( xNew, m_xImpl->getEnvironment() ); aNewContent.setPropertyValues( nPropertyHandles, rPropertyValues ); diff --git a/unotools/source/ucbhelper/ucbhelper.cxx b/unotools/source/ucbhelper/ucbhelper.cxx index 2b301efc4e52..a798f485516a 100644 --- a/unotools/source/ucbhelper/ucbhelper.cxx +++ b/unotools/source/ucbhelper/ucbhelper.cxx @@ -46,15 +46,13 @@ #include #include #include +#include #include -#include #include #include #include #include -#ifndef _COM_SUN_STAR_UCB_INTERACTIVEIODEXCEPTION_HPP_ #include -#endif #include #include #include @@ -489,11 +487,7 @@ sal_Bool UCBContentHelper::CanMakeFolder( const String& rFolder ) try { Content aCnt( rFolder, uno::Reference< XCommandEnvironment > () ); - uno::Reference< XContentCreator > xCreator = uno::Reference< XContentCreator >( aCnt.get(), UNO_QUERY ); - if ( !xCreator.is() ) - return sal_False; - - Sequence< ContentInfo > aInfo = xCreator->queryCreatableContentsInfo(); + Sequence< ContentInfo > aInfo = aCnt.queryCreatableContentsInfo(); sal_Int32 nCount = aInfo.getLength(); if ( nCount == 0 ) return sal_False; @@ -538,11 +532,7 @@ sal_Bool UCBContentHelper::MakeFolder( Content& aCnt, const String& aTitle, Cont try { - uno::Reference< XContentCreator > xCreator( aCnt.get(), UNO_QUERY ); - if ( !xCreator.is() ) - return sal_False; - - Sequence< ContentInfo > aInfo = xCreator->queryCreatableContentsInfo(); + Sequence< ContentInfo > aInfo = aCnt.queryCreatableContentsInfo(); sal_Int32 nCount = aInfo.getLength(); if ( nCount == 0 ) return sal_False; -- cgit From 74d69666a871202c0073d4fe23982c7cea063276 Mon Sep 17 00:00:00 2001 From: ericb Date: Thu, 7 Jan 2010 10:16:57 +0100 Subject: eraser01: #i103174# fix missing changes due to rebase from external repository --- cppcanvas/inc/cppcanvas/color.hxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cppcanvas/inc/cppcanvas/color.hxx b/cppcanvas/inc/cppcanvas/color.hxx index e1cb30900e5e..ad0430713ead 100644 --- a/cppcanvas/inc/cppcanvas/color.hxx +++ b/cppcanvas/inc/cppcanvas/color.hxx @@ -83,6 +83,11 @@ namespace cppcanvas return (nRed << 24U)|(nGreen << 16U)|(nBlue << 8U)|(nAlpha); } + inline sal_Int32 unMakeColor( sal_uInt8 nAlpha, sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue) + { + return (nAlpha << 24U)|(nRed << 16U)|(nGreen << 8U)|(nBlue); + } + inline sal_Int32 makeColorARGB( sal_uInt8 nAlpha, sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue) { return (nAlpha << 24U)|(nRed << 16U)|(nGreen << 8U)|(nBlue); -- cgit From 0b2cc3465d5a793c36b6ba2752d4b332a6d61e05 Mon Sep 17 00:00:00 2001 From: Christian Lippka Date: Thu, 7 Jan 2010 11:53:09 +0000 Subject: reverted previous patch --- vcl/source/gdi/outdev3.cxx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/vcl/source/gdi/outdev3.cxx b/vcl/source/gdi/outdev3.cxx index e39ca248567f..51aad0790a26 100644 --- a/vcl/source/gdi/outdev3.cxx +++ b/vcl/source/gdi/outdev3.cxx @@ -7479,7 +7479,7 @@ BOOL OutputDevice::GetTextBoundRect( Rectangle& rRect, { bRet = pSalLayout->GetBoundRect( *mpGraphics, aPixelRect ); - if( bRet && (aPixelRect.GetWidth() > 0) || (aPixelRect.GetHeight() > 0) ) + if( bRet ) { int nWidthFactor = pSalLayout->GetUnitsPerPixel(); @@ -7601,12 +7601,6 @@ BOOL OutputDevice::GetTextBoundRect( Rectangle& rRect, aBmp.ReleaseAccess( pAcc ); - if( (nRight <= nLeft) || (nBottom <= nTop) ) - { - rRect.SetEmpty(); - return TRUE; - } - if( nTop <= nBottom ) { Size aSize( nRight - nLeft + 1, nBottom - nTop + 1 ); -- cgit From 86f7dae1d7a3f95a68cf5132cef03073787d3810 Mon Sep 17 00:00:00 2001 From: Stephan Bergmann Date: Thu, 7 Jan 2010 16:18:32 +0000 Subject: #i53184# further fix in INetURLObject::setAbsURIRef for UNC server names containing underscores --- tools/source/fsys/urlobj.cxx | 18 ++++++++---------- tools/workben/urltest.cxx | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/tools/source/fsys/urlobj.cxx b/tools/source/fsys/urlobj.cxx index f7ffed5e4dd1..e0f711bd2883 100644 --- a/tools/source/fsys/urlobj.cxx +++ b/tools/source/fsys/urlobj.cxx @@ -1022,16 +1022,14 @@ bool INetURLObject::setAbsURIRef(rtl::OUString const & rTheAbsURIRef, if (pEnd - pPos >= 2 && pPos[0] == '/' && pPos[1] == '/') { sal_Unicode const * p1 = pPos + 2; - if ( - p1 == pEnd || *p1 == nFragmentDelimiter || *p1 == '/' || - ( - ( - scanDomain(p1, pEnd) > 0 || - scanIPv6reference(p1, pEnd) - ) && - (p1 == pEnd || *p1 == nFragmentDelimiter || *p1 == '/') - ) - ) + while (p1 != pEnd && *p1 != '/' && + *p1 != nFragmentDelimiter) + { + ++p1; + } + if (parseHostOrNetBiosName( + pPos + 2, p1, bOctets, ENCODE_ALL, + RTL_TEXTENCODING_DONTKNOW, true, NULL)) { aSynAbsURIRef. appendAscii(RTL_CONSTASCII_STRINGPARAM("//")); diff --git a/tools/workben/urltest.cxx b/tools/workben/urltest.cxx index a232f8ebdd93..0e9d22081cb4 100644 --- a/tools/workben/urltest.cxx +++ b/tools/workben/urltest.cxx @@ -1629,6 +1629,20 @@ main() rtl::OUString(urlobj.GetMainURL(INetURLObject::NO_DECODE))); } + if (true) { // #i53184# + rtl::OUString url(RTL_CONSTASCII_USTRINGPARAM("file://comp_name/path")); + bSuccess &= assertEqual( + rtl::OUString( + RTL_CONSTASCII_USTRINGPARAM("#i53184# smart INET_PROT_FILE")), + INetURLObject(url, INET_PROT_FILE).GetMainURL( + INetURLObject::NO_DECODE), + url); + bSuccess &= assertEqual( + rtl::OUString( + RTL_CONSTASCII_USTRINGPARAM("#i53184# strict")), + INetURLObject(url).GetMainURL(INetURLObject::NO_DECODE), url); + } + if (true) { rtl::OUString path; path = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/a/b/c")); -- cgit From 432e0fcb93c713a39890ec7ed0769521ef6ef3e8 Mon Sep 17 00:00:00 2001 From: hdu Date: Fri, 8 Jan 2010 12:59:39 +0100 Subject: #i108138# fix printing crash which happens since DEV300_m66 --- vcl/source/gdi/outdev3.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vcl/source/gdi/outdev3.cxx b/vcl/source/gdi/outdev3.cxx index 51aad0790a26..28fa4f8f5461 100644 --- a/vcl/source/gdi/outdev3.cxx +++ b/vcl/source/gdi/outdev3.cxx @@ -5601,6 +5601,8 @@ void OutputDevice::DrawTextArray( const Point& rStartPt, const String& rStr, if ( !IsDeviceOutputNecessary() ) return; + if( !mpGraphics && !ImplGetGraphics() ) + return; if( mbInitClipRegion ) ImplInitClipRegion(); if( mbOutputClipped ) -- cgit From 81f4386da532ba62e5e2381e57485197ce5da0bf Mon Sep 17 00:00:00 2001 From: sj Date: Mon, 11 Jan 2010 12:28:07 +0100 Subject: impress181: #i74384# correctly interpreting maxcolor value vor ppm (taking care also for pbp) --- goodies/source/filter.vcl/ipbm/ipbm.cxx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/goodies/source/filter.vcl/ipbm/ipbm.cxx b/goodies/source/filter.vcl/ipbm/ipbm.cxx index c0b0f6012116..3c30dd0c2ba3 100644 --- a/goodies/source/filter.vcl/ipbm/ipbm.cxx +++ b/goodies/source/filter.vcl/ipbm/ipbm.cxx @@ -172,6 +172,7 @@ BOOL PBMReader::ImplReadHeader() *mpPBM >> nID[ 0 ] >> nID[ 1 ]; if ( nID[ 0 ] != 'P' ) return FALSE; + mnMaxVal = mnWidth = mnHeight = 0; switch ( nID[ 1 ] ) { case '1' : @@ -179,6 +180,7 @@ BOOL PBMReader::ImplReadHeader() case '4' : mnMode = 0; nMax = 2; // number of parameters in Header + mnMaxVal = 1; break; case '2' : mbRaw = FALSE; @@ -195,9 +197,6 @@ BOOL PBMReader::ImplReadHeader() default: return FALSE; } - - mnMaxVal = mnWidth = mnHeight = 0; - while ( bFinished == FALSE ) { if ( mpPBM->GetError() ) -- cgit From c7fcabef35a9ccf49a5de2c8ff1470aee77c238d Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Tue, 12 Jan 2010 11:18:27 +0000 Subject: cmcfixes69: #i106157# support system graphite, even with a different stlport --- vcl/inc/postgraphitestl.h | 12 ++---------- vcl/inc/pregraphitestl.h | 20 +++++++++----------- 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/vcl/inc/postgraphitestl.h b/vcl/inc/postgraphitestl.h index 8a8a0ca056ae..736aa248b7ff 100644 --- a/vcl/inc/postgraphitestl.h +++ b/vcl/inc/postgraphitestl.h @@ -1,17 +1,9 @@ #ifdef std_was_redefined_as_stlport // put things back the way they were # define std std_was_redefined_as_stlport -# undef _STLP_DONT_REDEFINE_STD -# undef _STLP_WHOLE_NATIVE_STD -# undef _STLP_STRING -# undef _STLP_IOSTREAM -# undef _STLP_IOSFWD -# undef _STLP_IOMANIP -# undef _STLP_ALGORITHM -# undef _STLP_VECTOR -# undef _STLP_SET -# undef _STLP_MAP +# undef _STLP_OUTERMOST_HEADER_ID // force config to be re-read +# undef _STLP_NOTHROW_INHERENTLY # undef _STLP_CONFIG_H # include #endif diff --git a/vcl/inc/pregraphitestl.h b/vcl/inc/pregraphitestl.h index 84bede349d4f..ece0af477113 100644 --- a/vcl/inc/pregraphitestl.h +++ b/vcl/inc/pregraphitestl.h @@ -1,23 +1,20 @@ #if defined(GRAPHITEADAPTSTL) && defined(std) +# include +# include +# include +# include +# include +# include # define std_was_redefined_as_stlport std # undef std -# undef _STLP_CONFIG_H -# undef _STLP_STRING -# undef _STLP_IOSTREAM -# undef _STLP_IOSFWD -# undef _STLP_IOMANIP -# undef _STLP_ALGORITHM -# undef _STLP_VECTOR -# undef _STLP_SET -# undef _STLP_MAP -# define _STLP_DONT_REDEFINE_STD 1 -# define _STLP_WHOLE_NATIVE_STD 1 +# define _STLP_OUTERMOST_HEADER_ID 0xdeadbeaf # pragma GCC visibility push(default) # include _STLP_NATIVE_HEADER(exception_defines.h) # include _STLP_NATIVE_HEADER(limits) # include _STLP_NATIVE_HEADER(memory) # include _STLP_NATIVE_HEADER(exception) # include _STLP_NATIVE_HEADER(iosfwd) +# include _STLP_NATIVE_HEADER(algorithm) # include _STLP_NATIVE_HEADER(string) # include _STLP_NATIVE_HEADER(streambuf) # include _STLP_NATIVE_HEADER(ios) @@ -26,6 +23,7 @@ # include _STLP_NATIVE_HEADER(ostream) # include _STLP_NATIVE_HEADER(istream) # include _STLP_NATIVE_HEADER(iostream) +# include _STLP_NATIVE_HEADER(vector) # pragma GCC visibility pop #endif //sil_std resolves to the std that Graphite was built with -- cgit From 6d62a5cf692529856b21cfa84a71fdfde75521e3 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Tue, 12 Jan 2010 13:04:00 +0000 Subject: cmcfixes69: #i108258# fix mismatch new[]/delete --- transex3/source/inireader.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/transex3/source/inireader.cxx b/transex3/source/inireader.cxx index 0985e788452d..63f902a5a1da 100644 --- a/transex3/source/inireader.cxx +++ b/transex3/source/inireader.cxx @@ -120,7 +120,7 @@ void INIreader::toStlString( const UnicodeString& str , string& stl_str) char* buffer = new char[ str.length()*3 ]; str.extract( 0 , str.length() , buffer ); stl_str = string( buffer ); - delete buffer; + delete [] buffer; } void INIreader::trim( string& str ) -- cgit From b38be2caf83f44538f213d1c01420aee67bebce3 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Tue, 12 Jan 2010 13:06:48 +0000 Subject: cmcfixes69: #i108259# fix possible leaks --- transex3/source/export2.cxx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/transex3/source/export2.cxx b/transex3/source/export2.cxx index 7815e80e033f..bf2648b0ca4f 100644 --- a/transex3/source/export2.cxx +++ b/transex3/source/export2.cxx @@ -354,17 +354,18 @@ bool Export::CopyFile( const ByteString& source , const ByteString& dest ) const int BUFFERSIZE = 8192; char buf[ BUFFERSIZE ]; - FILE* IN_FILE = fopen( source.GetBuffer() , "r" ); - FILE* OUT_FILE = fopen( dest.GetBuffer() , "w" ); - + FILE* IN_FILE = fopen( source.GetBuffer() , "r" ); if( IN_FILE == NULL ) { cerr << "Export::CopyFile WARNING: Could not open " << source.GetBuffer() << "\n"; return false; } + + FILE* OUT_FILE = fopen( dest.GetBuffer() , "w" ); if( OUT_FILE == NULL ) { cerr << "Export::CopyFile WARNING: Could not open/create " << dest.GetBuffer() << " for writing\n"; + fclose( IN_FILE ); return false; } -- cgit From e646dde27ab190586ad123de14cfe870dc26aaae Mon Sep 17 00:00:00 2001 From: Michael Stahl Date: Wed, 13 Jan 2010 17:55:09 +0100 Subject: swunolocking1: #i108161#: WeakReferenceHelper: Apple g++ 4.0.1 erroneously believes that it is ambiguous to use WeakReference::operator=(Reference). as a workaround, introduce WeakReferenceHelper::clear(), and fix all users. --- comphelper/inc/comphelper/weakeventlistener.hxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/comphelper/inc/comphelper/weakeventlistener.hxx b/comphelper/inc/comphelper/weakeventlistener.hxx index c6938e2b8423..045dfb169312 100644 --- a/comphelper/inc/comphelper/weakeventlistener.hxx +++ b/comphelper/inc/comphelper/weakeventlistener.hxx @@ -76,7 +76,7 @@ namespace comphelper inline void resetListener( ) { - m_aListener = ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(); + m_aListener.clear(); } -- cgit From dcbaee1e7d51a7645ce5236b9c8d78736a51c326 Mon Sep 17 00:00:00 2001 From: Kurt Zenker Date: Thu, 14 Jan 2010 17:37:57 +0100 Subject: masterfix: #i108160# build error fixed --- canvas/source/cairo/cairo_canvashelper.cxx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/canvas/source/cairo/cairo_canvashelper.cxx b/canvas/source/cairo/cairo_canvashelper.cxx index 5469010f2745..7a5e81a5512a 100644 --- a/canvas/source/cairo/cairo_canvashelper.cxx +++ b/canvas/source/cairo/cairo_canvashelper.cxx @@ -990,7 +990,8 @@ namespace cairocanvas aEdge.setNextControlPoint(0, aCandidate.getNextControlPoint(a)); aEdge.setPrevControlPoint(1, aCandidate.getPrevControlPoint(nNextIndex)); - doPolyPolygonImplementation( aEdge, aOperation, + doPolyPolygonImplementation( basegfx::B2DPolyPolygon(aEdge), + aOperation, pCairo, pTextures, mpSurfaceProvider, xPolyPolygon->getFillRule() ); @@ -1187,7 +1188,7 @@ namespace cairocanvas cairo_save( mpCairo.get() ); useStates( viewState, renderState, true ); - doPolyPolygonPath( xPolyPolygon, Fill, &textures ); + doPolyPolygonPath( xPolyPolygon, Fill, false, &textures ); cairo_restore( mpCairo.get() ); } -- cgit From b2fa4ba9756e52f4ddbadb112673c7ed445ade00 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 14 Jan 2010 19:12:18 +0100 Subject: solar.hrc moved to vcl --- svl/inc/svl/solar.hrc | 305 -------------------------------------------------- 1 file changed, 305 deletions(-) delete mode 100644 svl/inc/svl/solar.hrc diff --git a/svl/inc/svl/solar.hrc b/svl/inc/svl/solar.hrc deleted file mode 100644 index 96149b89131c..000000000000 --- a/svl/inc/svl/solar.hrc +++ /dev/null @@ -1,305 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: solar.hrc,v $ - * $Revision: 1.6 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef _SOLAR_HRC -#define _SOLAR_HRC - -// defines ------------------------------------------------------------------ - -#define CREATERESMGR_NAME( Name ) #Name -#define CREATERESMGR( Name ) ResMgr::CreateResMgr( CREATERESMGR_NAME( Name ) ) - -#define RID_SFX_START 260 -#define RID_SFX_END 9999 - -#define RID_LIB_START 10000 -#define RID_LIB_END 19999 - -#define RID_SVX_START (RID_LIB_START) -#define RID_SVX_END (RID_LIB_START+499) - -#define RID_SBASIC_START (RID_LIB_START+500) -#define RID_SBASIC_END (RID_LIB_START+2999) - -#define RID_BASIC_START (RID_LIB_START+3000) -#define RID_BASIC_END (RID_LIB_START+4499) - -#define RID_UUI_START (RID_LIB_START+4500) -#define RID_UUI_END (RID_LIB_START+4599) - -#define RID_HELP_START (RID_LIB_START+4600) -#define RID_HELP_END (RID_LIB_START+4799) - -#define RID_MAIL_START (RID_LIB_START+4800) -#define RID_MAIL_END (RID_LIB_START+4849) - -#define RID_BASICIDE_START (RID_LIB_START+4850) -#define RID_BASICIDE_END (RID_LIB_START+4949) - -#define RID_SVXITEMS_START (RID_LIB_START+4950) -#define RID_SVXITEMS_END (RID_LIB_START+5599) - -#define RID_SBA_START (RID_LIB_START+5600) -#define RID_SBA_END (RID_LIB_START+5649) - -#define RID_ISETBRW_START (RID_LIB_START+5650) -#define RID_ISETBRW_END (RID_LIB_START+5699) - -#define RID_EXTENSIONS_START (RID_LIB_START+5700) -#define RID_EXTENSIONS_END (RID_LIB_START+5799) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_OUTL_START (RID_LIB_START+5900) -#define RID_OUTL_END (RID_LIB_START+5919) - -#define RID_SVTOOLS_START (RID_LIB_START+5920) -#define RID_SVTOOLS_END (RID_LIB_START+5999) - -#define RID_INET_START (RID_LIB_START+6000) -#define RID_INET_END (RID_LIB_START+6059) - -#define RID_SO2_START (RID_LIB_START+6060) -#define RID_SO2_END (RID_LIB_START+6099) - -#define RID_GOODIES_START (RID_LIB_START+6100) -#define RID_GOODIES_END (RID_LIB_START+6149) - -#define RID_SJ_START (RID_LIB_START+6150) -#define RID_SJ_END (RID_LIB_START+6199) - -#define RID_SI_START (RID_LIB_START+6200) -#define RID_SI_END (RID_LIB_START+6399) - -#define RID_DLG_START (RID_LIB_START+6400) -#define RID_DLG_END (RID_LIB_START+6499) - -#define RID_OFA_START (RID_LIB_START+6500) -#define RID_OFA_END (RID_LIB_START+6999) - -#define RID_CHANNEL_START (RID_LIB_START+7000) -#define RID_CHANNEL_END (RID_LIB_START+7499) - -#define RID_CHAOS_START (RID_LIB_START+7500) -#define RID_CHAOS_END (RID_LIB_START+7999) - -#define RID_FORMS_START (RID_LIB_START+8000) -#define RID_FORMS_END (RID_LIB_START+8999) - -#define RID_FORMLAYER_START (RID_LIB_START+9000) -#define RID_FORMLAYER_END (RID_LIB_START+9199) - -#define RID_DBACCESS_START (RID_LIB_START+9200) -#define RID_DBACCESS_END (RID_LIB_START+9699) - -#define RID_MORE_EXTENSIONS_START (RID_LIB_START+9700) -#define RID_MORE_EXTENSIONS_END (RID_LIB_START+9999) - -#define RID_DB_EXTENSIONS_START (RID_LIB_START+10000) -#define RID_DB_EXTENSIONS_END (RID_LIB_START+10199) - -#define RID_FILTER_START (RID_LIB_START+10200) -#define RID_FILTER_END (RID_LIB_START+10299) - -// do *NOT* add more ranges here, RID_LIB_END is (RID_LIB_START + 10000) - -#define RID_APP_START 20000 -#define RID_APP_END 31999 - -#define RID_SW_START (20000) -#define RID_SW_END (25999) - -#define RID_SC_START (26000) -#define RID_SC_END (26999) - -#define RID_SD_START (27000) -#define RID_SD_END (27999) - -#define RID_OBJ_START (30000) -#define RID_OBJ_END (32767) - -#define RID_SIM_START (RID_OBJ_START+ 0) -#define RID_SIM_END (RID_OBJ_START+ 255) - -#define RID_SMA_START (RID_OBJ_START+ 256) -#define RID_SMA_END (RID_OBJ_START+ 511) - -#define RID_SCH_START (RID_OBJ_START+ 512) -#define RID_SCH_END (RID_OBJ_START+ 767) - -#define RID_RPT_START (RID_OBJ_START+768) -#define RID_RPT_END (RID_OBJ_START+1000) - -#define RID_FORMULA_START (RID_OBJ_START+1001) -#define RID_FORMULA_END (RID_OBJ_START+1200) -// Help-Ids -------------------------------------------------------------- - -#define HID_OK_BUTTON 0 -#define HID_CANCEL_BUTTON 0 -#define HID_HELP_BUTTON 0 - -#define HID_START 32768 - -#define HID_SVTOOLS_START (HID_START+200) -#define HID_SVTOOLS_END (HID_START+299) - -#define HID_SFX_START (HID_START+300) -#define HID_SFX_END (HID_START+999) - -#define HID_LIB_START (HID_START+1000) -#define HID_LIB_END (HID_START+19999) - -#define HID_SVX_START (HID_LIB_START) -#define HID_SVX_END (HID_LIB_START+431) - -#define HID_WIZARD_START (HID_LIB_START+432) -#define HID_WIZARD_END (HID_LIB_START+999) -//please note: There is also HID_WIZARD2 below - -// FREE - -#define HID_CUI_START (HID_LIB_START+1100) -#define HID_CUI_END (HID_LIB_START+1699) - -#define HID_OFA_START (HID_LIB_START+1760) -#define HID_OFA_END (HID_LIB_START+1999) - -#define HID_HELP_START (HID_LIB_START+2000) -#define HID_HELP_END (HID_LIB_START+2050) - -#define HID_CHAOS_START (HID_LIB_START+2051) -#define HID_CHAOS_END (HID_LIB_START+2069) - -#define HID_UUI_START (HID_LIB_START+2070) -#define HID_UUI_END (HID_LIB_START+2099) - -#define HID_GOODIES_START (HID_LIB_START+2100) -#define HID_GOODIES_END (HID_LIB_START+2199) - -#define HID_SCHEDULE_START (HID_LIB_START+2200) -#define HID_SCHEDULE_END (HID_LIB_START+3399) - -#define HID_CHANNEL_START (HID_LIB_START+3400) -#define HID_CHANNEL_END (HID_LIB_START+3499) - -#define HID_SBA_START (HID_LIB_START+ 3500) -#define HID_SBA_END (HID_LIB_START+ 3999) - -#define HID_FORMS_START (HID_LIB_START+4000) -#define HID_FORMS_END (HID_LIB_START+4999) - -#define HID_DBACCESS_START (HID_LIB_START+5000) -#define HID_DBACCESS_END (HID_LIB_START+5299) - -#define HID_PORTAL_START (HID_LIB_START+5300) -#define HID_PORTAL_END (HID_LIB_START+5599) - -#define HID_PORTAL_ADMIN_START (HID_LIB_START+5600) -#define HID_PORTAL_ADMIN_END (HID_LIB_START+5999) - -#define HID_SYNCACCESS_START (HID_LIB_START+6000) -#define HID_SYNCACCESS_END (HID_LIB_START+6099) - -#define HID_SVX_EXT0_START (HID_LIB_START+6100) -#define HID_SVX_EXT0_END (HID_LIB_START+6599) - -#define HID_FRAMEWORK_START (HID_LIB_START+6600) -#define HID_FRAMEWORK_END (HID_LIB_START+6999) - -#define HID_WIZARD2_START (HID_LIB_START+7000) -#define HID_WIZARD2_END (HID_LIB_START+8999) - -#define HID_DESKTOP_START (HID_LIB_START+9000) -#define HID_DESKTOP_END (HID_LIB_START+9299) - -#define HID_XMLSECURITY_START (HID_LIB_START+9300) -#define HID_XMLSECURITY_END (HID_LIB_START+9999) - -#define HID_APP_START (HID_START+20000) -#define HID_APP_END (HID_START+29999) - -#define HID_SW_START (HID_START+20000) -#define HID_SW_END (HID_START+24999) - -#define HID_SC_START (HID_START+25000) -#define HID_SC_END (HID_START+26999) - -#define HID_SD_START (HID_START+27000) -#define HID_SD_END (HID_START+27999) - -#define HID_Sa_START (HID_START+28000) -#define HID_Sa_END (HID_START+28999) - -#define HID_Sb_START (HID_START+29000) -#define HID_Sb_END (HID_START+29999) - -#define HID_OBJ_START (HID_START+30000) -#define HID_OBJ_END (HID_START+32767) - -#define HID_CUI3_START (HID_OBJ_START+ 0) -#define HID_CUI3_END (HID_OBJ_START+ 239) - -#define HID_AVMEDIA_START (HID_OBJ_START+ 240) -#define HID_AVMEDIA_END (HID_OBJ_START+ 255) - -#define HID_SMA_START (HID_OBJ_START+ 256) -#define HID_SMA_END (HID_OBJ_START+ 511) - -#define HID_SCH_START (HID_OBJ_START+ 512) -#define HID_SCH_END (HID_OBJ_START+ 767) - -#define HID_BASICIDE_START (HID_OBJ_START+ 768) -#define HID_BASICIDE_END (HID_OBJ_START+1023) - -#define HID_SMA2_START (HID_OBJ_START+1024) -#define HID_SMA2_END (HID_OBJ_START+1280) - -#define HID_FILTER_START (HID_OBJ_START+1281) -#define HID_FILTER_END (HID_OBJ_START+1580) - -#define HID_LICENSING_START (HID_OBJ_START+1581) -#define HID_LICENSING_END (HID_OBJ_START+1680) - -#define HID_RPT_START (HID_OBJ_START+1681) -#define HID_RPT_END (HID_OBJ_START+2080) - -#define HID_FORMULA_START (HID_OBJ_START+2081) -#define HID_FORMULA_END (HID_OBJ_START+2280) - -#define HID_EXTENSIONS_START (HID_OBJ_START+2281) -#define HID_EXTENSIONS_END (HID_OBJ_START+2800) - - -#endif - -- cgit From 6ac5d627b946828fdf791cca381e9c526c755582 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Thu, 14 Jan 2010 22:27:44 +0100 Subject: undo previous erroneous change, solar.hrc belongs to svl instead vcl now --- goodies/inc/goodies.hrc | 2 +- goodies/inc/pch/precompiled_goodies.hxx | 2 +- goodies/source/filter.vcl/egif/egif.cxx | 2 +- goodies/source/filter.vcl/eos2met/eos2met.cxx | 2 +- goodies/source/filter.vcl/epbm/epbm.cxx | 2 +- goodies/source/filter.vcl/epgm/epgm.cxx | 2 +- goodies/source/filter.vcl/epict/epict.cxx | 2 +- goodies/source/filter.vcl/eppm/eppm.cxx | 2 +- goodies/source/filter.vcl/eps/eps.cxx | 2 +- goodies/source/filter.vcl/etiff/etiff.cxx | 2 +- goodies/source/filter.vcl/ipcd/ipcd.cxx | 2 +- goodies/source/inv/invader.cxx | 2 +- goodies/source/unographic/provider.cxx | 2 +- goodies/source/unographic/transformer.cxx | 2 +- svl/inc/svl/solar.hrc | 306 +++++++++++++++++++++ svl/inc/svl/svtools.hrc | 2 +- svtools/bmpmaker/bmp.cxx | 2 +- svtools/bmpmaker/bmpsum.cxx | 2 +- svtools/inc/svtools/helpid.hrc | 2 +- .../filter.vcl/filter/SvFilterOptionsDialog.cxx | 2 +- svtools/source/filter.vcl/filter/filter.cxx | 2 +- svtools/source/plugapp/testtool.src | 2 +- svtools/source/uno/unoifac2.hrc | 2 +- svtools/workben/unodialog/udlg_global.hrc | 2 +- vcl/inc/vcl/solar.hrc | 306 --------------------- vcl/inc/vcl/svids.hrc | 2 +- vcl/prj/build.lst | 2 +- vcl/prj/d.lst | 1 - 28 files changed, 331 insertions(+), 332 deletions(-) create mode 100644 svl/inc/svl/solar.hrc delete mode 100644 vcl/inc/vcl/solar.hrc diff --git a/goodies/inc/goodies.hrc b/goodies/inc/goodies.hrc index 0cad63e4efdd..139987c4f6ee 100644 --- a/goodies/inc/goodies.hrc +++ b/goodies/inc/goodies.hrc @@ -31,7 +31,7 @@ #define _GOODIES_HRC #ifndef _SOLAR_HRC -#include +#include #endif // Dialoge --------------------------------------------------------------- diff --git a/goodies/inc/pch/precompiled_goodies.hxx b/goodies/inc/pch/precompiled_goodies.hxx index 754e737467b4..fe6f2ec433e5 100644 --- a/goodies/inc/pch/precompiled_goodies.hxx +++ b/goodies/inc/pch/precompiled_goodies.hxx @@ -100,7 +100,7 @@ #include "svtools/fltcall.hxx" #include "svl/itemprop.hxx" #include "svl/lstner.hxx" -#include "vcl/solar.hrc" +#include "svl/solar.hrc" #include "svtools/stdctrl.hxx" #include "svl/svarray.hxx" diff --git a/goodies/source/filter.vcl/egif/egif.cxx b/goodies/source/filter.vcl/egif/egif.cxx index 6cef33de0187..9f2aeaddd686 100644 --- a/goodies/source/filter.vcl/egif/egif.cxx +++ b/goodies/source/filter.vcl/egif/egif.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "giflzwc.hxx" diff --git a/goodies/source/filter.vcl/eos2met/eos2met.cxx b/goodies/source/filter.vcl/eos2met/eos2met.cxx index 74db6f344492..b818e9cd26ba 100644 --- a/goodies/source/filter.vcl/eos2met/eos2met.cxx +++ b/goodies/source/filter.vcl/eos2met/eos2met.cxx @@ -47,7 +47,7 @@ #include #include #include -#include +#include #include "strings.hrc" #include "dlgeos2.hxx" diff --git a/goodies/source/filter.vcl/epbm/epbm.cxx b/goodies/source/filter.vcl/epbm/epbm.cxx index 2913452df4a9..a624e7f45cfb 100644 --- a/goodies/source/filter.vcl/epbm/epbm.cxx +++ b/goodies/source/filter.vcl/epbm/epbm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/epgm/epgm.cxx b/goodies/source/filter.vcl/epgm/epgm.cxx index 435a53da6b9f..32d6e74a5cfe 100644 --- a/goodies/source/filter.vcl/epgm/epgm.cxx +++ b/goodies/source/filter.vcl/epgm/epgm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/epict/epict.cxx b/goodies/source/filter.vcl/epict/epict.cxx index 4f20619eb185..cd9e33edd5d9 100644 --- a/goodies/source/filter.vcl/epict/epict.cxx +++ b/goodies/source/filter.vcl/epict/epict.cxx @@ -33,7 +33,7 @@ #include #include -#include +#include #include #include diff --git a/goodies/source/filter.vcl/eppm/eppm.cxx b/goodies/source/filter.vcl/eppm/eppm.cxx index 5d682a215f6a..d17b4f7777ae 100644 --- a/goodies/source/filter.vcl/eppm/eppm.cxx +++ b/goodies/source/filter.vcl/eppm/eppm.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include #include "strings.hrc" diff --git a/goodies/source/filter.vcl/eps/eps.cxx b/goodies/source/filter.vcl/eps/eps.cxx index d3580bf4ebc6..83b5a94f97f2 100644 --- a/goodies/source/filter.vcl/eps/eps.cxx +++ b/goodies/source/filter.vcl/eps/eps.cxx @@ -46,7 +46,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/goodies/source/filter.vcl/etiff/etiff.cxx b/goodies/source/filter.vcl/etiff/etiff.cxx index c4bd6524627b..3cdec42d0978 100644 --- a/goodies/source/filter.vcl/etiff/etiff.cxx +++ b/goodies/source/filter.vcl/etiff/etiff.cxx @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include diff --git a/goodies/source/filter.vcl/ipcd/ipcd.cxx b/goodies/source/filter.vcl/ipcd/ipcd.cxx index b0d7cbc1eabb..f7a5f3652cbf 100644 --- a/goodies/source/filter.vcl/ipcd/ipcd.cxx +++ b/goodies/source/filter.vcl/ipcd/ipcd.cxx @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include //============================ PCDReader ================================== diff --git a/goodies/source/inv/invader.cxx b/goodies/source/inv/invader.cxx index 4e91536e577b..0aed6e76848f 100644 --- a/goodies/source/inv/invader.cxx +++ b/goodies/source/inv/invader.cxx @@ -37,7 +37,7 @@ #include "invader.hrc" #include "strings.hrc" #include "score.hxx" -#include +#include #include #include #include diff --git a/goodies/source/unographic/provider.cxx b/goodies/source/unographic/provider.cxx index b332dd4233e2..1f7de99d4473 100644 --- a/goodies/source/unographic/provider.cxx +++ b/goodies/source/unographic/provider.cxx @@ -46,7 +46,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/goodies/source/unographic/transformer.cxx b/goodies/source/unographic/transformer.cxx index ee4371172514..7e18c10cdd41 100644 --- a/goodies/source/unographic/transformer.cxx +++ b/goodies/source/unographic/transformer.cxx @@ -43,7 +43,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/svl/inc/svl/solar.hrc b/svl/inc/svl/solar.hrc new file mode 100644 index 000000000000..26ab8a959c5e --- /dev/null +++ b/svl/inc/svl/solar.hrc @@ -0,0 +1,306 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _SOLAR_HRC +#define _SOLAR_HRC + +// defines ------------------------------------------------------------------ + +#define CREATERESMGR_NAME( Name ) #Name +#define CREATERESMGR( Name ) ResMgr::CreateResMgr( CREATERESMGR_NAME( Name ) ) + +#define RID_SFX_START 260 +#define RID_SFX_END 9999 + +#define RID_LIB_START 10000 +#define RID_LIB_END 19999 + +#define RID_SVX_START (RID_LIB_START) +#define RID_SVX_END (RID_LIB_START+499) + +#define RID_SBASIC_START (RID_LIB_START+500) +#define RID_SBASIC_END (RID_LIB_START+2999) + +#define RID_BASIC_START (RID_LIB_START+3000) +#define RID_BASIC_END (RID_LIB_START+4499) + +#define RID_UUI_START (RID_LIB_START+4500) +#define RID_UUI_END (RID_LIB_START+4599) + +#define RID_HELP_START (RID_LIB_START+4600) +#define RID_HELP_END (RID_LIB_START+4799) + +#define RID_MAIL_START (RID_LIB_START+4800) +#define RID_MAIL_END (RID_LIB_START+4849) + +#define RID_BASICIDE_START (RID_LIB_START+4850) +#define RID_BASICIDE_END (RID_LIB_START+4949) + +#define RID_SVXITEMS_START (RID_LIB_START+4950) +#define RID_SVXITEMS_END (RID_LIB_START+5599) + +#define RID_SBA_START (RID_LIB_START+5600) +#define RID_SBA_END (RID_LIB_START+5649) + +#define RID_ISETBRW_START (RID_LIB_START+5650) +#define RID_ISETBRW_END (RID_LIB_START+5699) + +#define RID_EXTENSIONS_START (RID_LIB_START+5700) +#define RID_EXTENSIONS_END (RID_LIB_START+5799) + +#define RID_EDIT_START (RID_LIB_START+5800) +#define RID_EDIT_END (RID_LIB_START+5899) + +#define RID_EDIT_START (RID_LIB_START+5800) +#define RID_EDIT_END (RID_LIB_START+5899) + +#define RID_OUTL_START (RID_LIB_START+5900) +#define RID_OUTL_END (RID_LIB_START+5919) + +#define RID_SVTOOLS_START (RID_LIB_START+5920) +#define RID_SVTOOLS_END (RID_LIB_START+5999) + +#define RID_INET_START (RID_LIB_START+6000) +#define RID_INET_END (RID_LIB_START+6059) + +#define RID_SO2_START (RID_LIB_START+6060) +#define RID_SO2_END (RID_LIB_START+6099) + +#define RID_GOODIES_START (RID_LIB_START+6100) +#define RID_GOODIES_END (RID_LIB_START+6149) + +#define RID_SJ_START (RID_LIB_START+6150) +#define RID_SJ_END (RID_LIB_START+6199) + +#define RID_SI_START (RID_LIB_START+6200) +#define RID_SI_END (RID_LIB_START+6399) + +#define RID_DLG_START (RID_LIB_START+6400) +#define RID_DLG_END (RID_LIB_START+6499) + +#define RID_OFA_START (RID_LIB_START+6500) +#define RID_OFA_END (RID_LIB_START+6999) + +#define RID_CHANNEL_START (RID_LIB_START+7000) +#define RID_CHANNEL_END (RID_LIB_START+7499) + +#define RID_CHAOS_START (RID_LIB_START+7500) +#define RID_CHAOS_END (RID_LIB_START+7999) + +#define RID_FORMS_START (RID_LIB_START+8000) +#define RID_FORMS_END (RID_LIB_START+8999) + +#define RID_FORMLAYER_START (RID_LIB_START+9000) +#define RID_FORMLAYER_END (RID_LIB_START+9199) + +#define RID_DBACCESS_START (RID_LIB_START+9200) +#define RID_DBACCESS_END (RID_LIB_START+9699) + +#define RID_MORE_EXTENSIONS_START (RID_LIB_START+9700) +#define RID_MORE_EXTENSIONS_END (RID_LIB_START+9999) + +#define RID_DB_EXTENSIONS_START (RID_LIB_START+10000) +#define RID_DB_EXTENSIONS_END (RID_LIB_START+10199) + +#define RID_FILTER_START (RID_LIB_START+10200) +#define RID_FILTER_END (RID_LIB_START+10299) + +// do *NOT* add more ranges here, RID_LIB_END is (RID_LIB_START + 10000) + +#define RID_APP_START 20000 +#define RID_APP_END 31999 + +#define RID_SW_START (20000) +#define RID_SW_END (25999) + +#define RID_SC_START (26000) +#define RID_SC_END (26999) + +#define RID_SD_START (27000) +#define RID_SD_END (27999) + +#define RID_OBJ_START (30000) +#define RID_OBJ_END (32767) + +#define RID_SIM_START (RID_OBJ_START+ 0) +#define RID_SIM_END (RID_OBJ_START+ 255) + +#define RID_SMA_START (RID_OBJ_START+ 256) +#define RID_SMA_END (RID_OBJ_START+ 511) + +#define RID_SCH_START (RID_OBJ_START+ 512) +#define RID_SCH_END (RID_OBJ_START+ 767) + +#define RID_RPT_START (RID_OBJ_START+768) +#define RID_RPT_END (RID_OBJ_START+1000) + +#define RID_FORMULA_START (RID_OBJ_START+1001) +#define RID_FORMULA_END (RID_OBJ_START+1200) +// Help-Ids -------------------------------------------------------------- + +#define HID_OK_BUTTON 0 +#define HID_CANCEL_BUTTON 0 +#define HID_HELP_BUTTON 0 + +#define HID_START 32768 + +#define HID_VCL_START (HID_START+100) +#define HID_VCL_END (HID_START+150) + +#define HID_SVTOOLS_START (HID_START+200) +#define HID_SVTOOLS_END (HID_START+299) + +#define HID_SFX_START (HID_START+300) +#define HID_SFX_END (HID_START+999) + +#define HID_LIB_START (HID_START+1000) +#define HID_LIB_END (HID_START+19999) + +#define HID_SVX_START (HID_LIB_START) +#define HID_SVX_END (HID_LIB_START+431) + +#define HID_WIZARD_START (HID_LIB_START+432) +#define HID_WIZARD_END (HID_LIB_START+999) +//please note: There is also HID_WIZARD2 below + +// FREE + +#define HID_CUI_START (HID_LIB_START+1100) +#define HID_CUI_END (HID_LIB_START+1699) + +#define HID_OFA_START (HID_LIB_START+1760) +#define HID_OFA_END (HID_LIB_START+1999) + +#define HID_HELP_START (HID_LIB_START+2000) +#define HID_HELP_END (HID_LIB_START+2050) + +#define HID_CHAOS_START (HID_LIB_START+2051) +#define HID_CHAOS_END (HID_LIB_START+2069) + +#define HID_UUI_START (HID_LIB_START+2070) +#define HID_UUI_END (HID_LIB_START+2099) + +#define HID_GOODIES_START (HID_LIB_START+2100) +#define HID_GOODIES_END (HID_LIB_START+2199) + +#if 0 // currently unused range +#define HID_SCHEDULE_START (HID_LIB_START+2200) +#define HID_SCHEDULE_END (HID_LIB_START+3399) +#endif + +#define HID_CHANNEL_START (HID_LIB_START+3400) +#define HID_CHANNEL_END (HID_LIB_START+3499) + +#define HID_SBA_START (HID_LIB_START+ 3500) +#define HID_SBA_END (HID_LIB_START+ 3999) + +#define HID_FORMS_START (HID_LIB_START+4000) +#define HID_FORMS_END (HID_LIB_START+4999) + +#define HID_DBACCESS_START (HID_LIB_START+5000) +#define HID_DBACCESS_END (HID_LIB_START+5299) + +#define HID_PORTAL_START (HID_LIB_START+5300) +#define HID_PORTAL_END (HID_LIB_START+5599) + +#define HID_PORTAL_ADMIN_START (HID_LIB_START+5600) +#define HID_PORTAL_ADMIN_END (HID_LIB_START+5999) + +#define HID_SYNCACCESS_START (HID_LIB_START+6000) +#define HID_SYNCACCESS_END (HID_LIB_START+6099) + +#define HID_SVX_EXT0_START (HID_LIB_START+6100) +#define HID_SVX_EXT0_END (HID_LIB_START+6599) + +#define HID_FRAMEWORK_START (HID_LIB_START+6600) +#define HID_FRAMEWORK_END (HID_LIB_START+6999) + +#define HID_WIZARD2_START (HID_LIB_START+7000) +#define HID_WIZARD2_END (HID_LIB_START+8999) + +#define HID_DESKTOP_START (HID_LIB_START+9000) +#define HID_DESKTOP_END (HID_LIB_START+9299) + +#define HID_XMLSECURITY_START (HID_LIB_START+9300) +#define HID_XMLSECURITY_END (HID_LIB_START+9999) + +#define HID_APP_START (HID_START+20000) +#define HID_APP_END (HID_START+29999) + +#define HID_SW_START (HID_START+20000) +#define HID_SW_END (HID_START+24999) + +#define HID_SC_START (HID_START+25000) +#define HID_SC_END (HID_START+26999) + +#define HID_SD_START (HID_START+27000) +#define HID_SD_END (HID_START+27999) + +#define HID_Sa_START (HID_START+28000) +#define HID_Sa_END (HID_START+28999) + +#define HID_Sb_START (HID_START+29000) +#define HID_Sb_END (HID_START+29999) + +#define HID_OBJ_START (HID_START+30000) +#define HID_OBJ_END (HID_START+32767) + +#define HID_CUI3_START (HID_OBJ_START+ 0) +#define HID_CUI3_END (HID_OBJ_START+ 239) + +#define HID_AVMEDIA_START (HID_OBJ_START+ 240) +#define HID_AVMEDIA_END (HID_OBJ_START+ 255) + +#define HID_SMA_START (HID_OBJ_START+ 256) +#define HID_SMA_END (HID_OBJ_START+ 511) + +#define HID_SCH_START (HID_OBJ_START+ 512) +#define HID_SCH_END (HID_OBJ_START+ 767) + +#define HID_BASICIDE_START (HID_OBJ_START+ 768) +#define HID_BASICIDE_END (HID_OBJ_START+1023) + +#define HID_SMA2_START (HID_OBJ_START+1024) +#define HID_SMA2_END (HID_OBJ_START+1280) + +#define HID_FILTER_START (HID_OBJ_START+1281) +#define HID_FILTER_END (HID_OBJ_START+1580) + +#define HID_LICENSING_START (HID_OBJ_START+1581) +#define HID_LICENSING_END (HID_OBJ_START+1680) + +#define HID_RPT_START (HID_OBJ_START+1681) +#define HID_RPT_END (HID_OBJ_START+2080) + +#define HID_FORMULA_START (HID_OBJ_START+2081) +#define HID_FORMULA_END (HID_OBJ_START+2280) + +#define HID_EXTENSIONS_START (HID_OBJ_START+2281) +#define HID_EXTENSIONS_END (HID_OBJ_START+2800) + +#endif + diff --git a/svl/inc/svl/svtools.hrc b/svl/inc/svl/svtools.hrc index ec3bf093d753..e4cc91cfcb49 100644 --- a/svl/inc/svl/svtools.hrc +++ b/svl/inc/svl/svtools.hrc @@ -30,7 +30,7 @@ #ifndef _SVTOOLS_HRC #define _SVTOOLS_HRC "$Revision: 1.0" -#include +#include #define RID_SVTOOLS_BITMAP_START (RID_SVTOOLS_START + 0) #define RID_SVTOOLS_IMAGELIST_START (RID_SVTOOLS_START + 0) diff --git a/svtools/bmpmaker/bmp.cxx b/svtools/bmpmaker/bmp.cxx index 52e2cb5fa7b0..b91dae79bbad 100644 --- a/svtools/bmpmaker/bmp.cxx +++ b/svtools/bmpmaker/bmp.cxx @@ -43,7 +43,7 @@ using namespace std; #include -#include "vcl/solar.hrc" +#include "svl/solar.hrc" #include "filedlg.hxx" #include "bmpcore.hxx" #include "bmp.hrc" diff --git a/svtools/bmpmaker/bmpsum.cxx b/svtools/bmpmaker/bmpsum.cxx index 6ba0ac3cfc78..3eee49ef695d 100644 --- a/svtools/bmpmaker/bmpsum.cxx +++ b/svtools/bmpmaker/bmpsum.cxx @@ -45,7 +45,7 @@ #include #include -#include "vcl/solar.hrc" +#include "svl/solar.hrc" #define EXIT_NOERROR 0x00000000 #define EXIT_INVALIDFILE 0x00000001 diff --git a/svtools/inc/svtools/helpid.hrc b/svtools/inc/svtools/helpid.hrc index d18120b8c0d4..937898f37af1 100644 --- a/svtools/inc/svtools/helpid.hrc +++ b/svtools/inc/svtools/helpid.hrc @@ -33,7 +33,7 @@ // include --------------------------------------------------------------- -#include +#include // Help-Ids -------------------------------------------------------------- diff --git a/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx b/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx index d07251079919..584814dd9e92 100644 --- a/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx +++ b/svtools/source/filter.vcl/filter/SvFilterOptionsDialog.cxx @@ -37,7 +37,7 @@ #include "FilterConfigCache.hxx" #include #include -#include +#include #include #include "dlgexpor.hxx" #include "dlgejpg.hxx" diff --git a/svtools/source/filter.vcl/filter/filter.cxx b/svtools/source/filter.vcl/filter/filter.cxx index 372b7496920b..306307a0bf91 100644 --- a/svtools/source/filter.vcl/filter/filter.cxx +++ b/svtools/source/filter.vcl/filter/filter.cxx @@ -54,7 +54,7 @@ #include "jpeg.hxx" #include "xbmread.hxx" #include "xpmread.hxx" -#include +#include #include "strings.hrc" #include "sgffilt.hxx" #include "osl/module.hxx" diff --git a/svtools/source/plugapp/testtool.src b/svtools/source/plugapp/testtool.src index 4333dedd4255..78b63c2fb819 100644 --- a/svtools/source/plugapp/testtool.src +++ b/svtools/source/plugapp/testtool.src @@ -28,7 +28,7 @@ * ************************************************************************/ #include "testtool.hrc" -#include +#include #define Control_Control 5 diff --git a/svtools/source/uno/unoifac2.hrc b/svtools/source/uno/unoifac2.hrc index 64941b1c3013..4f46edffdc51 100644 --- a/svtools/source/uno/unoifac2.hrc +++ b/svtools/source/uno/unoifac2.hrc @@ -33,7 +33,7 @@ #ifndef _SOLAR_HRC -#include +#include #endif //! Um den Überblick über alle benutzten HelpID's zu behalten sind diese diff --git a/svtools/workben/unodialog/udlg_global.hrc b/svtools/workben/unodialog/udlg_global.hrc index 6fa2679e3386..bde0e5e86ce2 100644 --- a/svtools/workben/unodialog/udlg_global.hrc +++ b/svtools/workben/unodialog/udlg_global.hrc @@ -31,7 +31,7 @@ #ifndef SVTOOLS_UDLG_GLOBAL_HRC #define SVTOOLS_UDLG_GLOBAL_HRC -#include +#include //===================================================================== //= bases diff --git a/vcl/inc/vcl/solar.hrc b/vcl/inc/vcl/solar.hrc deleted file mode 100644 index 26ab8a959c5e..000000000000 --- a/vcl/inc/vcl/solar.hrc +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2009 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef _SOLAR_HRC -#define _SOLAR_HRC - -// defines ------------------------------------------------------------------ - -#define CREATERESMGR_NAME( Name ) #Name -#define CREATERESMGR( Name ) ResMgr::CreateResMgr( CREATERESMGR_NAME( Name ) ) - -#define RID_SFX_START 260 -#define RID_SFX_END 9999 - -#define RID_LIB_START 10000 -#define RID_LIB_END 19999 - -#define RID_SVX_START (RID_LIB_START) -#define RID_SVX_END (RID_LIB_START+499) - -#define RID_SBASIC_START (RID_LIB_START+500) -#define RID_SBASIC_END (RID_LIB_START+2999) - -#define RID_BASIC_START (RID_LIB_START+3000) -#define RID_BASIC_END (RID_LIB_START+4499) - -#define RID_UUI_START (RID_LIB_START+4500) -#define RID_UUI_END (RID_LIB_START+4599) - -#define RID_HELP_START (RID_LIB_START+4600) -#define RID_HELP_END (RID_LIB_START+4799) - -#define RID_MAIL_START (RID_LIB_START+4800) -#define RID_MAIL_END (RID_LIB_START+4849) - -#define RID_BASICIDE_START (RID_LIB_START+4850) -#define RID_BASICIDE_END (RID_LIB_START+4949) - -#define RID_SVXITEMS_START (RID_LIB_START+4950) -#define RID_SVXITEMS_END (RID_LIB_START+5599) - -#define RID_SBA_START (RID_LIB_START+5600) -#define RID_SBA_END (RID_LIB_START+5649) - -#define RID_ISETBRW_START (RID_LIB_START+5650) -#define RID_ISETBRW_END (RID_LIB_START+5699) - -#define RID_EXTENSIONS_START (RID_LIB_START+5700) -#define RID_EXTENSIONS_END (RID_LIB_START+5799) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_EDIT_START (RID_LIB_START+5800) -#define RID_EDIT_END (RID_LIB_START+5899) - -#define RID_OUTL_START (RID_LIB_START+5900) -#define RID_OUTL_END (RID_LIB_START+5919) - -#define RID_SVTOOLS_START (RID_LIB_START+5920) -#define RID_SVTOOLS_END (RID_LIB_START+5999) - -#define RID_INET_START (RID_LIB_START+6000) -#define RID_INET_END (RID_LIB_START+6059) - -#define RID_SO2_START (RID_LIB_START+6060) -#define RID_SO2_END (RID_LIB_START+6099) - -#define RID_GOODIES_START (RID_LIB_START+6100) -#define RID_GOODIES_END (RID_LIB_START+6149) - -#define RID_SJ_START (RID_LIB_START+6150) -#define RID_SJ_END (RID_LIB_START+6199) - -#define RID_SI_START (RID_LIB_START+6200) -#define RID_SI_END (RID_LIB_START+6399) - -#define RID_DLG_START (RID_LIB_START+6400) -#define RID_DLG_END (RID_LIB_START+6499) - -#define RID_OFA_START (RID_LIB_START+6500) -#define RID_OFA_END (RID_LIB_START+6999) - -#define RID_CHANNEL_START (RID_LIB_START+7000) -#define RID_CHANNEL_END (RID_LIB_START+7499) - -#define RID_CHAOS_START (RID_LIB_START+7500) -#define RID_CHAOS_END (RID_LIB_START+7999) - -#define RID_FORMS_START (RID_LIB_START+8000) -#define RID_FORMS_END (RID_LIB_START+8999) - -#define RID_FORMLAYER_START (RID_LIB_START+9000) -#define RID_FORMLAYER_END (RID_LIB_START+9199) - -#define RID_DBACCESS_START (RID_LIB_START+9200) -#define RID_DBACCESS_END (RID_LIB_START+9699) - -#define RID_MORE_EXTENSIONS_START (RID_LIB_START+9700) -#define RID_MORE_EXTENSIONS_END (RID_LIB_START+9999) - -#define RID_DB_EXTENSIONS_START (RID_LIB_START+10000) -#define RID_DB_EXTENSIONS_END (RID_LIB_START+10199) - -#define RID_FILTER_START (RID_LIB_START+10200) -#define RID_FILTER_END (RID_LIB_START+10299) - -// do *NOT* add more ranges here, RID_LIB_END is (RID_LIB_START + 10000) - -#define RID_APP_START 20000 -#define RID_APP_END 31999 - -#define RID_SW_START (20000) -#define RID_SW_END (25999) - -#define RID_SC_START (26000) -#define RID_SC_END (26999) - -#define RID_SD_START (27000) -#define RID_SD_END (27999) - -#define RID_OBJ_START (30000) -#define RID_OBJ_END (32767) - -#define RID_SIM_START (RID_OBJ_START+ 0) -#define RID_SIM_END (RID_OBJ_START+ 255) - -#define RID_SMA_START (RID_OBJ_START+ 256) -#define RID_SMA_END (RID_OBJ_START+ 511) - -#define RID_SCH_START (RID_OBJ_START+ 512) -#define RID_SCH_END (RID_OBJ_START+ 767) - -#define RID_RPT_START (RID_OBJ_START+768) -#define RID_RPT_END (RID_OBJ_START+1000) - -#define RID_FORMULA_START (RID_OBJ_START+1001) -#define RID_FORMULA_END (RID_OBJ_START+1200) -// Help-Ids -------------------------------------------------------------- - -#define HID_OK_BUTTON 0 -#define HID_CANCEL_BUTTON 0 -#define HID_HELP_BUTTON 0 - -#define HID_START 32768 - -#define HID_VCL_START (HID_START+100) -#define HID_VCL_END (HID_START+150) - -#define HID_SVTOOLS_START (HID_START+200) -#define HID_SVTOOLS_END (HID_START+299) - -#define HID_SFX_START (HID_START+300) -#define HID_SFX_END (HID_START+999) - -#define HID_LIB_START (HID_START+1000) -#define HID_LIB_END (HID_START+19999) - -#define HID_SVX_START (HID_LIB_START) -#define HID_SVX_END (HID_LIB_START+431) - -#define HID_WIZARD_START (HID_LIB_START+432) -#define HID_WIZARD_END (HID_LIB_START+999) -//please note: There is also HID_WIZARD2 below - -// FREE - -#define HID_CUI_START (HID_LIB_START+1100) -#define HID_CUI_END (HID_LIB_START+1699) - -#define HID_OFA_START (HID_LIB_START+1760) -#define HID_OFA_END (HID_LIB_START+1999) - -#define HID_HELP_START (HID_LIB_START+2000) -#define HID_HELP_END (HID_LIB_START+2050) - -#define HID_CHAOS_START (HID_LIB_START+2051) -#define HID_CHAOS_END (HID_LIB_START+2069) - -#define HID_UUI_START (HID_LIB_START+2070) -#define HID_UUI_END (HID_LIB_START+2099) - -#define HID_GOODIES_START (HID_LIB_START+2100) -#define HID_GOODIES_END (HID_LIB_START+2199) - -#if 0 // currently unused range -#define HID_SCHEDULE_START (HID_LIB_START+2200) -#define HID_SCHEDULE_END (HID_LIB_START+3399) -#endif - -#define HID_CHANNEL_START (HID_LIB_START+3400) -#define HID_CHANNEL_END (HID_LIB_START+3499) - -#define HID_SBA_START (HID_LIB_START+ 3500) -#define HID_SBA_END (HID_LIB_START+ 3999) - -#define HID_FORMS_START (HID_LIB_START+4000) -#define HID_FORMS_END (HID_LIB_START+4999) - -#define HID_DBACCESS_START (HID_LIB_START+5000) -#define HID_DBACCESS_END (HID_LIB_START+5299) - -#define HID_PORTAL_START (HID_LIB_START+5300) -#define HID_PORTAL_END (HID_LIB_START+5599) - -#define HID_PORTAL_ADMIN_START (HID_LIB_START+5600) -#define HID_PORTAL_ADMIN_END (HID_LIB_START+5999) - -#define HID_SYNCACCESS_START (HID_LIB_START+6000) -#define HID_SYNCACCESS_END (HID_LIB_START+6099) - -#define HID_SVX_EXT0_START (HID_LIB_START+6100) -#define HID_SVX_EXT0_END (HID_LIB_START+6599) - -#define HID_FRAMEWORK_START (HID_LIB_START+6600) -#define HID_FRAMEWORK_END (HID_LIB_START+6999) - -#define HID_WIZARD2_START (HID_LIB_START+7000) -#define HID_WIZARD2_END (HID_LIB_START+8999) - -#define HID_DESKTOP_START (HID_LIB_START+9000) -#define HID_DESKTOP_END (HID_LIB_START+9299) - -#define HID_XMLSECURITY_START (HID_LIB_START+9300) -#define HID_XMLSECURITY_END (HID_LIB_START+9999) - -#define HID_APP_START (HID_START+20000) -#define HID_APP_END (HID_START+29999) - -#define HID_SW_START (HID_START+20000) -#define HID_SW_END (HID_START+24999) - -#define HID_SC_START (HID_START+25000) -#define HID_SC_END (HID_START+26999) - -#define HID_SD_START (HID_START+27000) -#define HID_SD_END (HID_START+27999) - -#define HID_Sa_START (HID_START+28000) -#define HID_Sa_END (HID_START+28999) - -#define HID_Sb_START (HID_START+29000) -#define HID_Sb_END (HID_START+29999) - -#define HID_OBJ_START (HID_START+30000) -#define HID_OBJ_END (HID_START+32767) - -#define HID_CUI3_START (HID_OBJ_START+ 0) -#define HID_CUI3_END (HID_OBJ_START+ 239) - -#define HID_AVMEDIA_START (HID_OBJ_START+ 240) -#define HID_AVMEDIA_END (HID_OBJ_START+ 255) - -#define HID_SMA_START (HID_OBJ_START+ 256) -#define HID_SMA_END (HID_OBJ_START+ 511) - -#define HID_SCH_START (HID_OBJ_START+ 512) -#define HID_SCH_END (HID_OBJ_START+ 767) - -#define HID_BASICIDE_START (HID_OBJ_START+ 768) -#define HID_BASICIDE_END (HID_OBJ_START+1023) - -#define HID_SMA2_START (HID_OBJ_START+1024) -#define HID_SMA2_END (HID_OBJ_START+1280) - -#define HID_FILTER_START (HID_OBJ_START+1281) -#define HID_FILTER_END (HID_OBJ_START+1580) - -#define HID_LICENSING_START (HID_OBJ_START+1581) -#define HID_LICENSING_END (HID_OBJ_START+1680) - -#define HID_RPT_START (HID_OBJ_START+1681) -#define HID_RPT_END (HID_OBJ_START+2080) - -#define HID_FORMULA_START (HID_OBJ_START+2081) -#define HID_FORMULA_END (HID_OBJ_START+2280) - -#define HID_EXTENSIONS_START (HID_OBJ_START+2281) -#define HID_EXTENSIONS_END (HID_OBJ_START+2800) - -#endif - diff --git a/vcl/inc/vcl/svids.hrc b/vcl/inc/vcl/svids.hrc index 695fa6f849e8..e2a8226ac878 100644 --- a/vcl/inc/vcl/svids.hrc +++ b/vcl/inc/vcl/svids.hrc @@ -31,7 +31,7 @@ #ifndef _SV_SVIDS_HRC #define _SV_SVIDS_HRC -#include "vcl/solar.hrc" +#include "svl/solar.hrc" #define SV_RESID_STDOFFSET 0 #define SV_RESID_WINOFFSET 1 diff --git a/vcl/prj/build.lst b/vcl/prj/build.lst index 5d2aaf90c6f7..cf2824f72942 100644 --- a/vcl/prj/build.lst +++ b/vcl/prj/build.lst @@ -1,4 +1,4 @@ -vc vcl : l10n apple_remote BOOST:boost rsc sot ucbhelper unotools ICU:icu GRAPHITE:graphite i18npool i18nutil unoil ridljar X11_EXTENSIONS:x11_extensions offuh basegfx basebmp tools transex3 icc SO:print_header cpputools shell NULL +vc vcl : l10n apple_remote BOOST:boost rsc sot ucbhelper unotools ICU:icu GRAPHITE:graphite i18npool i18nutil unoil ridljar X11_EXTENSIONS:x11_extensions offuh basegfx basebmp tools transex3 icc SO:print_header cpputools shell svl NULL vc vcl usr1 - all vc_mkout NULL vc vcl\inc nmake - all vc_inc NULL vc vcl\source\glyphs nmake - all vc_glyphs vc_inc NULL diff --git a/vcl/prj/d.lst b/vcl/prj/d.lst index afe8a5808be7..b106ff73729e 100644 --- a/vcl/prj/d.lst +++ b/vcl/prj/d.lst @@ -13,7 +13,6 @@ mkdir: %_DEST%\inc%_EXT%\vcl ..\%__SRC%\obj\salmain.obj %_DEST%\lib%_EXT%\salmain.obj ..\%__SRC%\obj\salmain.o %_DEST%\lib%_EXT%\salmain.o -..\inc\vcl\solar.hrc %_DEST%\inc%_EXT%\vcl\solar.hrc ..\inc\vcl\accel.hxx %_DEST%\inc%_EXT%\vcl\accel.hxx ..\inc\vcl\alpha.hxx %_DEST%\inc%_EXT%\vcl\alpha.hxx ..\inc\vcl\animate.hxx %_DEST%\inc%_EXT%\vcl\animate.hxx -- cgit From a2637545e1419956096899a82a9c79511d83fbc5 Mon Sep 17 00:00:00 2001 From: "Philipp Lohmann [pl]" Date: Fri, 15 Jan 2010 00:20:57 +0100 Subject: solve some merge problems --- vcl/source/gdi/makefile.mk | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/vcl/source/gdi/makefile.mk b/vcl/source/gdi/makefile.mk index 9e4047d63e82..ed2a9b2ba1e1 100755 --- a/vcl/source/gdi/makefile.mk +++ b/vcl/source/gdi/makefile.mk @@ -58,6 +58,7 @@ EXCEPTIONSFILES= $(SLO)$/salmisc.obj \ $(SLO)$/print.obj \ $(SLO)$/print2.obj \ $(SLO)$/print3.obj \ + $(SLO)$/oldprintadaptor.obj \ $(SLO)$/configsettings.obj \ $(SLO)$/sallayout.obj \ $(SLO)$/image.obj \ @@ -73,7 +74,6 @@ EXCEPTIONSFILES= $(SLO)$/salmisc.obj \ $(SLO)$/pngread.obj \ $(SLO)$/pngwrite.obj \ $(SLO)$/virdev.obj \ - $(SLO)$/impprn.obj \ $(SLO)$/gdimtf.obj \ $(SLO)$/graphictools.obj \ $(SLO)$/textlayout.obj \ @@ -105,7 +105,6 @@ SLOFILES= $(EXCEPTIONSFILES) \ $(SLO)$/mapmod.obj \ $(SLO)$/metaact.obj \ $(SLO)$/octree.obj \ - $(SLO)$/oldprintadaptor.obj \ $(SLO)$/outmap.obj \ $(SLO)$/outdev2.obj \ $(SLO)$/outdev4.obj \ @@ -118,11 +117,7 @@ SLOFILES= $(EXCEPTIONSFILES) \ $(SLO)$/pdfwriter.obj \ $(SLO)$/salgdilayout.obj \ $(SLO)$/extoutdevdata.obj \ - $(SLO)$/salnativewidgets-none.obj \ - $(SLO)$/bmpconv.obj \ - $(SLO)$/pngread.obj \ - $(SLO)$/pngwrite.obj \ - $(SLO)$/graphictools.obj + $(SLO)$/salnativewidgets-none.obj # --- Targets ------------------------------------------------------ -- cgit From c979003e3c9601f525011341c322ba2c27e2a0da Mon Sep 17 00:00:00 2001 From: Kurt Zenker Date: Mon, 18 Jan 2010 15:07:17 +0100 Subject: masterfix: #i10000# use typeinfo instead of typeinfo.h which cause an error on mac --- comphelper/source/property/property.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/comphelper/source/property/property.cxx b/comphelper/source/property/property.cxx index 17949b9889dd..0ccc28d4238b 100644 --- a/comphelper/source/property/property.cxx +++ b/comphelper/source/property/property.cxx @@ -42,7 +42,7 @@ #include #include #include - #include + #include #endif #include #include -- cgit From 7f5f6c30e89c27422a1576ccceb9b0d79c8e3f0d Mon Sep 17 00:00:00 2001 From: Kurt Zenker Date: Mon, 18 Jan 2010 15:24:16 +0100 Subject: masterfix: #i10000# use SvMemoryStream::GetEndOfData() instead of SvMemoryStream::GetSize() --- goodies/source/filter.vcl/ieps/ieps.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/goodies/source/filter.vcl/ieps/ieps.cxx b/goodies/source/filter.vcl/ieps/ieps.cxx index 742985904ce8..7f1ecfc65bd0 100644 --- a/goodies/source/filter.vcl/ieps/ieps.cxx +++ b/goodies/source/filter.vcl/ieps/ieps.cxx @@ -293,7 +293,7 @@ static bool RenderAsPNGThroughHelper(const sal_uInt8* pBuf, sal_uInt32 nBytesRea aMemStm.Seek(0); if ( - aMemStm.GetSize() && + aMemStm.GetEndOfData() && GraphicConverter::Import(aMemStm, rGraphic, CVT_PNG) == ERRCODE_NONE ) { -- cgit From 37375c0464d0912ea7b173a99f9cbbc47bd93de4 Mon Sep 17 00:00:00 2001 From: Caolán McNamara Date: Mon, 18 Jan 2010 15:37:42 +0000 Subject: s390xport02: #i108410# different results for s390x --- basegfx/test/basegfx2d.cxx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/basegfx/test/basegfx2d.cxx b/basegfx/test/basegfx2d.cxx index 1bd15702e143..61c02e8ccdd2 100644 --- a/basegfx/test/basegfx2d.cxx +++ b/basegfx/test/basegfx2d.cxx @@ -490,7 +490,12 @@ public: // fTools::equal, linux and mac produce more 'C' than 'S' statements, while WIN32 // uses more 'S' statements (as it should be for circles) CPPUNIT_ASSERT_MESSAGE("exporting to circle does not produce the expected number of coordinates", - nCount==67 || nCount==50); +#ifdef S390X + nCount==61 +#else + nCount==67 || nCount==50 +#endif + ); const B2DPolygon aRect( tools::createPolygonFromRect( B2DRange(0.0,0.0,4000.0,4000.0) )); -- cgit From 54311d2499a8502ea3a827347992c2f4d6e40d31 Mon Sep 17 00:00:00 2001 From: Ivo Hinkelmann Date: Fri, 22 Jan 2010 18:50:33 +0100 Subject: cws l10ntools: #i107386# #i107993# #ii107992# #i107991# #i108587# Added some buildtypes , fix for broken localize_sl regarding UPDMINOREXT , pmladeks localize.pl ooo enforcer patch --- transex3/prj/build.lst | 2 +- transex3/scripts/localize.pl | 13 ++++++++++--- transex3/source/localize.cxx | 17 ++++++++++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/transex3/prj/build.lst b/transex3/prj/build.lst index 0017471af134..685686192daf 100644 --- a/transex3/prj/build.lst +++ b/transex3/prj/build.lst @@ -1,4 +1,4 @@ -tr transex3 : tools libxslt berkeleydb LUCENE:lucene NULL +tr transex3 : tools LIBXSLT:libxslt BERKELEYDB:berkeleydb LUCENE:lucene NULL tr transex3 usr1 - all tr_mkout NULL tr transex3\inc nmake - all tr_inc NULL tr transex3\source nmake - all tr_src tr_inc NULL diff --git a/transex3/scripts/localize.pl b/transex3/scripts/localize.pl index 10e8124027b1..0f6a19effc38 100755 --- a/transex3/scripts/localize.pl +++ b/transex3/scripts/localize.pl @@ -78,6 +78,7 @@ my $WIN; my $languages; #my %sl_modules; # Contains all modules where en-US and de is source language my $use_default_date = '0'; +my $force_ooo_module = '0'; my %is_ooo_module; my %is_so_module; my $DELIMITER; @@ -275,7 +276,7 @@ sub check_modules_scm sub is_openoffice_module { my $module = shift; - return "TRUE", if defined $is_ooo_module{ $module }; + return "TRUE", if ( $force_ooo_module || defined $is_ooo_module{ $module } ); return ""; } @@ -1114,7 +1115,7 @@ sub parse_options{ my $extract; my $success = GetOptions('f=s' => \$sdffile , 'l=s' => \$languages , 's=s' => \$srcpath , 'h' => \$help , 'v' => \$bVerbose , 'm' => \$merge , 'e' => \$extract , 'x' => \$no_sort , 'd' => \$use_default_date , 'c' => \$create_dirs , - 'n' => \$no_gsicheck ); + 'n' => \$no_gsicheck , 'o' => \$force_ooo_module ); $outputfile = $sdffile; #print STDOUT "DBG: lang = $languages\n"; @@ -1126,7 +1127,11 @@ sub parse_options{ exit(1); } } - if( $help || !$success || $#ARGV > 1 || ( !$sdffile ) ){ + if( $help ){ + usage(); + exit(0); + } + if( !$success || $#ARGV > 1 || ( !$sdffile ) ){ usage(); exit(1); } @@ -1167,6 +1172,8 @@ sub usage{ print STDERR " -h File with localize.sdf's\n!"; print STDERR " -n No gsicheck\n"; print STDERR " -i Module to merge\n"; + print STDERR " -o force using ooo localization from the l10n module instead of l10n_so; \n"; + print STDERR " useful if the type can't be detected by the .svn tags; \n"; print STDERR " -v Verbose\n"; print STDERR "\nExample:\n"; print STDERR "\nlocalize -e -l en-US,pt-BR=en-US -f my.sdf\n( Extract en-US and pt-BR with en-US fallback )\n"; diff --git a/transex3/source/localize.cxx b/transex3/source/localize.cxx index c82d152cac7e..e23165ee657c 100644 --- a/transex3/source/localize.cxx +++ b/transex3/source/localize.cxx @@ -938,10 +938,25 @@ int _cdecl main( int argc, char *argv[] ) bool hasPwd = treeconfig.getActiveRepositories( repos ); if( hasPwd ) cout << "Found special path!\n"; + string minor_ext; + bool has_minor_ext; + + if( Export::GetEnv("UPDMINOREXT") != NULL ) + { + minor_ext = string( Export::GetEnv("UPDMINOREXT") ); + has_minor_ext = minor_ext.size(); + } + else + has_minor_ext = false; + // localize through all repositories for( vector::iterator iter = repos.begin(); iter != repos.end() ; ++iter ) { - string curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter; + string curRepository; + if( has_minor_ext ) + curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter + minor_ext; + else + curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter; cout << "Localizing repository " << curRepository << "\n"; SourceTreeLocalizer aIter( ByteString( curRepository.c_str() ) , sVersion , (sOutput.Len() > 0) , bQuiet2 , bSkipLinks ); aIter.SetLanguageRestriction( sLanguages ); -- cgit From 8316671089f33c8aba5c5e72348854de16df9379 Mon Sep 17 00:00:00 2001 From: Ivo Hinkelmann Date: Mon, 25 Jan 2010 17:20:55 +0100 Subject: l10ntools: #i108657# rename transex3 to l10ntools --- l10ntools/inc/cfgmerge.hxx | 208 ++ l10ntools/inc/export.hxx | 586 +++++ l10ntools/inc/gsicheck.hxx | 131 + l10ntools/inc/helpmerge.hxx | 87 + l10ntools/inc/inireader.hxx | 52 + l10ntools/inc/l10ntools/directory.hxx | 54 + l10ntools/inc/l10ntools/file.hxx | 23 + l10ntools/inc/l10ntools/vosapp.hxx | 33 + l10ntools/inc/lngmerge.hxx | 69 + l10ntools/inc/makefile.mk | 51 + l10ntools/inc/pch/precompiled_l10ntools.cxx | 32 + l10ntools/inc/pch/precompiled_l10ntools.hxx | 35 + l10ntools/inc/srciter.hxx | 61 + l10ntools/inc/tagtest.hxx | 399 +++ l10ntools/inc/tokens.h | 112 + l10ntools/inc/treeconfig.hxx | 28 + l10ntools/inc/utf8conv.hxx | 47 + l10ntools/inc/wrdtrans.hxx | 90 + l10ntools/inc/wtranode.hxx | 121 + l10ntools/inc/wtratree.hxx | 162 ++ l10ntools/inc/xmlparse.hxx | 553 ++++ l10ntools/inc/xmlutil.hxx | 9 + l10ntools/inc/xrmmerge.hxx | 161 ++ l10ntools/java/l10nconv/build.xml | 233 ++ l10ntools/java/l10nconv/converter.MF | 1 + .../l10nconv/documentation/readmeConverter.sxw | Bin 0 -> 9824 bytes .../star/tooling/DirtyTags/DirtyTagWrapCheck.java | 85 + .../star/tooling/DirtyTags/DirtyTagWrapper.java | 252 ++ .../java/com/sun/star/tooling/DirtyTags/Tag.java | 249 ++ .../com/sun/star/tooling/DirtyTags/TagPair.java | 310 +++ .../com/sun/star/tooling/converter/Convert.java | 553 ++++ .../com/sun/star/tooling/converter/Converter.java | 523 ++++ .../star/tooling/converter/ConverterException.java | 79 + .../sun/star/tooling/converter/DataHandler.java | 149 ++ .../com/sun/star/tooling/converter/DataReader.java | 79 + .../com/sun/star/tooling/converter/DataWriter.java | 91 + .../com/sun/star/tooling/converter/ExtMap.java | 97 + .../com/sun/star/tooling/converter/FileMaker.java | 87 + .../com/sun/star/tooling/converter/GSIReader.java | 250 ++ .../com/sun/star/tooling/converter/GSIWriter.java | 246 ++ .../star/tooling/converter/GSIandSDFMerger.java | 167 ++ .../star/tooling/converter/LineErrorException.java | 81 + .../sun/star/tooling/converter/OutputHandler.java | 228 ++ .../star/tooling/converter/ResTypeResolver.java | 71 + .../com/sun/star/tooling/converter/Resolver.java | 98 + .../com/sun/star/tooling/converter/SDFReader.java | 635 +++++ .../com/sun/star/tooling/converter/SDFWriter.java | 175 ++ .../sun/star/tooling/converter/XLIFFReader.java | 745 ++++++ .../sun/star/tooling/converter/XLIFFWriter.java | 535 ++++ .../com/sun/star/tooling/converter/dtd/xliff.dtd | 391 +++ .../tooling/languageResolver/LanguageResolver.java | 201 ++ .../com/sun/star/tooling/languageResolver/lang.map | 41 + l10ntools/java/l10nconv/makefile.mk | 39 + l10ntools/java/receditor/build.xml | 173 ++ .../java/transex3/controller/EditorController.java | 334 +++ .../receditor/java/transex3/controller/Main.java | 10 + .../java/transex3/model/ResourceFile.java | 77 + .../receditor/java/transex3/model/SdfEntity.java | 211 ++ .../receditor/java/transex3/model/SdfString.java | 192 ++ .../java/receditor/java/transex3/view/Editor.java | 97 + .../receditor/java/transex3/view/SdfTable.java | 24 + l10ntools/java/receditor/makefile.mk | 39 + l10ntools/java/receditor/receditor.MF | 1 + l10ntools/layout/README | 27 + l10ntools/layout/layoutparse.cxx | 139 + l10ntools/layout/layoutparse.hxx | 55 + l10ntools/layout/loc.sdf | 24 + l10ntools/layout/makefile.mk | 81 + l10ntools/layout/tralay.cxx | 403 +++ l10ntools/layout/zoom.xml | 40 + l10ntools/prj/build.lst | 10 + l10ntools/prj/d.lst | 61 + l10ntools/scripts/fast_merge.pl | 348 +++ l10ntools/scripts/keyidGen.pl | 189 ++ l10ntools/scripts/localize.pl | 1201 +++++++++ l10ntools/scripts/localize_old.pl | 1130 +++++++++ l10ntools/source/cfg_yy_wrapper.c | 2 + l10ntools/source/cfglex.l | 232 ++ l10ntools/source/cfgmerge.cxx | 886 +++++++ l10ntools/source/directory.cxx | 276 ++ l10ntools/source/export.cxx | 2660 ++++++++++++++++++++ l10ntools/source/export2.cxx | 741 ++++++ l10ntools/source/file.cxx | 58 + l10ntools/source/filter/merge/FCFGMerge.cfg | 125 + l10ntools/source/filter/merge/FCFGMerge.java | 131 + l10ntools/source/filter/merge/Manifest.mf | 1 + l10ntools/source/filter/merge/Merger.java | 364 +++ l10ntools/source/filter/merge/makefile.mk | 96 + .../source/filter/utils/AnalyzeStartupLog.java | 328 +++ l10ntools/source/filter/utils/Cache.java | 2449 ++++++++++++++++++ l10ntools/source/filter/utils/ConfigHelper.java | 303 +++ l10ntools/source/filter/utils/FileHelper.java | 766 ++++++ l10ntools/source/filter/utils/Logger.java | 177 ++ .../utils/MalformedCommandLineException.java | 50 + l10ntools/source/filter/utils/XMLHelper.java | 825 ++++++ l10ntools/source/filter/utils/makefile.mk | 57 + l10ntools/source/gsicheck.cxx | 1177 +++++++++ l10ntools/source/gsiconv.cxx | 372 +++ l10ntools/source/help/HelpCompiler.cxx | 593 +++++ l10ntools/source/help/HelpCompiler.hxx | 320 +++ l10ntools/source/help/HelpFileDocument.java | 89 + l10ntools/source/help/HelpIndexerTool.java | 372 +++ l10ntools/source/help/HelpLinker.cxx | 1173 +++++++++ l10ntools/source/help/compilehelp.hxx | 81 + l10ntools/source/help/helplinker.pmk | 35 + l10ntools/source/help/makefile.mk | 120 + l10ntools/source/helpex.cxx | 299 +++ l10ntools/source/helpmerge.cxx | 730 ++++++ l10ntools/source/inireader.cxx | 132 + l10ntools/source/lngex.cxx | 226 ++ l10ntools/source/lngmerge.cxx | 360 +++ l10ntools/source/localize.cxx | 986 ++++++++ l10ntools/source/makefile.mk | 210 ++ l10ntools/source/merge.cxx | 445 ++++ l10ntools/source/src_yy_wrapper.c | 2 + l10ntools/source/srciter.cxx | 141 ++ l10ntools/source/srclex.l | 308 +++ l10ntools/source/tagtest.cxx | 1577 ++++++++++++ l10ntools/source/treeconfig.cxx | 128 + l10ntools/source/utf8conv.cxx | 77 + l10ntools/source/wrdtrans.cxx | 248 ++ l10ntools/source/wtranode.cxx | 111 + l10ntools/source/wtratree.cxx | 421 ++++ l10ntools/source/xgfconv.cxx | 66 + l10ntools/source/xmlparse.cxx | 1456 +++++++++++ l10ntools/source/xrm_yy_wrapper.c | 2 + l10ntools/source/xrmlex.l | 228 ++ l10ntools/source/xrmmerge.cxx | 754 ++++++ l10ntools/workbench/gsicheck_errors.sdf | 15 + l10ntools/workbench/gsicheck_errors_err-.sdf | 11 + l10ntools/workbench/gsicheck_errors_err-l.sdf | 2 + l10ntools/workbench/gsicheck_errors_err-s.sdf | 9 + l10ntools/workbench/gsicheck_errors_err-t.sdf | 9 + l10ntools/workbench/gsicheck_errors_ok-.sdf | 5 + l10ntools/workbench/gsicheck_errors_ok-l.sdf | 12 + l10ntools/workbench/gsicheck_errors_ok-s.sdf | 6 + l10ntools/workbench/gsicheck_errors_ok-t.sdf | 6 + l10ntools/workbench/gsicheckcheck.btm | 17 + transex3/inc/cfgmerge.hxx | 208 -- transex3/inc/export.hxx | 586 ----- transex3/inc/gsicheck.hxx | 131 - transex3/inc/helpmerge.hxx | 87 - transex3/inc/inireader.hxx | 52 - transex3/inc/lngmerge.hxx | 69 - transex3/inc/makefile.mk | 51 - transex3/inc/pch/precompiled_transex3.cxx | 32 - transex3/inc/pch/precompiled_transex3.hxx | 35 - transex3/inc/srciter.hxx | 61 - transex3/inc/tagtest.hxx | 399 --- transex3/inc/tokens.h | 112 - transex3/inc/transex3/directory.hxx | 54 - transex3/inc/transex3/file.hxx | 23 - transex3/inc/transex3/vosapp.hxx | 33 - transex3/inc/treeconfig.hxx | 28 - transex3/inc/utf8conv.hxx | 47 - transex3/inc/wrdtrans.hxx | 90 - transex3/inc/wtranode.hxx | 121 - transex3/inc/wtratree.hxx | 162 -- transex3/inc/xmlparse.hxx | 553 ---- transex3/inc/xmlutil.hxx | 9 - transex3/inc/xrmmerge.hxx | 161 -- transex3/java/l10nconv/build.xml | 233 -- transex3/java/l10nconv/converter.MF | 1 - .../l10nconv/documentation/readmeConverter.sxw | Bin 9824 -> 0 bytes .../star/tooling/DirtyTags/DirtyTagWrapCheck.java | 85 - .../star/tooling/DirtyTags/DirtyTagWrapper.java | 252 -- .../java/com/sun/star/tooling/DirtyTags/Tag.java | 249 -- .../com/sun/star/tooling/DirtyTags/TagPair.java | 310 --- .../com/sun/star/tooling/converter/Convert.java | 553 ---- .../com/sun/star/tooling/converter/Converter.java | 523 ---- .../star/tooling/converter/ConverterException.java | 79 - .../sun/star/tooling/converter/DataHandler.java | 149 -- .../com/sun/star/tooling/converter/DataReader.java | 79 - .../com/sun/star/tooling/converter/DataWriter.java | 91 - .../com/sun/star/tooling/converter/ExtMap.java | 97 - .../com/sun/star/tooling/converter/FileMaker.java | 87 - .../com/sun/star/tooling/converter/GSIReader.java | 250 -- .../com/sun/star/tooling/converter/GSIWriter.java | 246 -- .../star/tooling/converter/GSIandSDFMerger.java | 167 -- .../star/tooling/converter/LineErrorException.java | 81 - .../sun/star/tooling/converter/OutputHandler.java | 228 -- .../star/tooling/converter/ResTypeResolver.java | 71 - .../com/sun/star/tooling/converter/Resolver.java | 98 - .../com/sun/star/tooling/converter/SDFReader.java | 635 ----- .../com/sun/star/tooling/converter/SDFWriter.java | 175 -- .../sun/star/tooling/converter/XLIFFReader.java | 745 ------ .../sun/star/tooling/converter/XLIFFWriter.java | 535 ---- .../com/sun/star/tooling/converter/dtd/xliff.dtd | 391 --- .../tooling/languageResolver/LanguageResolver.java | 201 -- .../com/sun/star/tooling/languageResolver/lang.map | 41 - transex3/java/l10nconv/makefile.mk | 39 - transex3/java/receditor/build.xml | 173 -- .../java/transex3/controller/EditorController.java | 334 --- .../receditor/java/transex3/controller/Main.java | 10 - .../java/transex3/model/ResourceFile.java | 77 - .../receditor/java/transex3/model/SdfEntity.java | 211 -- .../receditor/java/transex3/model/SdfString.java | 192 -- .../java/receditor/java/transex3/view/Editor.java | 97 - .../receditor/java/transex3/view/SdfTable.java | 24 - transex3/java/receditor/makefile.mk | 39 - transex3/java/receditor/receditor.MF | 1 - transex3/layout/README | 27 - transex3/layout/layoutparse.cxx | 139 - transex3/layout/layoutparse.hxx | 55 - transex3/layout/loc.sdf | 24 - transex3/layout/makefile.mk | 81 - transex3/layout/tralay.cxx | 403 --- transex3/layout/zoom.xml | 40 - transex3/prj/build.lst | 10 - transex3/prj/d.lst | 61 - transex3/scripts/fast_merge.pl | 348 --- transex3/scripts/keyidGen.pl | 189 -- transex3/scripts/localize.pl | 1201 --------- transex3/scripts/localize_old.pl | 1130 --------- transex3/source/cfg_yy_wrapper.c | 2 - transex3/source/cfglex.l | 232 -- transex3/source/cfgmerge.cxx | 886 ------- transex3/source/directory.cxx | 276 -- transex3/source/export.cxx | 2660 -------------------- transex3/source/export2.cxx | 741 ------ transex3/source/file.cxx | 58 - transex3/source/filter/merge/FCFGMerge.cfg | 125 - transex3/source/filter/merge/FCFGMerge.java | 131 - transex3/source/filter/merge/Manifest.mf | 1 - transex3/source/filter/merge/Merger.java | 364 --- transex3/source/filter/merge/makefile.mk | 96 - .../source/filter/utils/AnalyzeStartupLog.java | 328 --- transex3/source/filter/utils/Cache.java | 2449 ------------------ transex3/source/filter/utils/ConfigHelper.java | 303 --- transex3/source/filter/utils/FileHelper.java | 766 ------ transex3/source/filter/utils/Logger.java | 177 -- .../utils/MalformedCommandLineException.java | 50 - transex3/source/filter/utils/XMLHelper.java | 825 ------ transex3/source/filter/utils/makefile.mk | 57 - transex3/source/gsicheck.cxx | 1177 --------- transex3/source/gsiconv.cxx | 372 --- transex3/source/help/HelpCompiler.cxx | 593 ----- transex3/source/help/HelpCompiler.hxx | 320 --- transex3/source/help/HelpFileDocument.java | 89 - transex3/source/help/HelpIndexerTool.java | 372 --- transex3/source/help/HelpLinker.cxx | 1173 --------- transex3/source/help/compilehelp.hxx | 81 - transex3/source/help/helplinker.pmk | 35 - transex3/source/help/makefile.mk | 120 - transex3/source/helpex.cxx | 299 --- transex3/source/helpmerge.cxx | 730 ------ transex3/source/inireader.cxx | 132 - transex3/source/lngex.cxx | 226 -- transex3/source/lngmerge.cxx | 360 --- transex3/source/localize.cxx | 986 -------- transex3/source/makefile.mk | 210 -- transex3/source/merge.cxx | 445 ---- transex3/source/src_yy_wrapper.c | 2 - transex3/source/srciter.cxx | 141 -- transex3/source/srclex.l | 308 --- transex3/source/tagtest.cxx | 1577 ------------ transex3/source/treeconfig.cxx | 128 - transex3/source/utf8conv.cxx | 77 - transex3/source/wrdtrans.cxx | 248 -- transex3/source/wtranode.cxx | 111 - transex3/source/wtratree.cxx | 421 ---- transex3/source/xgfconv.cxx | 66 - transex3/source/xmlparse.cxx | 1456 ----------- transex3/source/xrm_yy_wrapper.c | 2 - transex3/source/xrmlex.l | 228 -- transex3/source/xrmmerge.cxx | 754 ------ transex3/workbench/gsicheck_errors.sdf | 15 - transex3/workbench/gsicheck_errors_err-.sdf | 11 - transex3/workbench/gsicheck_errors_err-l.sdf | 2 - transex3/workbench/gsicheck_errors_err-s.sdf | 9 - transex3/workbench/gsicheck_errors_err-t.sdf | 9 - transex3/workbench/gsicheck_errors_ok-.sdf | 5 - transex3/workbench/gsicheck_errors_ok-l.sdf | 12 - transex3/workbench/gsicheck_errors_ok-s.sdf | 6 - transex3/workbench/gsicheck_errors_ok-t.sdf | 6 - transex3/workbench/gsicheckcheck.btm | 17 - vcl/prj/build.lst | 2 +- 277 files changed, 38520 insertions(+), 38520 deletions(-) create mode 100644 l10ntools/inc/cfgmerge.hxx create mode 100644 l10ntools/inc/export.hxx create mode 100644 l10ntools/inc/gsicheck.hxx create mode 100644 l10ntools/inc/helpmerge.hxx create mode 100644 l10ntools/inc/inireader.hxx create mode 100644 l10ntools/inc/l10ntools/directory.hxx create mode 100644 l10ntools/inc/l10ntools/file.hxx create mode 100644 l10ntools/inc/l10ntools/vosapp.hxx create mode 100644 l10ntools/inc/lngmerge.hxx create mode 100644 l10ntools/inc/makefile.mk create mode 100644 l10ntools/inc/pch/precompiled_l10ntools.cxx create mode 100644 l10ntools/inc/pch/precompiled_l10ntools.hxx create mode 100644 l10ntools/inc/srciter.hxx create mode 100644 l10ntools/inc/tagtest.hxx create mode 100644 l10ntools/inc/tokens.h create mode 100644 l10ntools/inc/treeconfig.hxx create mode 100644 l10ntools/inc/utf8conv.hxx create mode 100644 l10ntools/inc/wrdtrans.hxx create mode 100644 l10ntools/inc/wtranode.hxx create mode 100644 l10ntools/inc/wtratree.hxx create mode 100644 l10ntools/inc/xmlparse.hxx create mode 100644 l10ntools/inc/xmlutil.hxx create mode 100644 l10ntools/inc/xrmmerge.hxx create mode 100755 l10ntools/java/l10nconv/build.xml create mode 100755 l10ntools/java/l10nconv/converter.MF create mode 100755 l10ntools/java/l10nconv/documentation/readmeConverter.sxw create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFReader.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java create mode 100755 l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map create mode 100755 l10ntools/java/l10nconv/makefile.mk create mode 100755 l10ntools/java/receditor/build.xml create mode 100644 l10ntools/java/receditor/java/transex3/controller/EditorController.java create mode 100644 l10ntools/java/receditor/java/transex3/controller/Main.java create mode 100644 l10ntools/java/receditor/java/transex3/model/ResourceFile.java create mode 100644 l10ntools/java/receditor/java/transex3/model/SdfEntity.java create mode 100644 l10ntools/java/receditor/java/transex3/model/SdfString.java create mode 100644 l10ntools/java/receditor/java/transex3/view/Editor.java create mode 100644 l10ntools/java/receditor/java/transex3/view/SdfTable.java create mode 100755 l10ntools/java/receditor/makefile.mk create mode 100755 l10ntools/java/receditor/receditor.MF create mode 100644 l10ntools/layout/README create mode 100644 l10ntools/layout/layoutparse.cxx create mode 100644 l10ntools/layout/layoutparse.hxx create mode 100644 l10ntools/layout/loc.sdf create mode 100644 l10ntools/layout/makefile.mk create mode 100644 l10ntools/layout/tralay.cxx create mode 100644 l10ntools/layout/zoom.xml create mode 100644 l10ntools/prj/build.lst create mode 100644 l10ntools/prj/d.lst create mode 100644 l10ntools/scripts/fast_merge.pl create mode 100644 l10ntools/scripts/keyidGen.pl create mode 100755 l10ntools/scripts/localize.pl create mode 100755 l10ntools/scripts/localize_old.pl create mode 100644 l10ntools/source/cfg_yy_wrapper.c create mode 100644 l10ntools/source/cfglex.l create mode 100644 l10ntools/source/cfgmerge.cxx create mode 100644 l10ntools/source/directory.cxx create mode 100644 l10ntools/source/export.cxx create mode 100644 l10ntools/source/export2.cxx create mode 100644 l10ntools/source/file.cxx create mode 100644 l10ntools/source/filter/merge/FCFGMerge.cfg create mode 100644 l10ntools/source/filter/merge/FCFGMerge.java create mode 100644 l10ntools/source/filter/merge/Manifest.mf create mode 100644 l10ntools/source/filter/merge/Merger.java create mode 100644 l10ntools/source/filter/merge/makefile.mk create mode 100644 l10ntools/source/filter/utils/AnalyzeStartupLog.java create mode 100644 l10ntools/source/filter/utils/Cache.java create mode 100644 l10ntools/source/filter/utils/ConfigHelper.java create mode 100644 l10ntools/source/filter/utils/FileHelper.java create mode 100644 l10ntools/source/filter/utils/Logger.java create mode 100644 l10ntools/source/filter/utils/MalformedCommandLineException.java create mode 100644 l10ntools/source/filter/utils/XMLHelper.java create mode 100644 l10ntools/source/filter/utils/makefile.mk create mode 100644 l10ntools/source/gsicheck.cxx create mode 100644 l10ntools/source/gsiconv.cxx create mode 100644 l10ntools/source/help/HelpCompiler.cxx create mode 100644 l10ntools/source/help/HelpCompiler.hxx create mode 100644 l10ntools/source/help/HelpFileDocument.java create mode 100644 l10ntools/source/help/HelpIndexerTool.java create mode 100644 l10ntools/source/help/HelpLinker.cxx create mode 100644 l10ntools/source/help/compilehelp.hxx create mode 100644 l10ntools/source/help/helplinker.pmk create mode 100644 l10ntools/source/help/makefile.mk create mode 100644 l10ntools/source/helpex.cxx create mode 100644 l10ntools/source/helpmerge.cxx create mode 100644 l10ntools/source/inireader.cxx create mode 100644 l10ntools/source/lngex.cxx create mode 100644 l10ntools/source/lngmerge.cxx create mode 100644 l10ntools/source/localize.cxx create mode 100644 l10ntools/source/makefile.mk create mode 100644 l10ntools/source/merge.cxx create mode 100644 l10ntools/source/src_yy_wrapper.c create mode 100644 l10ntools/source/srciter.cxx create mode 100644 l10ntools/source/srclex.l create mode 100644 l10ntools/source/tagtest.cxx create mode 100644 l10ntools/source/treeconfig.cxx create mode 100644 l10ntools/source/utf8conv.cxx create mode 100644 l10ntools/source/wrdtrans.cxx create mode 100644 l10ntools/source/wtranode.cxx create mode 100644 l10ntools/source/wtratree.cxx create mode 100644 l10ntools/source/xgfconv.cxx create mode 100644 l10ntools/source/xmlparse.cxx create mode 100644 l10ntools/source/xrm_yy_wrapper.c create mode 100644 l10ntools/source/xrmlex.l create mode 100644 l10ntools/source/xrmmerge.cxx create mode 100644 l10ntools/workbench/gsicheck_errors.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_err-.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_err-l.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_err-s.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_err-t.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_ok-.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_ok-l.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_ok-s.sdf create mode 100644 l10ntools/workbench/gsicheck_errors_ok-t.sdf create mode 100644 l10ntools/workbench/gsicheckcheck.btm delete mode 100644 transex3/inc/cfgmerge.hxx delete mode 100644 transex3/inc/export.hxx delete mode 100644 transex3/inc/gsicheck.hxx delete mode 100644 transex3/inc/helpmerge.hxx delete mode 100644 transex3/inc/inireader.hxx delete mode 100644 transex3/inc/lngmerge.hxx delete mode 100644 transex3/inc/makefile.mk delete mode 100644 transex3/inc/pch/precompiled_transex3.cxx delete mode 100644 transex3/inc/pch/precompiled_transex3.hxx delete mode 100644 transex3/inc/srciter.hxx delete mode 100644 transex3/inc/tagtest.hxx delete mode 100644 transex3/inc/tokens.h delete mode 100644 transex3/inc/transex3/directory.hxx delete mode 100644 transex3/inc/transex3/file.hxx delete mode 100644 transex3/inc/transex3/vosapp.hxx delete mode 100644 transex3/inc/treeconfig.hxx delete mode 100644 transex3/inc/utf8conv.hxx delete mode 100644 transex3/inc/wrdtrans.hxx delete mode 100644 transex3/inc/wtranode.hxx delete mode 100644 transex3/inc/wtratree.hxx delete mode 100644 transex3/inc/xmlparse.hxx delete mode 100644 transex3/inc/xmlutil.hxx delete mode 100644 transex3/inc/xrmmerge.hxx delete mode 100755 transex3/java/l10nconv/build.xml delete mode 100755 transex3/java/l10nconv/converter.MF delete mode 100755 transex3/java/l10nconv/documentation/readmeConverter.sxw delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFReader.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java delete mode 100755 transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map delete mode 100755 transex3/java/l10nconv/makefile.mk delete mode 100755 transex3/java/receditor/build.xml delete mode 100644 transex3/java/receditor/java/transex3/controller/EditorController.java delete mode 100644 transex3/java/receditor/java/transex3/controller/Main.java delete mode 100644 transex3/java/receditor/java/transex3/model/ResourceFile.java delete mode 100644 transex3/java/receditor/java/transex3/model/SdfEntity.java delete mode 100644 transex3/java/receditor/java/transex3/model/SdfString.java delete mode 100644 transex3/java/receditor/java/transex3/view/Editor.java delete mode 100644 transex3/java/receditor/java/transex3/view/SdfTable.java delete mode 100755 transex3/java/receditor/makefile.mk delete mode 100755 transex3/java/receditor/receditor.MF delete mode 100644 transex3/layout/README delete mode 100644 transex3/layout/layoutparse.cxx delete mode 100644 transex3/layout/layoutparse.hxx delete mode 100644 transex3/layout/loc.sdf delete mode 100644 transex3/layout/makefile.mk delete mode 100644 transex3/layout/tralay.cxx delete mode 100644 transex3/layout/zoom.xml delete mode 100644 transex3/prj/build.lst delete mode 100644 transex3/prj/d.lst delete mode 100644 transex3/scripts/fast_merge.pl delete mode 100644 transex3/scripts/keyidGen.pl delete mode 100755 transex3/scripts/localize.pl delete mode 100755 transex3/scripts/localize_old.pl delete mode 100644 transex3/source/cfg_yy_wrapper.c delete mode 100644 transex3/source/cfglex.l delete mode 100644 transex3/source/cfgmerge.cxx delete mode 100644 transex3/source/directory.cxx delete mode 100644 transex3/source/export.cxx delete mode 100644 transex3/source/export2.cxx delete mode 100644 transex3/source/file.cxx delete mode 100644 transex3/source/filter/merge/FCFGMerge.cfg delete mode 100644 transex3/source/filter/merge/FCFGMerge.java delete mode 100644 transex3/source/filter/merge/Manifest.mf delete mode 100644 transex3/source/filter/merge/Merger.java delete mode 100644 transex3/source/filter/merge/makefile.mk delete mode 100644 transex3/source/filter/utils/AnalyzeStartupLog.java delete mode 100644 transex3/source/filter/utils/Cache.java delete mode 100644 transex3/source/filter/utils/ConfigHelper.java delete mode 100644 transex3/source/filter/utils/FileHelper.java delete mode 100644 transex3/source/filter/utils/Logger.java delete mode 100644 transex3/source/filter/utils/MalformedCommandLineException.java delete mode 100644 transex3/source/filter/utils/XMLHelper.java delete mode 100644 transex3/source/filter/utils/makefile.mk delete mode 100644 transex3/source/gsicheck.cxx delete mode 100644 transex3/source/gsiconv.cxx delete mode 100644 transex3/source/help/HelpCompiler.cxx delete mode 100644 transex3/source/help/HelpCompiler.hxx delete mode 100644 transex3/source/help/HelpFileDocument.java delete mode 100644 transex3/source/help/HelpIndexerTool.java delete mode 100644 transex3/source/help/HelpLinker.cxx delete mode 100644 transex3/source/help/compilehelp.hxx delete mode 100644 transex3/source/help/helplinker.pmk delete mode 100644 transex3/source/help/makefile.mk delete mode 100644 transex3/source/helpex.cxx delete mode 100644 transex3/source/helpmerge.cxx delete mode 100644 transex3/source/inireader.cxx delete mode 100644 transex3/source/lngex.cxx delete mode 100644 transex3/source/lngmerge.cxx delete mode 100644 transex3/source/localize.cxx delete mode 100644 transex3/source/makefile.mk delete mode 100644 transex3/source/merge.cxx delete mode 100644 transex3/source/src_yy_wrapper.c delete mode 100644 transex3/source/srciter.cxx delete mode 100644 transex3/source/srclex.l delete mode 100644 transex3/source/tagtest.cxx delete mode 100644 transex3/source/treeconfig.cxx delete mode 100644 transex3/source/utf8conv.cxx delete mode 100644 transex3/source/wrdtrans.cxx delete mode 100644 transex3/source/wtranode.cxx delete mode 100644 transex3/source/wtratree.cxx delete mode 100644 transex3/source/xgfconv.cxx delete mode 100644 transex3/source/xmlparse.cxx delete mode 100644 transex3/source/xrm_yy_wrapper.c delete mode 100644 transex3/source/xrmlex.l delete mode 100644 transex3/source/xrmmerge.cxx delete mode 100644 transex3/workbench/gsicheck_errors.sdf delete mode 100644 transex3/workbench/gsicheck_errors_err-.sdf delete mode 100644 transex3/workbench/gsicheck_errors_err-l.sdf delete mode 100644 transex3/workbench/gsicheck_errors_err-s.sdf delete mode 100644 transex3/workbench/gsicheck_errors_err-t.sdf delete mode 100644 transex3/workbench/gsicheck_errors_ok-.sdf delete mode 100644 transex3/workbench/gsicheck_errors_ok-l.sdf delete mode 100644 transex3/workbench/gsicheck_errors_ok-s.sdf delete mode 100644 transex3/workbench/gsicheck_errors_ok-t.sdf delete mode 100644 transex3/workbench/gsicheckcheck.btm diff --git a/l10ntools/inc/cfgmerge.hxx b/l10ntools/inc/cfgmerge.hxx new file mode 100644 index 000000000000..9f1c97f05af5 --- /dev/null +++ b/l10ntools/inc/cfgmerge.hxx @@ -0,0 +1,208 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: cfgmerge.hxx,v $ + * $Revision: 1.8 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _CFG_MERGE_HXX +#define _CFG_MERGE_HXX + +#include +#include +#include + +typedef std::hash_map + ByteStringHashMap; + + +// +// class CfgStackData +// + +class CfgStackData +{ +friend class CfgParser; +friend class CfgExport; +friend class CfgMerge; +private: + ByteString sTagType; + ByteString sIdentifier; + + ByteString sResTyp; + + ByteString sTextTag; + ByteString sEndTextTag; + + ByteStringHashMap sText; +public: + CfgStackData( const ByteString &rTag, const ByteString &rId ) + : sTagType( rTag ), sIdentifier( rId ) {}; + + ByteString &GetTagType() { return sTagType; } + ByteString &GetIdentifier() { return sIdentifier; } + +}; + +// +// class CfgStack +// + +DECLARE_LIST( CfgStackList, CfgStackData * ) + +class CfgStack : public CfgStackList +{ +public: + CfgStack() : CfgStackList( 10, 10 ) {} + ~CfgStack(); + + ULONG Push( CfgStackData *pStackData ); + CfgStackData *Push( const ByteString &rTag, const ByteString &rId ); + CfgStackData *Pop() { return Remove( Count() - 1 ); } + + CfgStackData *GetStackData( ULONG nPos = LIST_APPEND ); + + ByteString GetAccessPath( ULONG nPos = LIST_APPEND ); +}; + +// +// class CfgParser +// + +class CfgParser +{ +protected: + ByteString sCurrentResTyp; + ByteString sCurrentIsoLang; + ByteString sCurrentText; + + ByteString sLastWhitespace; + + CfgStack aStack; + CfgStackData *pStackData; + + BOOL bLocalize; + + virtual void WorkOnText( + ByteString &rText, + const ByteString &nLangIndex )=0; + + virtual void WorkOnRessourceEnd()=0; + + virtual void Output( const ByteString& rOutput )=0; + + void Error( const ByteString &rError ); + +private: + int ExecuteAnalyzedToken( int nToken, char *pToken ); + std::vector aLanguages; + void AddText( + ByteString &rText, + const ByteString &rIsoLang, + const ByteString &rResTyp ); + +BOOL IsTokenClosed( const ByteString &rToken ); + +public: + CfgParser(); + virtual ~CfgParser(); + + int Execute( int nToken, char * pToken ); +}; + +// +// class CfgOutputParser +// + +class CfgOutputParser : public CfgParser +{ +protected: + SvFileStream *pOutputStream; +public: + CfgOutputParser ( const ByteString &rOutputFile ); + virtual ~CfgOutputParser(); +}; + +// +// class CfgExport +// + +class CfgExport : public CfgOutputParser +{ +private: + ByteString sPrj; + ByteString sPath; + std::vector aLanguages; +protected: + void WorkOnText( + ByteString &rText, + const ByteString &rIsoLang + ); + + void WorkOnRessourceEnd(); + void Output( const ByteString& rOutput ); +public: + CfgExport( + const ByteString &rOutputFile, + const ByteString &rProject, + const ByteString &rFilePath + ); + ~CfgExport(); +}; + +// +// class CfgMerge +// + +class CfgMerge : public CfgOutputParser +{ +private: + MergeDataFile *pMergeDataFile; + std::vector aLanguages; + ResData *pResData; + + BOOL bGerman; + ByteString sFilename; + BOOL bEnglish; + +protected: + void WorkOnText( + ByteString &rText, + const ByteString &nLangIndex ); + + void WorkOnRessourceEnd(); + + void Output( const ByteString& rOutput ); +public: + CfgMerge( + const ByteString &rMergeSource, + const ByteString &rOutputFile, + ByteString &rFilename + ); + ~CfgMerge(); +}; + +#endif diff --git a/l10ntools/inc/export.hxx b/l10ntools/inc/export.hxx new file mode 100644 index 000000000000..6d94297c25fb --- /dev/null +++ b/l10ntools/inc/export.hxx @@ -0,0 +1,586 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: export.hxx,v $ + * $Revision: 1.27 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _EXPORT_HXX +#define _EXPORT_HXX + +#ifndef L10NTOOLS_DIRECTORY_HXX +#define L10NTOOLS_DIRECTORY_HXX +#include +#endif + + +// #define MERGE_SOURCE_LANGUAGES <- To merge en-US and de resource + +#include +#include +#include +#include +#include +#include + +#include /* std::hashmap*/ +#include /* std::iterator*/ +#include /* std::set*/ +#include /* std::vector*/ +#include +#include + +#include +#ifdef WNT +#include +#endif + +#define NO_TRANSLATE_ISO "x-no-translate" + +#define JAPANESE_ISO "ja" + + +struct eqstr{ + BOOL operator()(const char* s1, const char* s2) const{ + return strcmp(s1,s2)==0; + } +}; + +struct equalByteString{ + bool operator()( const ByteString& rKey1, const ByteString& rKey2 ) const { + return rKey1.CompareTo( rKey2 )==COMPARE_EQUAL; + } +}; +struct lessByteString{ + bool operator()( const ByteString& rKey1, const ByteString& rKey2 ) const { + return rKey1.CompareTo( rKey2 )==COMPARE_LESS; + } +}; + +struct hashByteString{ + size_t operator()( const ByteString& rName ) const{ + std::hash< const char* > myHash; + return myHash( rName.GetBuffer() ); + } +}; + +class PFormEntrys; +class MergeData; +typedef std::set ByteStringSet; + +typedef std::hash_map + ByteStringHashMap; + +typedef std::hash_map + ByteStringBoolHashMap; + +typedef std::hash_map + PFormEntrysHashMap; + +typedef std::hash_map + MergeDataHashMap; + +#define SOURCE_LANGUAGE ByteString("en-US") +#define LIST_REFID "LIST_REFID" + +typedef ByteStringHashMap ExportListEntry; + +DECLARE_LIST( ExportListBase, ExportListEntry * ) + +// +// class ExportList +// + +class ExportList : public ExportListBase +{ +private: + ULONG nSourceLanguageListEntryCount; + +public: + ExportList() : ExportListBase() { nSourceLanguageListEntryCount = 0; } + ULONG GetSourceLanguageListEntryCount() { return nSourceLanguageListEntryCount; } + void NewSourceLanguageListEntry() { nSourceLanguageListEntryCount++; } +}; + +#define REFID_NONE 0xFFFF + +// +// struct ResData +// + +/****************************************************************************** +* Purpose: holds mandatory data to export a single res (used with ResStack) +******************************************************************************/ + +#define ID_LEVEL_NULL 0x0000 +#define ID_LEVEL_AUTOID 0x0001 +#define ID_LEVEL_TEXT 0x0002 +#define ID_LEVEL_FIELDNAME 0x0003 +#define ID_LEVEL_ACCESSPATH 0x0004 +#define ID_LEVEL_IDENTIFIER 0x0005 +#define ID_LEVEL_LISTINDEX 0x0006 + +class ResData +{ +public: + ~ResData(); + BOOL SetId( const ByteString &rId, USHORT nLevel ); + + USHORT nWidth; + USHORT nChildIndex; + USHORT nIdLevel; + BOOL bChild; + BOOL bChildWithText; + + BOOL bText; + BOOL bHelpText; + BOOL bQuickHelpText; + BOOL bTitle; + BOOL bList; + + BOOL bRestMerged; + + ByteString sResTyp; + ByteString sId; + ByteString sGId; + ByteString sHelpId; + ByteString sFilename; + + ByteStringHashMap sText; + USHORT nTextRefId; + + ByteStringHashMap sHelpText; + USHORT nHelpTextRefId; + + ByteStringHashMap sQuickHelpText; + USHORT nQuickHelpTextRefId; + + ByteStringHashMap sTitle; + USHORT nTitleRefId; + + ByteString sTextTyp; + ByteStringHashMap aFallbackData; + ByteStringHashMap aMergedLanguages; + + ExportList *pStringList; + ExportList *pUIEntries; + ExportList *pItemList; + ExportList *pFilterList; + ExportList *pPairedList; + + ByteString sPForm; + + void Dump(); + void addFallbackData( ByteString& sId , const ByteString& sText ); + bool getFallbackData( ByteString& sId , ByteString& sText); + + void addMergedLanguage( ByteString& sLang ); + bool isMerged( ByteString& sLang ); + ResData( const ByteString &rPF, const ByteString &rGId ) + : + nWidth( 0 ), + nChildIndex( 0 ), + nIdLevel( ID_LEVEL_NULL ), + bChild( FALSE ), + bChildWithText( FALSE ), + bText( FALSE ), + bHelpText( FALSE ), + bQuickHelpText( FALSE ), + bTitle( FALSE ), + bList( FALSE ), + bRestMerged( FALSE ), + sGId( rGId ), + nTextRefId( REFID_NONE ), + nHelpTextRefId( REFID_NONE ), + nQuickHelpTextRefId( REFID_NONE ), + nTitleRefId( REFID_NONE ), + sTextTyp( "Text" ), + pStringList( NULL ), + pUIEntries( NULL ), + pItemList( NULL ), + pFilterList( NULL ), + pPairedList( NULL ), + sPForm( rPF ) + { + sGId.EraseAllChars( '\r' ); + sPForm.EraseAllChars( '\r' ); + }; + ResData( const ByteString &rPF, const ByteString &rGId , const ByteString &rFilename ) + : + nChildIndex( 0 ), + nIdLevel( ID_LEVEL_NULL ), + bChild( FALSE ), + bChildWithText( FALSE ), + bText( FALSE ), + bHelpText( FALSE ), + bQuickHelpText( FALSE ), + bTitle( FALSE ), + bList( FALSE ), + bRestMerged( FALSE ), + sGId( rGId ), + sFilename( rFilename ), + nTextRefId( REFID_NONE ), + nHelpTextRefId( REFID_NONE ), + nQuickHelpTextRefId( REFID_NONE ), + nTitleRefId( REFID_NONE ), + sTextTyp( "Text" ), + pStringList( NULL ), + pUIEntries( NULL ), + pItemList( NULL ), + pFilterList( NULL ), + pPairedList( NULL ), + sPForm( rPF ) + + { + sGId.EraseAllChars( '\r' ); + sPForm.EraseAllChars( '\r' ); + }; + + +}; + + +// +// class Export +// + +/****************************************************************************** +* Purpose: syntax check and export of *.src, called from lexer +******************************************************************************/ + +#define LIST_NON 0x0000 +#define LIST_STRING 0x0001 +#define LIST_FILTER 0x0002 +#define LIST_ITEM 0x0004 +#define LIST_PAIRED 0x0005 +#define LIST_UIENTRIES 0x0008 +#define STRING_TYP_TEXT 0x0010 +#define STRING_TYP_HELPTEXT 0x0020 +#define STRING_TYP_QUICKHELPTEXT 0x0040 +#define STRING_TYP_TITLE 0x0080 + +#define MERGE_MODE_NORMAL 0x0000 +#define MERGE_MODE_LIST 0x0001 + +DECLARE_LIST( ResStack, ResData * ) +// forwards +class WordTransformer; +class ParserQueue; + +class Export +{ +private: + WordTransformer *pWordTransformer; + + CharSet aCharSet; // used charset in src + + SvFileStream aOutput; + + ResStack aResStack; // stack for parsing recursive + + ByteString sActPForm; // hold cur. system + + BOOL bDefine; // cur. res. in a define? + BOOL bNextMustBeDefineEOL; // define but no \ at lineend + ULONG nLevel; // res. recursiv? how deep? + USHORT nList; // cur. res. is String- or FilterList + ByteString nListLang; + ULONG nListIndex; + ULONG nListLevel; + bool bSkipFile; + ByteString sProject; + ByteString sRoot; + BOOL bEnableExport; + BOOL bMergeMode; + ByteString sMergeSrc; + ByteString sLastListLine; + BOOL bError; // any errors while export? + BOOL bReadOver; + BOOL bDontWriteOutput; + ByteString sLastTextTyp; + static bool isInitialized; + ByteString sFilename; + + +public: + ParserQueue* pParseQueue; // public ? + static ByteString sLanguages; // public ? + static ByteString sForcedLanguages; // public ? + + + static bool skipProject( ByteString sPrj ) ; + static void InitLanguages( bool bMergeMode = false ); + static void InitForcedLanguages( bool bMergeMode = false ); + static std::vector GetLanguages(); + static std::vector GetForcedLanguages(); + + static void SetLanguages( std::vector val ); + static void RemoveUTF8ByteOrderMarker( ByteString &rString ); + static bool hasUTF8ByteOrderMarker( const ByteString &rString ); + static void RemoveUTF8ByteOrderMarkerFromFile( const ByteString &rFilename ); + static bool fileHasUTF8ByteOrderMarker( const ByteString &rString ); + static ByteString GetIsoLangByIndex( USHORT nIndex ); + static void QuotHTML( ByteString &rString ); + static bool CopyFile( const ByteString& source , const ByteString& dest ); + + static void QuotHTMLXRM( ByteString &rString ); + static void UnquotHTML( ByteString &rString ); + + static const char* GetEnv( const char *pVar ); + static int getCurrentDirectory( rtl::OUString& base_fqurl , rtl::OUString& base ); + + static bool isSourceLanguage( const ByteString &sLanguage ); + static bool isAllowed( const ByteString &sLanguage ); + + static bool LanguageAllowed( const ByteString &nLanguage ); + static void Languages( std::vector::const_iterator& begin , std::vector::const_iterator& end ); + static void getRandomName( const ByteString& sPrefix , ByteString& sRandStr , const ByteString& sPostfix ); + static void getRandomName( ByteString& sRandStr ); + static void getCurrentDir( std::string& dir ); + + static void replaceEncoding( ByteString& rString ); + + static ByteString GetFallbackLanguage( const ByteString nLanguage ); + static void FillInFallbacks( ResData *pResData ); + static void FillInListFallbacks( ExportList *pList, const ByteString &nSource, const ByteString &nFallback ); + static ByteString GetTimeStamp(); + static BOOL ConvertLineEnds( ByteString sSource, ByteString sDestination ); + static ByteString GetNativeFile( ByteString sSource ); + static DirEntry GetTempFile(); + + static void DumpExportList( ByteString& sListName , ExportList& aList ); + static ByteString DumpMap( ByteString& sMapName , ByteStringHashMap& aMap ); + +private: + static std::vector aLanguages; + static std::vector aForcedLanguages; + + BOOL ListExists( ResData *pResData, USHORT nLst ); + + BOOL WriteData( ResData *pResData, BOOL bCreateNew = FALSE );// called befor dest. cur ResData + BOOL WriteExportList( ResData *pResData, ExportList *pExportList, + const ByteString &rTyp, BOOL bCreateNew = FALSE ); + + ByteString MergePairedList( ByteString& sLine , ByteString& sText ); + + ByteString FullId(); // creates cur. GID + + bool PairedListFallback( ByteString& sText , ResData& aResData ); + + ByteString GetPairedListID ( const ByteString& sText ); + ByteString GetPairedListString ( const ByteString& sText ); + ByteString StripList ( const ByteString& sText ); + + void UnmergeUTF8( ByteString& sOrig ); + void InsertListEntry( const ByteString &rText, const ByteString &rLine ); + void CleanValue( ByteString &rValue ); + ByteString GetText( const ByteString &rSource, int nToken ); + + BOOL PrepareTextToMerge( ByteString &rText, USHORT nTyp, + ByteString &nLangIndex, ResData *pResData ); + + void MergeRest( ResData *pResData, USHORT nMode = MERGE_MODE_NORMAL ); + void ConvertMergeContent( ByteString &rText ); + + void WriteToMerged( const ByteString &rText , bool bSDFContent ); + void SetChildWithText(); + + void CutComment( ByteString &rText ); + +public: + Export( const ByteString &rOutput, BOOL bWrite, + const ByteString &rPrj, const ByteString &rPrjRoot , const ByteString& rFile ); + Export( const ByteString &rOutput, BOOL bWrite, + const ByteString &rPrj, const ByteString &rPrjRoot, + const ByteString &rMergeSource , const ByteString& rFile ); + ~Export(); + + void Init(); + int Execute( int nToken, const char * pToken ); // called from lexer + void SetError() { bError = TRUE; } + BOOL GetError() { return bError; } +}; + + +// +// class PFormEntrys +// + +/****************************************************************************** +* Purpose: holds information of data to merge (one pform) +******************************************************************************/ + +class PFormEntrys : public ByteString +{ +friend class MergeDataFile; +private: + ByteString sHelpText; // empty string + ByteStringHashMap sText; + ByteStringBoolHashMap bTextFirst; + ByteStringHashMap sQuickHelpText; + ByteStringBoolHashMap bQuickHelpTextFirst; + ByteStringHashMap sTitle; + ByteStringBoolHashMap bTitleFirst; + +public: + PFormEntrys( const ByteString &rPForm ) : ByteString( rPForm ) {}; + ByteString Dump(); + void InsertEntry( + const ByteString &nId , + const ByteString &rText, + const ByteString &rQuickHelpText, + const ByteString &rTitle + ) + { + + sText[ nId ] = rText; + bTextFirst[ nId ] = true; + sQuickHelpText[ nId ] = rQuickHelpText; + bQuickHelpTextFirst[ nId ] = true; + sTitle[ nId ] = rTitle; + bTitleFirst[ nId ] = true; + } + BOOL GetText( ByteString &rReturn, USHORT nTyp, const ByteString &nLangIndex, BOOL bDel = FALSE ); +}; + +// +// class MergeData +// + +/****************************************************************************** +* Purpose: holds information of data to merge (one ressource) +******************************************************************************/ + +class MergeDataFile; + +class MergeData +{ +friend class MergeDataFile; +private: + ByteString sTyp; + ByteString sGID; + ByteString sLID; + ByteString sFilename; + PFormEntrysHashMap aMap; +public: + MergeData( const ByteString &rTyp, const ByteString &rGID, const ByteString &rLID , const ByteString &rFilename ) + : sTyp( rTyp ), sGID( rGID ), sLID( rLID ) , sFilename( rFilename ) {}; + ~MergeData(); + PFormEntrys* InsertEntry( const ByteString &rPForm ); + PFormEntrys* GetPFormEntrys( ResData *pResData ); + + void Insert( const ByteString& rPFO , PFormEntrys* pfEntrys ); + PFormEntrys* GetPFObject( const ByteString& rPFO ); + + ByteString Dump(); + BOOL operator==( ResData *pData ); +}; + +// +// class MergeDataFile +// + +/****************************************************************************** +* Purpose: holds information of data to merge +******************************************************************************/ + +class MergeDataFile +{ +private: + BOOL bErrorLog; + ByteString sErrorLog; + SvFileStream aErrLog; + ByteStringSet aLanguageSet; + MergeDataHashMap aMap; + ByteStringHashMap aLanguageMap; + std::vector aLanguageList; + ByteStringHashMap aFilenames; + + +public: + MergeDataFile( const ByteString &rFileName, const ByteString& rFile , BOOL bErrLog, CharSet aCharSet, bool bCaseSensitive = false ); + ~MergeDataFile(); + + + std::vector GetLanguages(); + MergeData *GetMergeData( ResData *pResData , bool bCaseSensitve = false ); + + PFormEntrys *GetPFormEntrys( ResData *pResData ); + PFormEntrys *GetPFormEntrysCaseSensitive( ResData *pResData ); + + void InsertEntry( const ByteString &rTYP, const ByteString &rGID, const ByteString &rLID, + const ByteString &rPFO, + const ByteString &nLang , const ByteString &rTEXT, + const ByteString &rQHTEXT, const ByteString &rTITLE , + const ByteString &sFilename , bool bCaseSensitive + ); + static USHORT GetLangIndex( USHORT nId ); + static ByteString CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive = false ); + + ByteString Dump(); + void WriteError( const ByteString &rLine ); +}; + + +class QueueEntry +{ +public: + QueueEntry( int nTypVal , ByteString sLineVal ): nTyp( nTypVal ) , sLine( sLineVal ){}; + int nTyp; + ByteString sLine; +}; + +class ParserQueue +{ +public: + + ParserQueue( Export& aExportObj ); + ~ParserQueue(); + + inline void Push( const QueueEntry& aEntry ); + bool bCurrentIsM; // public ? + bool bNextIsM; // public ? + bool bLastWasM; // public ? + bool bMflag; // public ? + + void Close(); +private: + // Future / Next + std::queue* aQueueNext; + // Current + std::queue* aQueueCur; + // Ref + std::queue* aQref; + + Export& aExport; + bool bStart; + bool bStartNext; + + inline void Pop( std::queue& aQueue ); + +}; +#endif + diff --git a/l10ntools/inc/gsicheck.hxx b/l10ntools/inc/gsicheck.hxx new file mode 100644 index 000000000000..13debcfc7106 --- /dev/null +++ b/l10ntools/inc/gsicheck.hxx @@ -0,0 +1,131 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: gsicheck.hxx,v $ + * $Revision: 1.8.22.1 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _GSICHECK_HXX_ +#define _GSICHECK_HXX_ + +#include "tagtest.hxx" + +// +// class GSILine +// +enum LineFormat { FORMAT_GSI, FORMAT_SDF, FORMAT_UNKNOWN }; + +class GSILine : public ByteString +{ +private: + + ParserMessageList aMessages; + LineFormat aFormat; + ULONG nLineNumber; + + ByteString aUniqId; + ByteString aLineType; + ByteString aLangId; + ByteString aText; + ByteString aQuickHelpText; + ByteString aTitle; + + BOOL bOK; + BOOL bFixed; + + void ReassembleLine(); + +public: + GSILine( const ByteString &rLine, ULONG nLine ); + LineFormat GetLineFormat() const { return aFormat; } + ULONG GetLineNumber() const { return nLineNumber; } + + ByteString const GetUniqId() const { return aUniqId; } + ByteString const GetLineType() const { return aLineType; } + ByteString const GetLanguageId() const { return aLangId; } + ByteString const GetText() const { return aText; } + String const GetUText() const { return String( aText, RTL_TEXTENCODING_UTF8 ); } + ByteString const GetQuickHelpText() const { return aQuickHelpText; } + ByteString const GetTitle() const { return aTitle; } + + void SetUText( String &aNew ) { aText = ByteString( aNew, RTL_TEXTENCODING_UTF8 ); ReassembleLine(); } + void SetText( ByteString &aNew ) { aText = aNew; ReassembleLine(); } + void SetQuickHelpText( ByteString &aNew ) { aQuickHelpText = aNew; ReassembleLine(); } + void SetTitle( ByteString &aNew ) { aTitle = aNew; ReassembleLine(); } + + ParserMessageList* GetMessageList() { return &aMessages; }; + BOOL HasMessages(){ return ( aMessages.Count() > 0 ); }; + + BOOL IsOK() const { return bOK; } + void NotOK(); + + BOOL IsFixed() const { return bFixed; } + void SetFixed() { bFixed = TRUE; }; +}; + +// +// class GSIBlock +// + +DECLARE_LIST( GSIBlock_Impl, GSILine * ) + +class LazySvFileStream; + +class GSIBlock : public GSIBlock_Impl +{ +private: + GSILine *pSourceLine; + GSILine *pReferenceLine; + void PrintList( ParserMessageList *pList, ByteString aPrefix, GSILine *pLine ); + BOOL bPrintContext; + BOOL bCheckSourceLang; + BOOL bCheckTranslationLang; + BOOL bReference; + BOOL bAllowKeyIDs; + BOOL bAllowSuspicious; + + BOOL bHasBlockError; + + BOOL IsUTF8( const ByteString &aTestee, BOOL bFixTags, USHORT &nErrorPos, ByteString &aErrorMsg, BOOL &bHasBeenFixed, ByteString &aFixed ) const; + BOOL TestUTF8( GSILine* pTestee, BOOL bFixTags ); + BOOL HasSuspiciousChars( GSILine* pTestee, GSILine* pSource ); + +public: + GSIBlock( BOOL PbPrintContext, BOOL bSource, BOOL bTrans, BOOL bRef, BOOL bAllowKID, BOOL bAllowSusp ); + ~GSIBlock(); + void PrintMessage( ByteString aType, ByteString aMsg, ByteString aPrefix, ByteString aContext, ULONG nLine, ByteString aUniqueId = ByteString() ); + void PrintError( ByteString aMsg, ByteString aPrefix, ByteString aContext, ULONG nLine, ByteString aUniqueId = ByteString() ); + void InsertLine( GSILine* pLine, const ByteString aSourceLang); + void SetReferenceLine( GSILine* pLine ); + BOOL CheckSyntax( ULONG nLine, BOOL bRequireSourceLine, BOOL bFixTags ); + + void WriteError( LazySvFileStream &aErrOut, BOOL bRequireSourceLine ); + void WriteCorrect( LazySvFileStream &aOkOut, BOOL bRequireSourceLine ); + void WriteFixed( LazySvFileStream &aFixOut, BOOL bRequireSourceLine ); +}; + +#endif + diff --git a/l10ntools/inc/helpmerge.hxx b/l10ntools/inc/helpmerge.hxx new file mode 100644 index 000000000000..0ebfa7ed62a9 --- /dev/null +++ b/l10ntools/inc/helpmerge.hxx @@ -0,0 +1,87 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: helpmerge.hxx,v $ + * $Revision: 1.12 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +// local includes +#include "export.hxx" +#include "xmlparse.hxx" +#include +#include +#include +#include /* auto_ptr */ +#include "tools/isofallback.hxx" + +#define MOVEFILE_REPLACE_EXISTING 0x01 + +/// This Class is responsible for extracting/merging OpenOffice XML Helpfiles +class HelpParser +{ +private: + ByteString sHelpFile; + bool bUTF8; + bool bHasInputList; + +/// Copy fallback language String (ENUS,DE) into position of the numeric language iso code +/// @PRECOND 0 < langIdx_in < MAX_IDX + static void FillInFallbacks( LangHashMap& rElem_out, ByteString sLangIdx_in ); + +/// Debugmethod, prints the content of the map to stdout + static void Dump( LangHashMap* rElem_in , const ByteString sKey_in ); + +/// Debugmethod, prints the content of the map to stdout + static void Dump( XMLHashMap* rElem_in ) ; + + + +public: + HelpParser( const ByteString &rHelpFile, bool bUTF8 , bool bHasInputList ); + ~HelpParser(){}; + +/// Method creates/append a SDF file with the content of a parsed XML file +/// @PRECOND rHelpFile is valid + static bool CreateSDF( const ByteString &rSDFFile_in, const ByteString &rPrj_in, const ByteString &rRoot_in, + const ByteString &sHelpFile, XMLFile *pXmlFile, const ByteString &rGsi1 ); + + static void parse_languages( std::vector& aLanguages , MergeDataFile& aMergeDataFile ); + +/// Method merges the String from the SDFfile into XMLfile. Both Strings must +/// point to existing files. + bool Merge( const ByteString &rSDFFile_in, const ByteString &rDestinationFile_in , ByteString& sLanguage , MergeDataFile& aMergeDataFile ); + bool Merge( const ByteString &rSDFFile, const ByteString &rPathX , const ByteString &rPathY , bool bISO + , const std::vector& aLanguages , MergeDataFile& aMergeDataFile , bool bCreateDir ); + +private: + static ByteString makeAbsolutePath( const ByteString& sHelpFile , const ByteString& rRoot_in ); + + ByteString GetOutpath( const ByteString& rPathX , const ByteString& sCur , const ByteString& rPathY ); + bool MergeSingleFile( XMLFile* file , MergeDataFile& aMergeDataFile , const ByteString& sLanguage , ByteString sPath ); + + void Process( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ); + void ProcessHelp( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ); + void MakeDir( const ByteString& sPath ); +}; diff --git a/l10ntools/inc/inireader.hxx b/l10ntools/inc/inireader.hxx new file mode 100644 index 000000000000..0861290adf9f --- /dev/null +++ b/l10ntools/inc/inireader.hxx @@ -0,0 +1,52 @@ +#include +#include +#include + +using namespace std; + +namespace transex3 +{ + +struct eqstr +{ + bool operator()( const string s1 , const string s2) const + { + return s1.compare( s2 ) == 0; + } +}; + +typedef std::hash_map< string , string > stringmap; +typedef std::hash_map< string, stringmap* > INImap; + +class INIreader +{ + private: + UErrorCode section_status; + UErrorCode parameter_status; + RegexMatcher* section_match; + RegexMatcher* parameter_match; + + public: + INIreader(): section_status ( U_ZERO_ERROR ) , + parameter_status ( U_ZERO_ERROR ) + { + section_match = new RegexMatcher ( "^\\s*\\[([a-zA-Z0-9]*)\\].*" , 0 , section_status ); + parameter_match = new RegexMatcher ( "^\\s*([a-zA-Z0-9]*)\\s*=\\s*([a-zA-Z0-9 ]*).*" , 0 , parameter_status ) ; + } + ~INIreader() + { + delete section_match; + delete parameter_match; + } + // open "filename", fill hash_map with sections / paramaters + bool read( INImap& myMap , string& filename ); + + private: + bool is_section( string& line , string& section_str ); + bool is_parameter( string& line , string& parameter_key , string& parameter_value ); + inline void check_status( UErrorCode status ); + inline void toStlString ( const UnicodeString& str, string& stl_str ); + inline void trim( string& str ); +}; + +} diff --git a/l10ntools/inc/l10ntools/directory.hxx b/l10ntools/inc/l10ntools/directory.hxx new file mode 100644 index 000000000000..6b71f59435f7 --- /dev/null +++ b/l10ntools/inc/l10ntools/directory.hxx @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +#ifdef WNT +#else +#include +#include +#include +#endif + +#include + +#ifndef L10NTOOLS_FILE_HXX +#define L10NTOOLS_FILE_HXX +#include +#endif + +namespace transex{ + +class Directory +{ + private: + rtl::OUString sDirectoryName; + rtl::OUString sFullName; + bool bSkipLinks; + + std::vector aDirVec; + std::vector aFileVec; + + public: + std::vector getSubDirectories() { return aDirVec; } + std::vector getFiles() { return aFileVec; } + + void readDirectory(); + void readDirectory( const rtl::OUString& sFullpath ); + void scanSubDir( int nLevels = 0 ); + + rtl::OUString getDirectoryName() { return sDirectoryName; } + rtl::OUString getFullName() { return sFullName ; } + void setSkipLinks( bool is_skipped ); + + void dump(); + Directory(){}; + + Directory( const rtl::OUString sFullPath ); + Directory( const rtl::OUString sFullPath , const rtl::OUString sEntry ) ; + Directory( const ByteString sFullPath ); + + static bool lessDir ( const Directory& rKey1, const Directory& rKey2 ) ; +}; + +} diff --git a/l10ntools/inc/l10ntools/file.hxx b/l10ntools/inc/l10ntools/file.hxx new file mode 100644 index 000000000000..e3a1a46b4ee8 --- /dev/null +++ b/l10ntools/inc/l10ntools/file.hxx @@ -0,0 +1,23 @@ +#include "rtl/ustring.hxx" + +namespace transex +{ + +class File +{ + private: + rtl::OUString sFileName; + rtl::OUString sFullName; + + public: + rtl::OUString getFileName(){ return sFileName; } + rtl::OUString getFullName(){ return sFullName; } + + File( const rtl::OUString sFile ); + File( const rtl::OUString sFullName , const rtl::OUString sFile ); + + static bool lessFile ( const File& rKey1, const File& rKey2 ); + +}; + +} diff --git a/l10ntools/inc/l10ntools/vosapp.hxx b/l10ntools/inc/l10ntools/vosapp.hxx new file mode 100644 index 000000000000..49e10e15e3d4 --- /dev/null +++ b/l10ntools/inc/l10ntools/vosapp.hxx @@ -0,0 +1,33 @@ +#ifndef VOSAPP_HXX +#define VOSAPP_HXX + +#include +#include +#include +#include + +// Mininmal vcl/svapp compatibility without vcl dependence +class Application +{ +public: + USHORT GetCommandLineParamCount(); + XubString GetCommandLineParam( USHORT nParam ); + virtual void Main() = 0; +}; + +// Urg: Cut & Paste from svapp.cxx: we don't want to depend on vcl +USHORT Application::GetCommandLineParamCount() +{ + vos::OStartupInfo aStartInfo; + return (USHORT)aStartInfo.getCommandArgCount(); +} + +XubString Application::GetCommandLineParam( USHORT nParam ) +{ + vos::OStartupInfo aStartInfo; + rtl::OUString aParam; + aStartInfo.getCommandArg( nParam, aParam ); + return XubString( aParam ); +} + +#endif /* VOSAPP_HXX */ diff --git a/l10ntools/inc/lngmerge.hxx b/l10ntools/inc/lngmerge.hxx new file mode 100644 index 000000000000..502889b27aa9 --- /dev/null +++ b/l10ntools/inc/lngmerge.hxx @@ -0,0 +1,69 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: lngmerge.hxx,v $ + * $Revision: 1.9 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +// local includes +#include "export.hxx" + +DECLARE_LIST( LngLineList, ByteString * ) + +#define LNG_OK 0x0000 +#define LNG_FILE_NOTFOUND 0x0001 +#define LNG_COULD_NOT_OPEN 0x0002 +#define SDF_OK 0x0003 +#define SDF_FILE_NOTFOUND 0x0004 +#define SDF_COULD_NOT_OPEN 0x0005 + +// +// class LngParser +// + +class LngParser +{ +private: + USHORT nError; + LngLineList *pLines; + ByteString sSource; + BOOL bDBIsUTF8; + BOOL bULF; + bool bQuiet; + std::vector aLanguages; + + void FillInFallbacks( ByteStringHashMap Text ); + bool isNextGroup( ByteString &sGroup_out , ByteString &sLine_in); + void ReadLine( const ByteString &sLine_in , ByteStringHashMap &rText_inout ); + void WriteSDF( SvFileStream &aSDFStream , ByteStringHashMap &rText_inout , + const ByteString &rPrj , + const ByteString &rRoot , const ByteString &sActFileName , const ByteString &sID ); +public: + LngParser( const ByteString &rLngFile, BOOL bUTF8, BOOL bULFFormat, bool bQuiet_in ); + ~LngParser(); + + BOOL CreateSDF( const ByteString &rSDFFile, const ByteString &rPrj, const ByteString &rRoot ); + BOOL Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile , const ByteString &rPrj ); +}; diff --git a/l10ntools/inc/makefile.mk b/l10ntools/inc/makefile.mk new file mode 100644 index 000000000000..6a704d63e48f --- /dev/null +++ b/l10ntools/inc/makefile.mk @@ -0,0 +1,51 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.3 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* +PRJ=.. + +PRJNAME=l10ntools +TARGET=inc + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk + +# --- Files -------------------------------------------------------- +# --- Targets ------------------------------------------------------- + +.INCLUDE : target.mk + +.IF "$(ENABLE_PCH)"!="" +ALLTAR : \ + $(SLO)$/precompiled.pch \ + $(SLO)$/precompiled_ex.pch + +.ENDIF # "$(ENABLE_PCH)"!="" + diff --git a/l10ntools/inc/pch/precompiled_l10ntools.cxx b/l10ntools/inc/pch/precompiled_l10ntools.cxx new file mode 100644 index 000000000000..b6cac813375f --- /dev/null +++ b/l10ntools/inc/pch/precompiled_l10ntools.cxx @@ -0,0 +1,32 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: precompiled_transex3.cxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "precompiled_l10ntools.hxx" + diff --git a/l10ntools/inc/pch/precompiled_l10ntools.hxx b/l10ntools/inc/pch/precompiled_l10ntools.hxx new file mode 100644 index 000000000000..2ed3c72ad4ee --- /dev/null +++ b/l10ntools/inc/pch/precompiled_l10ntools.hxx @@ -0,0 +1,35 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: precompiled_transex3.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): Generated on 2006-09-01 17:50:15.326479 + +#ifdef PRECOMPILED_HEADERS +#endif + diff --git a/l10ntools/inc/srciter.hxx b/l10ntools/inc/srciter.hxx new file mode 100644 index 000000000000..7f80074cd651 --- /dev/null +++ b/l10ntools/inc/srciter.hxx @@ -0,0 +1,61 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: srciter.hxx,v $ + * $Revision: 1.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef L10NTOOLS_DIRECTORY_HXX +#define L10NTOOLS_DIRECTORY_HXX +#include +#endif + +// class SourceTreeIterator +// + +class SourceTreeIterator +{ +private: + transex::Directory aRootDirectory; + bool bInExecute; + + void ExecuteDirectory( transex::Directory& pDirectory ); + +protected: + bool bLocal; + bool bSkipLinks; + +public: + SourceTreeIterator( const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in = false); + virtual ~SourceTreeIterator(); + + BOOL StartExecute(); + void EndExecute(); + + virtual void OnExecuteDirectory( const rtl::OUString &rDirectory ); +}; + + diff --git a/l10ntools/inc/tagtest.hxx b/l10ntools/inc/tagtest.hxx new file mode 100644 index 000000000000..811c4bf0e164 --- /dev/null +++ b/l10ntools/inc/tagtest.hxx @@ -0,0 +1,399 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: tagtest.hxx,v $ + * $Revision: 1.12 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _TAGTEST_HXX_ +#define _TAGTEST_HXX_ + +#include +#include +#include /* std::hashmap*/ + +class GSILine; + +typedef USHORT TokenId; + +#define TOK_INVALIDPOS USHORT( 0xFFFF ) + +class ParserMessage; + +DECLARE_LIST( Impl_ParserMessageList, ParserMessage* ) +class ParserMessageList; + + +struct equalByteString{ + bool operator()( const ByteString& rKey1, const ByteString& rKey2 ) const { + return rKey1.CompareTo( rKey2 )==COMPARE_EQUAL; + } +}; +struct lessByteString{ + bool operator()( const ByteString& rKey1, const ByteString& rKey2 ) const { + return rKey1.CompareTo( rKey2 )==COMPARE_LESS; + } +}; + +struct hashByteString{ + size_t operator()( const ByteString& rName ) const{ + std::hash< const char* > myHash; + return myHash( rName.GetBuffer() ); + } +}; + + + +typedef std::hash_map + StringHashMap; + +class TokenInfo +{ +private: + void SplitTag( ParserMessageList &rErrorList ); + + String aTagName; + StringHashMap aProperties; + BOOL bClosed; // tag is closed + BOOL bCloseTag; // tag is close Tag + + + BOOL bIsBroken; + BOOL bHasBeenFixed; + BOOL bDone; + +public: + + String aTokenString; + TokenId nId; + USHORT nPos; // Position in String + + TokenInfo():bClosed(FALSE),bCloseTag(FALSE),bIsBroken(FALSE),bHasBeenFixed(FALSE),bDone(FALSE),nId( 0 ){;} +explicit TokenInfo( TokenId pnId, USHORT nP ):bClosed(FALSE),bCloseTag(FALSE),bIsBroken(FALSE),bHasBeenFixed(FALSE),bDone(FALSE),nId( pnId ),nPos(nP){;} +explicit TokenInfo( TokenId pnId, USHORT nP, String paStr ):bClosed(FALSE),bCloseTag(FALSE),bIsBroken(FALSE),bHasBeenFixed(FALSE),bDone(FALSE),aTokenString( paStr ),nId( pnId ),nPos(nP) {;} +explicit TokenInfo( TokenId pnId, USHORT nP, String paStr, ParserMessageList &rErrorList ); + + String GetTagName() const; + + String MakeTag() const; + + /** + Is the property to be ignored or does it have the default value anyways + **/ + BOOL IsPropertyRelevant( const ByteString &aName, const String &aValue ) const; + BOOL IsPropertyValueValid( const ByteString &aName, const String &aValue ) const; + /** + Does the property contain the same value for all languages + e.g.: the href in a link tag + **/ + BOOL IsPropertyInvariant( const ByteString &aName, const String &aValue ) const; + /** + a subset of IsPropertyInvariant but containing only those that are fixable + we dont wat to fix e.g.: ahelp :: visibility + **/ + BOOL IsPropertyFixable( const ByteString &aName ) const; + BOOL MatchesTranslation( TokenInfo& rInfo, BOOL bGenErrors, ParserMessageList &rErrorList, BOOL bFixTags = FALSE ) const; + + BOOL IsDone() const { return bDone; } + void SetDone( BOOL bNew = TRUE ) { bDone = bNew; } + + BOOL HasBeenFixed() const { return bHasBeenFixed; } + void SetHasBeenFixed( BOOL bNew = TRUE ) { bHasBeenFixed = bNew; } +}; + + +class ParserMessageList : public Impl_ParserMessageList +{ +public: + void AddError( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ); + void AddWarning( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ); + + BOOL HasErrors(); +}; + + +#define TAG_GROUPMASK 0xF000 +#define TAG_GROUPSHIFT 12 + +#define TAG_GROUP( nTag ) (( nTag & TAG_GROUPMASK ) >> TAG_GROUPSHIFT ) +#define TAG_NOGROUP( nTag ) ( nTag & ~TAG_GROUPMASK ) // ~ = Bitweises NOT + +#define TAG_NOMORETAGS 0x0 + +#define TAG_GROUP_FORMAT 0x1 +#define TAG_ON 0x100 +#define TAG_BOLDON ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | TAG_ON | 0x001 ) +#define TAG_BOLDOFF ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | 0x001 ) +#define TAG_ITALICON ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | TAG_ON | 0x002 ) +#define TAG_ITALICOFF ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | 0x002 ) +#define TAG_UNDERLINEON ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | TAG_ON | 0x004 ) +#define TAG_UNDERLINEOFF ( TAG_GROUP_FORMAT << TAG_GROUPSHIFT | 0x004 ) + +#define TAG_GROUP_NOTALLOWED 0x2 +#define TAG_HELPID ( TAG_GROUP_NOTALLOWED << TAG_GROUPSHIFT | 0x001 ) +#define TAG_MODIFY ( TAG_GROUP_NOTALLOWED << TAG_GROUPSHIFT | 0x002 ) +#define TAG_REFNR ( TAG_GROUP_NOTALLOWED << TAG_GROUPSHIFT | 0x004 ) + +#define TAG_GROUP_STRUCTURE 0x3 +#define TAG_NAME ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x001 ) +#define TAG_HREF ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x002 ) +#define TAG_AVIS ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x004 ) +#define TAG_AHID ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x008 ) + +#define TAG_TITEL ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x020 ) +#define TAG_KEY ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x040 ) +#define TAG_INDEX ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x080 ) + +#define TAG_REFSTART ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x100 ) + +#define TAG_GRAPHIC ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x200 ) +#define TAG_NEXTVERSION ( TAG_GROUP_STRUCTURE << TAG_GROUPSHIFT | 0x400 ) + +#define TAG_GROUP_SYSSWITCH 0x4 +#define TAG_WIN ( TAG_GROUP_SYSSWITCH << TAG_GROUPSHIFT | 0x001 ) +#define TAG_UNIX ( TAG_GROUP_SYSSWITCH << TAG_GROUPSHIFT | 0x002 ) +#define TAG_MAC ( TAG_GROUP_SYSSWITCH << TAG_GROUPSHIFT | 0x004 ) +#define TAG_OS2 ( TAG_GROUP_SYSSWITCH << TAG_GROUPSHIFT | 0x008 ) + +#define TAG_GROUP_PROGSWITCH 0x5 +#define TAG_WRITER ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x001 ) +#define TAG_CALC ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x002 ) +#define TAG_DRAW ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x004 ) +#define TAG_IMPRESS ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x008 ) +#define TAG_SCHEDULE ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x010 ) +#define TAG_IMAGE ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x020 ) +#define TAG_MATH ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x040 ) +#define TAG_CHART ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x080 ) +#define TAG_OFFICE ( TAG_GROUP_PROGSWITCH << TAG_GROUPSHIFT | 0x100 ) + + +#define TAG_GROUP_META 0x6 +#define TAG_OFFICEFULLNAME ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x001 ) +#define TAG_OFFICENAME ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x002 ) +#define TAG_OFFICEPATH ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x004 ) +#define TAG_OFFICEVERSION ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x008 ) +#define TAG_PORTALNAME ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x010 ) +#define TAG_PORTALFULLNAME ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x020 ) +#define TAG_PORTALPATH ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x040 ) +#define TAG_PORTALVERSION ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x080 ) +#define TAG_PORTALSHORTNAME ( TAG_GROUP_META << TAG_GROUPSHIFT | 0x100 ) + + +#define TAG_GROUP_SINGLE 0x7 +#define TAG_REFINSERT ( TAG_GROUP_SINGLE << TAG_GROUPSHIFT | 0x001 ) + + +#define TAG_GROUP_MULTI 0x8 +#define TAG_END ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x010 ) +#define TAG_ELSE ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x020 ) +#define TAG_AEND ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x040 ) +#define TAG_VERSIONEND ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x080 ) +#define TAG_ENDGRAPHIC ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x100 ) + +#define TAG_GROUP_MISC 0x9 +#define TAG_COMMONSTART ( TAG_GROUP_MISC << TAG_GROUPSHIFT | 0x001 ) +#define TAG_COMMONEND ( TAG_GROUP_MISC << TAG_GROUPSHIFT | 0x002 ) + +#define TAG_UNKNOWN_TAG ( TAG_GROUP_MULTI << TAG_GROUPSHIFT | 0x800 ) + +DECLARE_LIST( TokenListImpl, TokenInfo* ) + +class TokenList : private TokenListImpl +{ +private: + + TokenList& operator =( const TokenList& rList ); +// { TokenListImpl::operator =( rList ); return *this; } + + +public: + using TokenListImpl::Count; + + + TokenList() : TokenListImpl(){}; + ~TokenList(){ Clear(); }; + + void Clear() + { + for ( ULONG i = 0 ; i < Count() ; i++ ) + delete TokenListImpl::GetObject( i ); + TokenListImpl::Clear(); + } + void Insert( TokenInfo p, ULONG nIndex = LIST_APPEND ) + { TokenListImpl::Insert( new TokenInfo(p), nIndex ); } +/* TokenInfo Remove( ULONG nIndex ) + { + TokenInfo aT = GetObject( nIndex ); + delete TokenListImpl::GetObject( nIndex ); + TokenListImpl::Remove( nIndex ); + return aT; + }*/ +// TokenInfo Remove( TokenInfo p ){ return Remove( GetPos( p ) ); } +// TokenInfo GetCurObject() const { return *TokenListImpl::GetCurObject(); } + TokenInfo& GetObject( ULONG nIndex ) const + { +// if ( TokenListImpl::GetObject(nIndex) ) + return *TokenListImpl::GetObject(nIndex); +// else +// return TokenInfo(); + } +/* ULONG GetPos( const TokenInfo p ) const + { + for ( ULONG i = 0 ; i < Count() ; i++ ) + if ( p == GetObject( i ) ) + return i; + return LIST_ENTRY_NOTFOUND; + }*/ + + TokenList( const TokenList& rList ); +/* { + for ( ULONG i = 0 ; i < rList.Count() ; i++ ) + { + Insert( rList.GetObject( i ), LIST_APPEND ); + } + }*/ +}; + +class ParserMessage +{ + USHORT nErrorNr; + ByteString aErrorText; + USHORT nTagBegin,nTagLength; + +protected: + ParserMessage( USHORT PnErrorNr, ByteString PaErrorText, const TokenInfo &rTag ); +public: + + USHORT GetErrorNr() { return nErrorNr; } + ByteString GetErrorText() { return aErrorText; } + + USHORT GetTagBegin() { return nTagBegin; } + USHORT GetTagLength() { return nTagLength; } + + virtual ~ParserMessage() {} + virtual BOOL IsError() =0; + virtual ByteString Prefix() =0; +}; + +class ParserError : public ParserMessage +{ +public: + ParserError( USHORT PnErrorNr, ByteString PaErrorText, const TokenInfo &rTag ); + + virtual BOOL IsError() {return TRUE;}; + virtual ByteString Prefix() {return "Error:"; }; +}; + +class ParserWarning : public ParserMessage +{ +public: + ParserWarning( USHORT PnErrorNr, ByteString PaErrorText, const TokenInfo &rTag ); + + virtual BOOL IsError() {return FALSE;}; + virtual ByteString Prefix() {return "Warning:"; }; +}; + +class SimpleParser +{ +private: + USHORT nPos; + String aSource; + String aLastToken; + TokenList aTokenList; + + TokenInfo aNextTag; // to store closetag in case of combined tags like
+ + String GetNextTokenString( ParserMessageList &rErrorList, USHORT &rTokeStartPos ); + +public: + SimpleParser(); + void Parse( String PaSource ); + TokenInfo GetNextToken( ParserMessageList &rErrorList ); + static String GetLexem( TokenInfo const &aToken ); + TokenList& GetTokenList(){ return aTokenList; } +}; + +class TokenParser +{ + BOOL match( const TokenInfo &aCurrentToken, const TokenId &aExpectedToken ); + BOOL match( const TokenInfo &aCurrentToken, const TokenInfo &aExpectedToken ); + void ParseError( USHORT nErrNr, ByteString aErrMsg, const TokenInfo &rTag ); + void Paragraph(); + void PfCase(); + void PfCaseBegin(); + void AppCase(); + void AppCaseBegin(); + void CaseEnd(); + void SimpleTag(); + void TagPair(); + void TagRef(); + + SimpleParser aParser; + TokenInfo aTag; + + TokenId nPfCaseOptions; + TokenId nAppCaseOptions; + BOOL bPfCaseActive ,bAppCaseActive; + + TokenId nActiveRefTypes; + + ParserMessageList *pErrorList; + +public: + TokenParser(); + void Parse( const String &aCode, ParserMessageList* pList ); +// ParserMessageList& GetErrors(){ return aErrorList; } +// BOOL HasErrors(){ return ( aErrorList.Count() > 0 ); } + TokenList& GetTokenList(){ return aParser.GetTokenList(); } +}; + +class LingTest +{ +private: + TokenParser aReferenceParser; + TokenParser aTesteeParser; + ParserMessageList aCompareWarningList; + void CheckTags( TokenList &aReference, TokenList &aTestee, BOOL bFixTags ); + BOOL IsTagMandatory( TokenInfo const &aToken, TokenId &aMetaTokens ); + String aFixedTestee; +public: + void CheckReference( GSILine *aReference ); + void CheckTestee( GSILine *aTestee, BOOL bHasSourceLine, BOOL bFixTags ); + +// ParserMessageList& GetReferenceErrors(){ return aReferenceParser.GetErrors(); } +// BOOL HasReferenceErrors(){ return aReferenceParser.HasErrors(); } + +// ParserMessageList& GetTesteeErrors(){ return aTesteeParser.GetErrors(); } +// BOOL HasTesteeErrors(){ return aTesteeParser.HasErrors(); } + + ParserMessageList& GetCompareWarnings(){ return aCompareWarningList; } + BOOL HasCompareWarnings(){ return ( aCompareWarningList.Count() > 0 ); } + + String GetFixedTestee(){ return aFixedTestee; } +}; + +#endif + diff --git a/l10ntools/inc/tokens.h b/l10ntools/inc/tokens.h new file mode 100644 index 000000000000..ef285f4c6361 --- /dev/null +++ b/l10ntools/inc/tokens.h @@ -0,0 +1,112 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: tokens.h,v $ + * $Revision: 1.9 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef _TOKENS_H +#define _TOKENS_H + +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +/* Tokens for parsing src files */ +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +#define IGNOREDTOKENS 400 /* #include | #pragma | //... | ... */ +#define COMMEND 401 /*... */ +#define DEFINEDRES 402 /* Text = { */ +#define ANYTOKEN 404 /* XYZ */ +#define UNKNOWNTOKEN 405 /* XYZ[ \t]$ */ +#define UNKNOWNCONSTRUCTION 406 /* XYZ ( xxx, yyy, zzz ) */ +#define UNKNOWNCHAR 407 /* . */ +/*------------------------------------------------------ */ +/* prev. tokens will not be executed */ +#define FILTER_LEVEL 500 +/* following tokens will be executed */ +/*------------------------------------------------------ */ +#define CONDITION 501 /* #if... | #endif ... | ... */ +#define EMPTYLINE 502 /* */ +#define RESSOURCE 503 /* Menu MID_TEST */ +#define RESSOURCEEXPR 504 /* Menu ( MID_TEST + .. ) */ +#define SMALRESSOURCE 505 /* PageItem { */ +#define TEXTLINE 506 /* TEXT = "hhh" */ +#define LONGTEXTLINE 507 /* TEXT = "hhh" TEST "HHH" ... */ +#define TEXT 508 /* "Something like this" */ +#define LEVELUP 509 /* { */ +#define LEVELDOWN 510 /* }; */ +#define APPFONTMAPPING 511 /* MAP_APPFONT(10,10) */ +#define ASSIGNMENT 512 /* Somathing = Anything */ +#define LISTASSIGNMENT 513 /* ...List [xyz]=... */ +#define LISTTEXT 514 /* < "Text" ... > */ +#define RSCDEFINE 515 /* #define MY_TEXT */ +#define RSCDEFINELEND 516 /* */ +#define NEWTEXTINRES 517 /* ### Achtung : Ne... */ +#define UIENTRIES 518 /* UIEntries = { */ +#define PRAGMA 519 /* #pragma ... */ +#define _LISTTEXT 521 /* { "Text" ... } */ +#define TEXTREFID 522 /* Text = 12345 */ +#define LISTRESID 523 /* < 12345; ... > */ +#define _LISTRESID 523 /* { 12345; ... } */ +#define NORMDEFINE 524 /* #define ... */ +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +/* Tokens for parsing cfg files */ +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +#define CFG_TAG 501 +#define CFG_TEXT_START 505 +#define CFG_TEXT_END 506 +#define CFG_TEXTCHAR 507 +#define CFG_CLOSETAG 508 +#define CFG_UNKNOWNTAG 509 +#define CFG_TOKEN_PACKAGE 600 +#define CFG_TOKEN_COMPONENT 601 +#define CFG_TOKEN_CONFIGNAME 602 +#define CFG_TOKEN_TEMPLATE 603 +#define CFG_TOKEN_OORNAME 604 +#define CFG_TOKEN_OORVALUE 605 +#define CFG_TOKEN_NO_TRANSLATE 606 + +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +/* Tokens for parsing xrm files */ +/*------------------------------------------------------ */ +/*------------------------------------------------------ */ +#define XRM_README_START 501 +#define XRM_README_END 502 +#define XRM_SECTION_START 503 +#define XRM_SECTION_END 504 +#define XRM_PARAGRAPH_START 505 +#define XRM_PARAGRAPH_END 506 +#define XRM_TEXT_START 507 +#define XRM_TEXT_END 508 +#define XRM_LIST_START 509 +#define XRM_LIST_END 510 +#define XML_TEXTCHAR 600 + + +#endif diff --git a/l10ntools/inc/treeconfig.hxx b/l10ntools/inc/treeconfig.hxx new file mode 100644 index 000000000000..96d693b0d376 --- /dev/null +++ b/l10ntools/inc/treeconfig.hxx @@ -0,0 +1,28 @@ +#include +#include + +#include "inireader.hxx" + +namespace transex3{ + +class Treeconfig +{ + + private: + INIreader inireader; + INImap map; + bool has_config_file; + void getCurrentDir( string& dir ); + bool isConfigFilePresent(); + + public: + + Treeconfig() : has_config_file( false ) { parseConfig(); } + // read the config file, returns true in case a config file had been found + bool parseConfig(); + // returns a string vector containing all active repositories, returns true in case we are deep inside + // of a source tree. This could affect the behavour of the tool + bool getActiveRepositories( vector& active_repos); +}; + +} diff --git a/l10ntools/inc/utf8conv.hxx b/l10ntools/inc/utf8conv.hxx new file mode 100644 index 000000000000..32e506edbda8 --- /dev/null +++ b/l10ntools/inc/utf8conv.hxx @@ -0,0 +1,47 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: utf8conv.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// global includes +#include +#include + +// +// class UTF8Converter +// + +class UTF8Converter +{ +private: + static void Convert( ByteString &rBuffer, rtl_TextEncoding nSourceENC, rtl_TextEncoding nDestENC ); + +public: + static ByteString ConvertToUTF8( const ByteString &rASCII, rtl_TextEncoding nEncoding ); + static ByteString ConvertFromUTF8( const ByteString &rUTF8, rtl_TextEncoding nEncoding ); +}; diff --git a/l10ntools/inc/wrdtrans.hxx b/l10ntools/inc/wrdtrans.hxx new file mode 100644 index 000000000000..efcb663204a6 --- /dev/null +++ b/l10ntools/inc/wrdtrans.hxx @@ -0,0 +1,90 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wrdtrans.hxx,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + +// OBSOLETE // + +#ifndef TX3_WRDTRANS_HXX +#define TX3_WRDTRANS_HXX + +// USED + // Base Classes + // Components +class WordTransTree; +class WordTrans_ErrorList; + // Parameters +#include + +class WordTransformer +{ + public: + enum E_Error + { + OK = 0, + ERROR_NO_WORDLIST, + ERROR_HOTKEY, + ERROR_OUTPUTSTRING_TOO_LONG, + OTHER_ERROR + }; + + // LIFECYCLE + WordTransformer(); + ~WordTransformer(); + BOOL LoadWordlist( /// @return False, if file could not be read, or there is already a wordlist loaded. + const ByteString & i_sWordlist_Filepath, + CharSet i_nWorkingCharSet = RTL_TEXTENCODING_MS_1252, + CharSet i_nFileCharSet = RTL_TEXTENCODING_MS_1252 ); + + // OPERATIONS + USHORT Transform( /// @return The number of errors during transforming. + ByteString & io_sText); + + // INQUIRY + USHORT NrOfErrors() const; + E_Error GetError( + USHORT i_nNr, /// [0 .. NrOfErrors()-1], other values return an empty error. + ByteString * o_pErrorText = 0) const; /// If o_pErrorText != 0, the String is filled with the description of the error. + + private: + // SERVICE FUNCTION + void CreateError(); + + // DATA + WordTransTree * dpTransformer; + WordTrans_ErrorList * + dpErrors; +}; + + + +#endif + + +*/ diff --git a/l10ntools/inc/wtranode.hxx b/l10ntools/inc/wtranode.hxx new file mode 100644 index 000000000000..4d71fc160fff --- /dev/null +++ b/l10ntools/inc/wtranode.hxx @@ -0,0 +1,121 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wtranode.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +#ifndef TX3_WTRANODE_HXX +#define TX3_WTRANODE_HXX + +// USED + // Base Classes + // Components + // Parameters +#include + + +typedef UINT8 BRANCH_T; + + + +const BRANCH_T C_BR_ALPHABASE = 4; +const BRANCH_T C_NR_OF_BRANCHES = 34; + + + + +/** @task + This is a node of the parsing-tree which implements the fuctionality of + class WordTransTree. + WordTransTree is dependant of this class, but NOT the other way! +**/ +class WTT_Node // WordTransTree-Node +{ + public: + enum E_TokenType + { +// no_token = 0, + token_to_keep, + token_to_replace + }; + + // LIFECYCLE + WTT_Node( + UINT8 i_nValue, // Own branch-value. + WTT_Node * i_pDefaultBranch, + WTT_Node * i_pDefaultBranchForAlphas ); + void SetBranch( + UINT8 i_cBranch, + WTT_Node * i_pNode ); + void SetAsTokenToReplace( + const ByteString & i_sReplaceString ); + ~WTT_Node(); + + // OPERATIONS + WTT_Node * GetNextNode( + UINT8 i_cBranch ); /// [0 .. C_NR_OF_BRANCHES-1], sonst GPF !!! + + // INQUIRY + E_TokenType TokenType() const; + UINT8 Value() const; + BOOL IsOnDeleting() const; + const ByteString & ReplaceString() const; + + private: + // DATA + UINT8 nValue; + E_TokenType eType; + ByteString sReplaceString; + WTT_Node * aBranches[C_NR_OF_BRANCHES]; // Mostly DYN pointers. + char bIsOnDeleting; +}; + + +inline WTT_Node * +WTT_Node::GetNextNode(UINT8 i_cBranch) + { return aBranches[i_cBranch]; } +inline WTT_Node::E_TokenType +WTT_Node::TokenType() const + { return eType; } +inline UINT8 +WTT_Node::Value() const + { return nValue; } +inline BOOL +WTT_Node::IsOnDeleting() const + { return bIsOnDeleting; } +inline const ByteString & +WTT_Node::ReplaceString() const + { return sReplaceString; } + + + + +#endif + + + diff --git a/l10ntools/inc/wtratree.hxx b/l10ntools/inc/wtratree.hxx new file mode 100644 index 000000000000..67d63280449f --- /dev/null +++ b/l10ntools/inc/wtratree.hxx @@ -0,0 +1,162 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wtratree.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +#ifndef TX3_WTRATREE_HXX +#define TX3_WTRATREE_HXX + +// USED + // Base Classes + // Components + // Parameters +#include + +const INT16 C_NR_OF_WTT_RESULTS = 5; +const INT16 C_NR_OF_POSSIBLE_CHARS = 256; + + +typedef unsigned char u_char; +typedef const char * constr; + + +class WTT_Node; + + +/** @task + This class implements the functionality, that class WordTransformer + offers. + WordTransformer is dependant of this class, but NOT the other way! +**/ +class WordTransTree +{ + public: + enum E_Result + { + OK = 0, + HOTKEY_LOST, + OUTPUT_OVERFLOW + }; + + + // LIFECYCLE + WordTransTree( + CharSet i_nWorkingCharSet = RTL_TEXTENCODING_MS_1252); + void SetCharSet( + CharSet i_nWorkingCharSet); + ~WordTransTree(); + + void AddWordPair( + const ByteString & i_sOldString, + const ByteString & i_sReplaceString ); + + // OPERATIONS + void InitTransformation( + const char * i_sInput, /// [!=0], a range of i_nInputLength must be valid memory for read. + UINT32 i_nInputLength, + UINT32 i_nOutputMaxLength = STRING_MAXLEN - 12 ); + E_Result TransformNextToken(); + + // INQUIRY + BOOL TextEndReached() const; + const char * Output() const; + + // These 3 functions are valid between two calls of + // TransformNextToken(): + E_Result CurResult() const; + ByteString CurReplacedString() const; + ByteString CurReplacingString() const; + char CurHotkey() const; + + private: + // SERVICE FUNCTONS + UINT8 CalculateBranch( + u_char i_cInputChar ) const; + + void Handle_Hotkey(); + void Handle_TokenToKeep(); + void Handle_TokenToTransform(); + + // DATA + // Fixed data + const u_char * sInput; + UINT32 nInputLength; + const u_char * pInputEnd; + + u_char * sOutput; // DYN + UINT32 nOutputMaxLength; + + WTT_Node * dpParsingTreeTop; // DYN + WTT_Node * pUnknownAlpha; + u_char cChar2Branch[C_NR_OF_POSSIBLE_CHARS]; + u_char c_AE, c_OE, c_UE, c_ae, c_oe, c_ue; + + // Working data + const u_char * pInputCurTokenStart; + const u_char * pInputPosition; + u_char * pOutputPosition; + WTT_Node * pCurParseNode; + + // Data which are valid only after a completed call to TransformNextToken() + E_Result eCurResult; + u_char cCurHotkey; // Letter wich is used as hotkey + u_char cCurHotkeySign; // Letter which is used to assign hotkey ('~'or '&') . +}; + + + + + + + +inline BOOL +WordTransTree::TextEndReached() const + { return pInputPosition == pInputEnd; } +inline const char * +WordTransTree::Output() const + { return TextEndReached() ? (constr) sOutput : ""; } +inline WordTransTree::E_Result +WordTransTree::CurResult() const + { return eCurResult; } +inline ByteString +WordTransTree::CurReplacedString() const + { return ByteString((constr) pInputCurTokenStart,pInputPosition-pInputCurTokenStart); } +inline char +WordTransTree::CurHotkey() const + { return cCurHotkey; } +inline UINT8 +WordTransTree::CalculateBranch(u_char i_cInputChar) const + { return cChar2Branch[i_cInputChar]; } + + + +#endif + + + diff --git a/l10ntools/inc/xmlparse.hxx b/l10ntools/inc/xmlparse.hxx new file mode 100644 index 000000000000..18b047ef75c1 --- /dev/null +++ b/l10ntools/inc/xmlparse.hxx @@ -0,0 +1,553 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: xmlparse.hxx,v $ + * $Revision: 1.15 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef BOOTSTRP_XMLPARSE_HXX +#define BOOTSTRP_XMLPARSE_HXX + +#include +#include +#include +#include +#include "tools/string.hxx" +#include "tools/list.hxx" +#define ENABLE_BYTESTRING_STREAM_OPERATORS +#include "tools/stream.hxx" +#include "tools/isofallback.hxx" +#include "export.hxx" +#include "xmlutil.hxx" + +#include +#include + +class XMLParentNode; +class XMLElement; + + +using namespace ::rtl; +using namespace std; + +#include /* std::hashmap*/ +#include /* std::deque*/ +#include /* std::iterator*/ +#include /* std::list*/ +#include /* std::vector*/ +#define XML_NODE_TYPE_FILE 0x001 +#define XML_NODE_TYPE_ELEMENT 0x002 +#define XML_NODE_TYPE_DATA 0x003 +#define XML_NODE_TYPE_COMMENT 0x004 +#define XML_NODE_TYPE_DEFAULT 0x005 +#define MAX_LANGUAGES 99 + + +//#define TESTDRIVER /* use xml2gsi testclass */ +//------------------------------------------------------------------------- + +/** Holds data of Attributes + */ +class XMLAttribute : public String +{ +private: + String sValue; + +public: + /// creates an attribute + XMLAttribute( + const String &rName, // attributes name + const String &rValue // attributes data + ) + : String( rName ), sValue( rValue ) {} + + /// getting value of an attribue + const String &GetValue() { return sValue; } + + void setValue(const String &rValue){sValue=rValue;} + + /// returns true if two attributes are equal and have the same value + BOOL IsEqual( + const XMLAttribute &rAttribute // the attribute which has to be equal + ) + { + return (( rAttribute == *this ) && ( rAttribute.sValue == sValue )); + } +}; + +DECLARE_LIST( XMLAttributeList, XMLAttribute * ) + +//------------------------------------------------------------------------- + +/** Virtual base to handle different kinds of XML nodes + */ +class XMLNode +{ +protected: + XMLNode() {} + +public: + virtual USHORT GetNodeType() = 0; + virtual ~XMLNode() {} +}; + +//------------------------------------------------------------------------- + +/** Virtual base to handle different kinds of child nodes + */ +class XMLChildNode : public XMLNode +{ +private: + XMLParentNode *pParent; + +protected: + XMLChildNode( XMLParentNode *pPar ); + XMLChildNode():pParent( NULL ){}; + XMLChildNode( const XMLChildNode& obj); + XMLChildNode& operator=(const XMLChildNode& obj); +public: + virtual USHORT GetNodeType() = 0; + + /// returns the parent of this node + XMLParentNode *GetParent() { return pParent; } + virtual ~XMLChildNode(){}; +}; + +DECLARE_LIST( XMLChildNodeList, XMLChildNode * ) + +//------------------------------------------------------------------------- + +/** Virtual base to handle different kinds of parent nodes + */ +class XMLData; + +class XMLParentNode : public XMLChildNode +{ +private: + XMLChildNodeList *pChildList; + static int dbgcnt; + //int nParentPos; +protected: + XMLParentNode( XMLParentNode *pPar ) + : XMLChildNode( pPar ), pChildList( NULL ) + { + } + XMLParentNode(): pChildList(NULL){ + } + /// Copyconstructor + XMLParentNode( const XMLParentNode& ); + + XMLParentNode& operator=(const XMLParentNode& obj); + virtual ~XMLParentNode(); + + +public: + virtual USHORT GetNodeType() = 0; + + /// returns child list of this node + XMLChildNodeList *GetChildList() { return pChildList; } + + /// adds a new child + void AddChild( + XMLChildNode *pChild /// the new child + ); + + void AddChild( + XMLChildNode *pChild , int pos /// the new child + ); + + virtual int GetPosition( ByteString id ); + int RemoveChild( XMLElement *pRefElement ); + void RemoveAndDeleteAllChilds(); + + /// returns a child element which matches the given one + XMLElement *GetChildElement( + XMLElement *pRefElement // the reference elelement + ); +}; + +//------------------------------------------------------------------------- + +DECLARE_LIST( XMLStringList, XMLElement* ) + +/// Mapping numeric Language code <-> XML Element +typedef std::hash_map< ByteString ,XMLElement* , hashByteString,equalByteString > LangHashMap; + +/// Mapping XML Element string identifier <-> Language Map +typedef std::hash_map XMLHashMap; + +/// Mapping iso alpha string code <-> iso numeric code +typedef std::hash_map HashMap; + +/// Mapping XML tag names <-> have localizable strings +typedef std::hash_map TagMap; + +/** Holds information of a XML file, is root node of tree + */ + + +class XMLFile : public XMLParentNode +{ +public: + XMLFile() ; + XMLFile( + const String &rFileName // the file name, empty if created from memory stream + ); + XMLFile( const XMLFile& obj ) ; + ~XMLFile(); + + ByteString* GetGroupID(std::deque &groupid); + void Print( XMLNode *pCur = NULL, USHORT nLevel = 0 ); + virtual void SearchL10NElements( XMLParentNode *pCur, int pos = 0 ); + void Extract( XMLFile *pCur = NULL ); + void View(); +// void static Signal_handler(int signo);//void*,oslSignalInfo * pInfo); + void showType(XMLParentNode* node); + + XMLHashMap* GetStrings(){return XMLStrings;} + BOOL Write( ByteString &rFilename ); + BOOL Write( ofstream &rStream , XMLNode *pCur = NULL ); + + bool CheckExportStatus( XMLParentNode *pCur = NULL );// , int pos = 0 ); + + XMLFile& operator=(const XMLFile& obj); + + virtual USHORT GetNodeType(); + + /// returns file name + const String &GetName() { return sFileName; } + void SetName( const String &rFilename ) { sFileName = rFilename; } + void SetFullName( const String &rFullFilename ) { sFullName = rFullFilename; } + const std::vector getOrder(){ return order; } + +protected: + // writes a string as UTF8 with dos line ends to a given stream + void WriteString( ofstream &rStream, const String &sString ); + + // quotes the given text for writing to a file + void QuotHTML( String &rString ); + + void InsertL10NElement( XMLElement* pElement); + + // DATA + String sFileName; + String sFullName; + + const ByteString ID,OLDREF,XML_LANG; + + TagMap nodes_localize; + XMLHashMap* XMLStrings; + + std::vector order; +}; + +/// An Utility class for XML +/// See RFC 3066 / #i8252# for ISO codes +class XMLUtil{ + +public: + /// Quot the XML characters and replace \n \t + static void QuotHTML( String &rString ); + + /// UnQuot the XML characters and restore \n \t + static void UnQuotHTML ( String &rString ); + + /// Return the numeric iso language code + //USHORT GetLangByIsoLang( const ByteString &rIsoLang ); + + /// Return the alpha strings representation + ByteString GetIsoLangByIndex( USHORT nIndex ); + + static XMLUtil& Instance(); + ~XMLUtil(); + + void dump(); + +private: + /// Mapping iso alpha string code <-> iso numeric code + HashMap lMap; + + /// Mapping iso numeric code <-> iso alpha string code + ByteString isoArray[MAX_LANGUAGES]; + + static void UnQuotData( String &rString ); + static void UnQuotTags( String &rString ); + + XMLUtil(); + XMLUtil(const XMLUtil&); + +}; + + + +//------------------------------------------------------------------------- + +/** Hold information of an element node + */ +class XMLElement : public XMLParentNode +{ +private: + String sElementName; + XMLAttributeList *pAttributes; + ByteString project, + filename, + id, + sOldRef, + resourceType, + languageId; + int nPos; + +protected: + void Print(XMLNode *pCur, OUStringBuffer& buffer , bool rootelement); +public: + /// create a element node + XMLElement(){} + XMLElement( + const String &rName, // the element name + XMLParentNode *Parent // parent node of this element + ): XMLParentNode( Parent ), + sElementName( rName ), + pAttributes( NULL ), + project(""), + filename(""), + id(""), + sOldRef(""), + resourceType(""), + languageId(""), + nPos(0) + { + } + ~XMLElement(); + XMLElement(const XMLElement&); + + XMLElement& operator=(const XMLElement& obj); + /// returns node type XML_NODE_ELEMENT + virtual USHORT GetNodeType(); + + /// returns element name + const String &GetName() { return sElementName; } + + /// returns list of attributes of this element + XMLAttributeList *GetAttributeList() { return pAttributes; } + + /// adds a new attribute to this element, typically used by parser + void AddAttribute( const String &rAttribute, const String &rValue ); + + void ChangeLanguageTag( const String &rValue ); + // Return a ASCII String representation of this object + OString ToOString(); + + // Return a Unicode String representation of this object + OUString ToOUString(); + + bool Equals(OUString refStr); + + /// returns a attribute + XMLAttribute *GetAttribute( + const String &rName // the attribute name + ); + void SetProject ( ByteString prj ){ project = prj; } + void SetFileName ( ByteString fn ){ filename = fn; } + void SetId ( ByteString theId ){ id = theId; } + void SetResourceType ( ByteString rt ){ resourceType = rt; } + void SetLanguageId ( ByteString lid ){ languageId = lid; } + void SetPos ( int nPos_in ){ nPos = nPos_in; } + void SetOldRef ( ByteString sOldRef_in ){ sOldRef = sOldRef_in; } + + virtual int GetPos() { return nPos; } + ByteString GetProject() { return project; } + ByteString GetFileName() { return filename; } + ByteString GetId() { return id; } + ByteString GetOldref() { return sOldRef; } + ByteString GetResourceType(){ return resourceType; } + ByteString GetLanguageId() { return languageId; } + + +}; +//------------------------------------------------------------------------- + + +/** Holds character data + */ +class XMLData : public XMLChildNode +{ +private: + String sData; + bool isNewCreated; + +public: + /// create a data node + XMLData( + const String &rData, // the initial data + XMLParentNode *Parent // the parent node of this data, typically a element node + ) + : XMLChildNode( Parent ), sData( rData ) , isNewCreated ( false ){} + XMLData( + const String &rData, // the initial data + XMLParentNode *Parent, // the parent node of this data, typically a element node + bool newCreated + ) + : XMLChildNode( Parent ), sData( rData ) , isNewCreated ( newCreated ){} + + XMLData(const XMLData& obj); + + XMLData& operator=(const XMLData& obj); + virtual USHORT GetNodeType(); + + /// returns the data + const String &GetData() { return sData; } + + bool isNew() { return isNewCreated; } + /// adds new character data to the existing one + void AddData( + const String &rData // the new data + ); + + + +}; + +//------------------------------------------------------------------------- + +/** Holds comments + */ +class XMLComment : public XMLChildNode +{ +private: + String sComment; + +public: + /// create a comment node + XMLComment( + const String &rComment, // the comment + XMLParentNode *Parent // the parent node of this comemnt, typically a element node + ) + : XMLChildNode( Parent ), sComment( rComment ) {} + + virtual USHORT GetNodeType(); + + XMLComment( const XMLComment& obj ); + + XMLComment& operator=(const XMLComment& obj); + + /// returns the comment + const String &GetComment() { return sComment; } +}; + +//------------------------------------------------------------------------- + +/** Holds additional file content like those for which no handler exists + */ +class XMLDefault : public XMLChildNode +{ +private: + String sDefault; + +public: + /// create a comment node + XMLDefault( + const String &rDefault, // the comment + XMLParentNode *Parent // the parent node of this comemnt, typically a element node + ) + : XMLChildNode( Parent ), sDefault( rDefault ) {} + + XMLDefault(const XMLDefault& obj); + + XMLDefault& operator=(const XMLDefault& obj); + + /// returns node type XML_NODE_TYPE_COMMENT + virtual USHORT GetNodeType(); + + /// returns the comment + const String &GetDefault() { return sDefault; } +}; + +//------------------------------------------------------------------------- + +/** struct for error information, used by class SimpleXMLParser + */ +struct XMLError { + XML_Error eCode; // the error code + ULONG nLine; // error line number + ULONG nColumn; // error column number + String sMessage; // readable error message +}; + +//------------------------------------------------------------------------- + +/** validating xml parser, creates a document tree with xml nodes + */ + + +class SimpleXMLParser +{ +private: + XML_Parser aParser; + XMLError aErrorInformation; + + XMLFile *pXMLFile; + XMLParentNode *pCurNode; + XMLData *pCurData; + + + static void StartElementHandler( void *userData, const XML_Char *name, const XML_Char **atts ); + static void EndElementHandler( void *userData, const XML_Char *name ); + static void CharacterDataHandler( void *userData, const XML_Char *s, int len ); + static void CommentHandler( void *userData, const XML_Char *data ); + static void DefaultHandler( void *userData, const XML_Char *s, int len ); + + + void StartElement( const XML_Char *name, const XML_Char **atts ); + void EndElement( const XML_Char *name ); + void CharacterData( const XML_Char *s, int len ); + void Comment( const XML_Char *data ); + void Default( const XML_Char *s, int len ); + + +public: + /// creates a new parser + SimpleXMLParser(); + ~SimpleXMLParser(); + + /// parse a file, returns NULL on criticall errors + XMLFile *Execute( + const String &rFullFileName, + const String &rFileName, // the file name + XMLFile *pXMLFileIn // the XMLFile + ); + + /// parse a memory stream, returns NULL on criticall errors + XMLFile *Execute( + SvMemoryStream *pStream // the stream + ); + + /// returns an error struct + const XMLError &GetError() { return aErrorInformation; } +}; + +#endif diff --git a/l10ntools/inc/xmlutil.hxx b/l10ntools/inc/xmlutil.hxx new file mode 100644 index 000000000000..812f50b85c45 --- /dev/null +++ b/l10ntools/inc/xmlutil.hxx @@ -0,0 +1,9 @@ +#define ENGLISH_US 1 +#define ENGLISH_US_ISO "en-US" +#define ENGLISH_US_PROPERTY "en_US" +#define ENGLISH_US_INDEX 1 +#define GERMAN_DE 4 +#define GERMAN_DE_ISO "x-german" +#define GERMAN_DE_INDEX 3 +#define GERMAN_ISO2 "de-DE" + diff --git a/l10ntools/inc/xrmmerge.hxx b/l10ntools/inc/xrmmerge.hxx new file mode 100644 index 000000000000..47be1ea7a038 --- /dev/null +++ b/l10ntools/inc/xrmmerge.hxx @@ -0,0 +1,161 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: xrmmerge.hxx,v $ + * $Revision: 1.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// global includes +#include + +// +// XRMResParser +// + +class XRMResParser +{ +private: + ByteString sGID; + ByteString sLID; + + BOOL bError; + BOOL bText; + + bool sLocalized; + + ByteString sCurrentOpenTag; + ByteString sCurrentCloseTag; + ByteString sCurrentText; + std::vector aLanguages; + +protected: + ByteString GetAttribute( const ByteString &rToken, const ByteString &rAttribute ); + void Error( const ByteString &rError ); + + virtual void Output( const ByteString& rOutput )=0; + virtual void WorkOnText( + const ByteString &rOpenTag, + ByteString &rText + )=0; + virtual void EndOfText( + const ByteString &rOpenTag, + const ByteString &rCloseTag + )=0; + + ByteString GetGID() { return sGID; } + ByteString GetLID() { return sLID; } + + void ConvertStringToDBFormat( ByteString &rString ); + void ConvertStringToXMLFormat( ByteString &rString ); + +public: + XRMResParser(); + virtual ~XRMResParser(); + + int Execute( int nToken, char * pToken ); + + void SetError( BOOL bErr = TRUE ) { bError = bErr; } + BOOL GetError() { return bError; } +}; + +// +// class XRMResOutputParser +// + +class XRMResOutputParser : public XRMResParser +{ +private: + std::vector aLanguages; +protected: + SvFileStream *pOutputStream; +public: + XRMResOutputParser ( const ByteString &rOutputFile ); + virtual ~XRMResOutputParser(); +}; + +// +// XRMResExport +// + +class XRMResExport : public XRMResOutputParser +{ +private: + ResData *pResData; + ByteString sPrj; + ByteString sPath; + std::vector aLanguages; + +protected: + void WorkOnText( + const ByteString &rOpenTag, + ByteString &rText + ); + void EndOfText( + const ByteString &rOpenTag, + const ByteString &rCloseTag + ); + void Output( const ByteString& rOutput ); + +public: + XRMResExport( + const ByteString &rOutputFile, + const ByteString &rProject, + const ByteString &rFilePath + ); + virtual ~XRMResExport(); +}; + +// +// class XRMResMerge +// + +class XRMResMerge : public XRMResOutputParser +{ +private: + MergeDataFile *pMergeDataFile; + ByteString sFilename; + ResData *pResData; + std::vector aLanguages; + +protected: + void WorkOnText( + const ByteString &rOpenTag, + ByteString &rText + ); + void EndOfText( + const ByteString &rOpenTag, + const ByteString &rCloseTag + ); + void Output( const ByteString& rOutput ); +public: + XRMResMerge( + const ByteString &rMergeSource, + const ByteString &rOutputFile, + ByteString &rFilename + ); + virtual ~XRMResMerge(); +}; + diff --git a/l10ntools/java/l10nconv/build.xml b/l10ntools/java/l10nconv/build.xml new file mode 100755 index 000000000000..6902227e5122 --- /dev/null +++ b/l10ntools/java/l10nconv/build.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <i>Copyright &#169; 2004 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303 USA</i> +
${docname}
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ diff --git a/l10ntools/java/l10nconv/converter.MF b/l10ntools/java/l10nconv/converter.MF new file mode 100755 index 000000000000..843d500b7548 --- /dev/null +++ b/l10ntools/java/l10nconv/converter.MF @@ -0,0 +1 @@ +Main-Class: com.sun.star.tooling.converter.Convert diff --git a/l10ntools/java/l10nconv/documentation/readmeConverter.sxw b/l10ntools/java/l10nconv/documentation/readmeConverter.sxw new file mode 100755 index 000000000000..f779e10acb2c Binary files /dev/null and b/l10ntools/java/l10nconv/documentation/readmeConverter.sxw differ diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java new file mode 100755 index 000000000000..d304c2544bff --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java @@ -0,0 +1,85 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: DirtyTagWrapCheck.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.DirtyTags; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + + + +public class DirtyTagWrapCheck { + static String line=""; + public static void main(String[] args) { + try { + File fi = new File("D:\\Testfiles\\KID_helpcontent.sdf");//Copy of + FileReader fr = new FileReader(fi); + BufferedReader br = new BufferedReader(fr); + + int readCounter=0; + int missCounter=0; + int lineErrorCounter=0; + while((line=br.readLine())!=null){ + readCounter++; + String [] split = line.split("\t"); + if(split.length<15){ + + lineErrorCounter++; + continue; + } + String string = split[10]; + String wrapped = DirtyTagWrapper.wrapString(string); + String unwrapped=DirtyTagWrapper.unwrapString(wrapped); + if(!string.equals(unwrapped)){ + + missCounter++; + System.out.println(""+readCounter+"\n"+string+"\n"+unwrapped+"\n"+wrapped+"\n"); + } + } + System.out.println("Fertig "+readCounter+" "+missCounter+" "+lineErrorCounter); + } catch (FileNotFoundException e) { + // + e.printStackTrace(); + } catch (IOException e) { + // + e.printStackTrace(); + } catch (DirtyTagWrapper.TagWrapperException e) { + System.out.println(e.getMessage()+"\n"+line+"\n"); + + } + + } +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java new file mode 100755 index 000000000000..49fc08b69d32 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java @@ -0,0 +1,252 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: DirtyTagWrapper.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.DirtyTags; + +import java.io.IOException; +import java.util.ArrayList; + +/** + * Solves the problem with translating strings from the + * Star-Office Help. This Strings contain XML snippets + * (that means parts of an xml dokument). I call them 'dirty' + * because the start of a tag (<) and the and of an tag (>) + * are quoted by a single backslash(\<.....\>). This is done + * because the text out of th tags should not contain '<' and '>' + * as Entity references (< or >) but as readable signs. + * This is for translation purposes. + * Because translators get mad while find out the really translatable + * parts between all the markup information, the XLIFF Specification + * allows to wrap parts of a String that should not be translated by + * special tags (, ). + * This Class has two static methods that do the wrapping and unwrapping + * NOTE: this won't work with not 'dirty' Strings. + * + * @author Christian Schmidt 2005 + * + */ +public class DirtyTagWrapper { + + private static boolean doWrap=true; + public static void setWrapping(boolean doWrap){ + DirtyTagWrapper.doWrap=doWrap; + } + + /** + * Unwraps the 'dirty' parts of a String from ept and bpt tags + * + * @param checkString The String to unwrap + * @return the unwrapped String + */ + public static String unwrapString(String checkString){ + //remove the ept and bpt tags + String[] splitted =checkString.split("(])*>)|()|(])*>)|()|(])*>)|()|(])*/>)"); + StringBuffer workBuffer= new StringBuffer(); + for(int i=0;i").replaceAll( ""","\"").replaceAll( "'","'"); + + //remove the nsub tags + splitted =string.split("(])*>)|()"); + StringBuffer returnBuffer= new StringBuffer(); + for(int i=0;i"); + + ArrayList tagString =new ArrayList(); + // put the while splitting lost parts to the end of the single strings + for(int j=0;j")){ + parts2[parts2.length-1]+="\\>"; + } + // split the leading text from the real tag string (<...>) + for(int j=0;j0&&parts2[j].indexOf("\\>")>0){ + //...then split it in two parts + // the leading text + tagString.add(parts2[j].substring(0,(parts2[j].indexOf("\\<")))); + // ...and the tag + tagString.add(parts2[j].substring(parts2[j].indexOf("\\<"))); + + }else{ + //no tag...must be text only + tagString.add(parts2[j]); + } + + } + ArrayList tagNames=new ArrayList(); + String item=""; + for(int i=0;i"); + if(start>=0&&end>0){ + boolean isStandalone=false; + if(item.endsWith("/\\>")){ + // this is a standalone tag + isStandalone=true; + } + item=item.substring(start,end); + + if(item.indexOf(" ")>0){ + item=item.substring(0,item.indexOf(" ")); + } + if(isStandalone){ + item=item+"/"; + } + tagNames.add(item); + }else{ + tagNames.add(""); + } + } + ArrayList tagType=new ArrayList(); + for(int i=0;i0){ + try{ + start=new TagPair(tagList); + returnBuffer.append(start.getWrapped()); + }catch(TagPair.TagPairConstructionException e){ + throw (new DirtyTagWrapper()).new TagWrapperException(e); + } + } + TagPair.resetCounter(); + return new String(returnBuffer); + } + /** + * @author Christian Schmidt 2005 + * + */ + public class TagWrapperException extends Exception { + + /** + * Create a new Instance of TagWrapperException + * + * + */ + public TagWrapperException() { + super(); + // + } + + /** + * Create a new Instance of TagWrapperException + * + * @param arg0 + */ + public TagWrapperException(String arg0) { + super(arg0); + // + } + + /** + * Create a new Instance of TagWrapperException + * + * @param arg0 + * @param arg1 + */ + public TagWrapperException(String arg0, Throwable arg1) { + super(arg0, arg1); + // + } + + /** + * Create a new Instance of TagWrapperException + * + * @param arg0 + */ + public TagWrapperException(Throwable arg0) { + super(arg0); + // + } + + } +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java new file mode 100755 index 000000000000..7495736ab68c --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java @@ -0,0 +1,249 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Tag.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.DirtyTags; + +import java.io.IOException; +import java.util.Map; + +import com.sun.star.tooling.converter.ExtMap; + +/** + * @author Christian Schmidt 2005 + * + */ +public class Tag { + private static int indent=0; + Map tagNames; + private String tagType; + private String tagName; + private String tagString; + public static Tag EMPTYTAG=new Tag("","",""); + + /** + * Create a new Instance of Tag + * + * @param tagType + * @param tagName + * @param tagString + */ + public Tag(String tagType, String tagName, String tagString) { + + this.tagType=tagType; + this.tagName=tagName; + this.tagString=tagString; + + tagNames=new ExtMap(); + tagNames.put("link","name"); + tagNames.put("caption","xml-lang"); + tagNames.put("alt","xml-lang"); + } + + public String getWrappedTagString() throws IOException{ + if(this.canHaveTranslateableContent()){ + return this.wrapTagStringIntern(); + }else{ + return xmlString(this.tagString); + } + } + + private final String xmlString( final String string) throws java.io.IOException { + if (string == null) + return string; // "" + String str = string; + + for(int i=0;i'){ + str=str.substring(0, i)+">"+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='"'){ + str=str.substring(0, i)+"""+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='\''){ + str=str.substring(0, i)+"'"+str.substring(i+1); + continue; + } + } + + return str; + } + /** + * @return + */ + private boolean canHaveTranslateableContent() { + return (tagNames.containsKey(this.tagName)); + + } + + /** + * @throws IOException + * + */ + private String wrapTagStringIntern() throws IOException { + + + String[] split=this.tagString.split("="); + int length=split.length; + // no attribute found; + if (length==0) return xmlString(tagString); + else{ + int i=0; + + while(i")<0) split[i]=xmlString(split[i]); + i++; + String value; + attributeName=(attributeName.substring(attributeName.lastIndexOf(" ")).trim()); + if((value=translateableAttributeValue(this.tagName)).equals(attributeName)){ + int valueStart=0; + int valueEnd=0; + + // get the value to the found attribute name + // it must either be surrounded by '"'... + if((valueStart=split[i].indexOf('"'))>=0){ + valueEnd = split[i].lastIndexOf('"'); + //...or surrounded by "'" + }else if((valueStart=split[i].indexOf("'"))>=0){ + valueEnd = split[i].lastIndexOf("'"); + }else{ + // there seems to be an error, + // we found an '=' (we split there) but no '"' or ''' + // but although we don't check the syntax + // we just continue + continue; + } + //ok we found the border of a value that might be translated + //now we wrap it with the tags + + split[i]=xmlString(split[i].substring(0,valueStart+1))+""+xmlString(split[i].substring(valueStart+1,valueEnd))+""+xmlString(split[i].substring(valueEnd)); + + } + } + String wrappedString=""; + // we have the wrapped parts, now we put them together + int j=0; + for(j=0;j=0&&end>0){ + tagString=tagString.substring(start,end); + + if(tagString.indexOf(" ")>0){ + tagString=tagString.substring(0,tagString.indexOf(" ")); + } + return tagString; + }else{ + return ""; + } + } + private static String extractTagType(String tagName){ + if(tagName.equals("")){ + return "Text"; + }else if(tagName.startsWith("/")){ + return "EndTag"; + }else if(tagName.endsWith("/")){ + return "StartAndEndTag"; + }else { + return "StartTag"; + } + } + + /** + * @return Returns the tagName. + */ + public String getTagName() { + return this.tagName; + } + /** + * @return Returns the tagString. + */ + public String getTagString() { + return this.tagString; + } + /** + * @return Returns the tagType. + */ + public String getTagType() { + return this.tagType; + } + + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java new file mode 100755 index 000000000000..7993fc9cf0a4 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java @@ -0,0 +1,310 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: TagPair.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.DirtyTags; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + + +/** + * @author Christian Schmidt 2005 + * + */ +public class TagPair { + + + private Tag startTag=Tag.EMPTYTAG; + private Tag endTag=Tag.EMPTYTAG; + private String startingText=""; + private ArrayList enclosedTags=new ArrayList(); + private long id; + private static int ElementCounter=1; + private String endingText=""; + + /** + * @author Christian Schmidt 2005 + * + */ + public class TagPairConstructionException extends Exception { + + /** + * Create a new Instance of TagPairConstructionException + * + * @param string + */ + public TagPairConstructionException(String string) { + + } + + } + + /** + * Create a new Instance of TagPair + * + * + */ + public TagPair() { + + } + + + /** + * Create a new Instance of TagPair + * + * Find matching tags in tagList, create a TagPair of it, create + * tagPairs from the content in the tagPair and remove all used + * tags from tagList. The rest of the tagList starts after the + * endTag of this TagPair. + * + * @param tagList a List of the tags to check + * + * @throws TagPairConstructionException + */ + public TagPair(ArrayList tagList) throws TagPairConstructionException { + + if(tagList.size()==0){ + return; + } + ArrayList contentList=new ArrayList();; + Tag tag=(Tag)tagList.get(0); + tagList.remove(0); + + + if("Text".equals(tag.getTagType())){ + // is this Text the only content + // of this Tag ? + if(tagList.size()==0){ + //yes...then it is the starting Text of this TagPair + this.startingText=tag.getTagString(); + return; + }else{ + //no...the tag is normal content + contentList.add(tag); + } + this.startingText=tag.getTagString(); + + }else if("EndTag".equals(tag.getTagType())){ + //ERRor throw EXception + }else if("StartTag".equals(tag.getTagType())){ + // find the matching end tag + this.startTag=tag; + Iterator iter=tagList.iterator(); + + int equivalentTagCounter=0; + while(iter.hasNext()){ + //is this the end tag? + if((tag=(Tag)iter.next()).getTagName().equals('/'+this.startTag.getTagName())&&equivalentTagCounter==0){ + //found the corresponding end tag + + //this TagPair is complete + //so it needs an id + this.id=TagPair.ElementCounter++; + this.endTag=tag; + //...remove it from list + tagList.removeAll(contentList); + tagList.remove(tag); + break; + }else{ + // tag is not the end tag + // so it is between the start and the end tag + // and belongs to the content + // but first check if it has the same name as the current tag + if(tag.getTagName().equals(this.startTag.getTagName())){ + // if this is a start tag like the current start tag + // we count it to find out the matching end tag in nested tags + if(tag.getTagType().equals("StartTag")){ + equivalentTagCounter++; + } + } + if(tag.getTagName().equals("/"+this.startTag.getTagName())){ + if(tag.getTagType().equals("EndTag")){ + equivalentTagCounter--; + } + } + + contentList.add(tag); + } + } + //found the end tag ? + //no... + if (this.endTag.getTagType()==""){ + + throw new TagPairConstructionException("ERROR: Missing end tag ("+ + this.startTag.getTagString()+")."); + //...yes + }else{ + //We need to check whether the content is starting or ending with text + //...check starting with text + if(contentList.size()>=1&&((String)((Tag)contentList.get(0)).getTagType()).equals("Text")){ + //yes...store it as startingText + this.startingText=(String)((Tag)contentList.get(0)).getTagString(); + //remove it from list + contentList.remove(0); + } + // ...check ending with text + if(contentList.size()>=1&&((String)((Tag)contentList.get(contentList.size()-1)).getTagType()).equals("Text")){ + //yes...store it as endingText + this.endingText=(String)((Tag)contentList.get(contentList.size()-1)).getTagString(); + //remove it from list + contentList.remove(contentList.size()-1); + } + //create the list of tags enclosed by this tagPair + createEnclosedTags(contentList); + } + //if stand AloneTag create own TagObject...give ID...add to List + }else if("StartAndEndTag".equals(tag.getTagType())){ + this.startTag=tag; + this.endTag=new Tag("EndOfStandAlone","",""); + createEnclosedTags(contentList); + } + + } + + /** + * @param contentList + * @throws TagPairConstructionException + */ + private void createEnclosedTags(ArrayList contentList) throws TagPairConstructionException { + while(contentList.size()>0){ + //create the inner TagPairs + this.enclosedTags.add(new TagPair(contentList)); + } + + } + + public String toString(){ + StringBuffer outString= new StringBuffer(this.startTag.toString()); + TagPair help=new TagPair(); + Iterator iter=enclosedTags.iterator(); + outString.append(this.startingText); + while(iter.hasNext()){ + if((help=(TagPair)iter.next())==null){ + continue; + }else{ + outString.append(help.toString()); + } + } + outString.append(this.endingText); + outString.append(this.endTag.toString()); + return new String(outString); + } + + public String getWrapped() throws IOException{ + Iterator iter=enclosedTags.iterator(); + StringBuffer returnBuffer=new StringBuffer(); + + returnBuffer.append(wrap(this.startTag)+xmlString(this.startingText)); + while(iter.hasNext()){ + returnBuffer.append(((TagPair)iter.next()).getWrapped()); + } + returnBuffer.append(xmlString(this.endingText)+wrap(this.endTag)); + + + + return new String(returnBuffer); + } + + private String wrap(Tag tag) throws IOException{ + String string=""; + //can be a start tag + if(tag.getTagType().startsWith("Start")){ + return new String(""+tag.getWrappedTagString()+""); + //...or a end tag + }else if (tag.getTagType().startsWith("End")){ + //maybe the end tag of a Start and end tag +// if("EndOfStandAlone".equals(tag.getTagType())){ +// return new String(""); +// }else{ + string=tag.getWrappedTagString(); + return new String(""+string+""); +// } + + //...or text + }else{ + return xmlString(tag.getTagString()); + } + } + /** + * Replaces all characters that mustn't be in XLIFF PCdata + * + * @param string the string to check + * @return the checked string with all characters replaced + * @throws java.io.IOException + */ + private final String xmlString( final String string) throws java.io.IOException { + if (string == null) + return string; // "" + String str = string; + + for(int i=0;i'){ + str=str.substring(0, i)+">"+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='"'){ + str=str.substring(0, i)+"""+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='\''){ + str=str.substring(0, i)+"'"+str.substring(i+1); + continue; + } + } + + return str; + } + + /** + * + */ + public static void resetCounter() { + TagPair.ElementCounter=1; + + } + + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java new file mode 100755 index 000000000000..5b1fb6c62b61 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java @@ -0,0 +1,553 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Convert.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * the main Class + * + * Command Line arguments are reviewed + * and a Converter is constructed + */ +package com.sun.star.tooling.converter; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Calendar; + +import com.sun.star.tooling.DirtyTags.DirtyTagWrapper; + +/** + * The main class of the converter tool + * + * The converter tool is command line based. + * Its classes allow the converting between the + * file formats sdf, gsi and xliff. + * + * Those file formats are used in localization + * of Star-Office and Open-Office. + * + * Information about the whole localization process can be found in + * http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf + * + * @author Christian Schmidt 2005 + * + */ +public class Convert { + + private static Calendar cal; + + private static final String EMPTY = ""; + + /** + * The name of the file containing the debug information + * that where found while converting (every output goes here too) + */ + private static String dbgName = EMPTY; + + /** + * the character that separates the extension from the file name + */ + private static final char extensionSeperator = '.'; + + /** + * the log File + */ + private static File log; + + /** + * the name of the log file + */ + private static String logString = EMPTY; + + /** + * indicates whether existing sources should be overwritten + * without asking + */ + private static boolean overwrite = false; + + /** + * A second Source File needed for GSI Merging + */ + private static File secondSource; + + //private static final char pathSeperator = '\\'; + + /** + * The language that should be the source language + * that means the language to translate from + */ + private static String sourceLanguage = "en-US"; + + /** + * the name of the source file + */ + private static String sourceName = EMPTY; + + /** + * the type of the source file (sdf,xliff,...) + */ + private static String sourceType = EMPTY; + + /** + * The time when converting started + */ + private static String startTime = EMPTY; + /** + * The language that should be the target language + * that means the language to translate to + */ + private static String TargetLanguage = EMPTY; + + /** + * the name of the target file + */ + private static String targetName = EMPTY; + + /** + * the type of the target file (sdf,xliff,...) + */ + private static String targetType = EMPTY; + + /** + * Store the current version ID and number of this tool + */ + final static String version = " Prod.20050710:1255 "; + + /** + * The name of the (original) sdf file used as second source for gsi->sdf merging + */ + private static String secondSourceName=EMPTY; + /** + * Indicate whether strings in xliff files should + * be wrapped with ept/bpt or sub tags to enable translation tools + * to synchronize source language string with there translation + * + * @see http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf + */ + private static boolean doWrap=true; + + + + public static void main(String[] args) throws IOException, Exception { + try{ + + //go, parse and check the command line parameters + ParameterChecker.checkClParameters(args); + ParameterChecker.createContentOfClParameters(); + //Initialize the tagWrapper + DirtyTagWrapper.setWrapping(doWrap); + //create an instance of converter + Converter conv = new Converter(sourceType, sourceName, sourceLanguage, + targetType, targetName, TargetLanguage,secondSourceName, overwrite); + // get aktual time + cal = Calendar.getInstance(); + startTime = cal.getTime().toString(); + //show infos + printPreamble(); + //do the job + conv.convert(); + + showStatistic(); + + //close log, debug... + OutputHandler.closeAll(); + + } catch(Exception e){ + System.out.print("An EXCEPTION occured, please check your commad line settings \n"+e.getMessage()); + System.exit(-1); + }catch(Throwable t){ + System.out.print("A FATAL ERROR occured, please check your commad line settings \n"+t.getMessage()); + System.exit(-1); + } + + } + + /** + * show the command line help + */ + private static void printHelp() { + + final String ls = System.getProperty("line.separator"); + System.out + .println( + + "File Converting Tool 'converter' Version " + + Convert.version + + ls + + "Converts SDF files to wellformed XLIFF or GSI files and vice versa" + ls + + ls + + "Use: " + ls + + "convert [-h]|[SourcePath [TargetPath] [-T Type] [[-S Type [secondSourcePath]] " + ls + + " [-s LanguageID] [-t LanguageID] [-l [LogPath]] [-o]]" + ls + + ls + + "-h show this help." + ls + + "SourcePath path of the file to convert." + ls + + "secondSourcePath path of the SDF file to merge to (GSI -> SDF only!)." + ls + + "TargetPath path where to store the result." + ls + + "LogPath path of the log file" + ls + + "-T Type the type of the target file (xliff,sdf,gsi)" + ls + + "-S Type the type of the source file (xliff,sdf,gsi)" + ls + + "-s LanguageID the ISO language code of the source language (de, fr...)." + ls + + " Default is 'en-US' " + ls + + "-t LanguageID the language code of the target language (de, fr...)." + ls + + " Default is first found Language other than source language." + ls + + "-l [LogPath] write a log file, you can name the file." + ls + + "-o overwrite existing files without asking." + ls + + "-nw disable the wrapping with ept/bpt tags." + ls + + ls + + "The created files were stored in the SourceFile Path if nothing else is given. " + ls + + "The extension is '.xliff','.sdf' depending on the source file and '.log' " + ls + + "for the logfile." + ls); + } + + /** + * show the parameters the converter starts with + * + * @throws IOException + */ + final private static void printPreamble() throws IOException { + OutputHandler.out(EMPTY); + OutputHandler.out("Source File is: " + sourceName); + OutputHandler.out("Target File is: " + targetName); + if (OutputHandler.doLog) { + OutputHandler.out("Log File is: " + logString); + } else { + OutputHandler.out("Log File is: disabled"); + } + + OutputHandler.out(EMPTY); + + } + + /** + * show some statistic data + * + * @throws IOException + */ + final private static void showStatistic() throws IOException { + OutputHandler.dbg(EMPTY); + OutputHandler + .out((targetType.equalsIgnoreCase("xliff") ? "TransUnits written: " + : "Lines written : ") + + Converter.getLineCounter()); + OutputHandler.dbg(EMPTY); + OutputHandler.out("Started at : " + Convert.startTime); + Convert.cal = Calendar.getInstance(); + OutputHandler.out("Finished at : " + Convert.cal.getTime()); + OutputHandler.dbg(EMPTY); + + } + + /** + * Get the extensiion of a file name + * (sdf,xliff,gsi) + * + * @param sourceString the file name + * @return the extension + */ + static protected String extractExtension(String sourceString) { + String ext = sourceString.substring(sourceString + .lastIndexOf(Convert.extensionSeperator) + 1); + return ext; + } + +// static protected String extractFileName(String sourceString) { +// String sName = EMPTY; +// sName = (sourceString.substring(sourceString +// .lastIndexOf(File.separator) + 1, sourceString +// .lastIndexOf(Convert.extensionSeperator))); +// +// return sName; +// } +// +// static protected String extractPath(String sourceString) { +// String sPath = sourceString.substring(0, sourceString +// .lastIndexOf(File.separator) + 1); +// return sPath; +// } + + /** + * + */ + public Convert() { + } + + /** + * + * Verify a parameter array and create content useable by the programm + * from the switches and attributes set at command line + * + * @author Christian Schmidt 2005 + */ + private static class ParameterChecker { + + /** + * Holds the path of the source file + */ + private static String filePath; + /** + * Holds the name of the source file + */ + private static String fileName; + + /** + * Create a new Instance of ParameterChecker + * + * + */ + public ParameterChecker(){}; + /** + * Checks the command line parameters + * + * @param args the parameters to check and to parse + * @throws IOException + */ + private static void checkClParameters(String[] args) throws IOException { + try { + //show help if no attrributes... + if (args.length == 0) { + printHelp(); + System.exit(-1); + } + //...or attribute is -h + if (args[0].equals("-h")) { + printHelp(); + System.exit(0); + } + if (args[0].equals("-ver")) { + System.out.println("File Converting Tool Version "+version); + System.exit(0); + } + //source file Location and path is always first attribute + sourceName = new String(args[0]); + + File source = new File(sourceName); + //break if there is no source to convert + if (!source.exists()) + throw new IOException("ERROR:Can not find Source File '" + + sourceName + "'. Aborting..."); + + // String name=source.getName(); + // String parent=source.getParent(); + // String path=source.getPath(); + + filePath = (source.getParent()==null)?"":source.getParent()+File.separator; //extractPath(sourceName); + fileName = source.getName().substring(0,source.getName().lastIndexOf(extensionSeperator)); + + for (int i = 1; i < args.length; i++) { + + + if ("-s".equals(args[i])) { + if (args.length > i + 1) { + sourceLanguage = args[++i]; + + } else { + throw new ConverterException( + "missing argument for -s source language"); + } + continue; + } + + if ("-S".equals(args[i])) { + if (args.length > i + 1) { + sourceType = args[++i]; + if (args.length > i +1 &&!args[i+1].startsWith("-")) { + secondSourceName = args[++i]; + } + + } else { + throw new ConverterException( + "missing argument for -S source type"); + } + continue; + } + + if ("-T".equals(args[i])) { + if (args.length > i + 1) { + targetType = args[++i]; + + + } else { + throw new ConverterException( + "missing argument for -T target type"); + } + continue; + } + + if ("-l".equals(args[i])) { + OutputHandler.doLog = true; + if (args.length > i + 1 + && (!args[i + 1].startsWith("-"))) { + logString = args[++i]; + } else { + logString = EMPTY; + } + continue; + } + + if ("-o".equals(args[i])) { + overwrite = true; + continue; + } + + if ("-nw".equals(args[i])) { + doWrap = false; + continue; + } + + if ("-h".equals(args[i])) { + printHelp(); + System.exit(0); + } + + if ("-dbg".equals(args[i])) { + OutputHandler.doDebug = true; + continue; + } + + if ("-t".equals(args[i])) { + if (args.length > i + 1) { + TargetLanguage = args[++i]; + } else { + throw new ConverterException( + "missing argument for -t target language"); + } + continue; + } + + if (i == 1 && !args[i].startsWith("-")) { //target file + // found + targetName = args[i]; + continue; + } + //if we come here we + //can not match the Attribute + throw new ConverterException("unknown Attribute: " + + args[i]); + + + }//end for + } catch (ConverterException e) { + OutputHandler.out("ERROR: "+e.getMessage()); + System.exit(-1); + } catch (Throwable t){ + System.out.print("An Error occured while parsing the command line,\n please check your commad line settings.\n "+t.getMessage()); + System.exit(-1); + } + + }//end checkClParameters + + /** + * Creates the appropriate content of what ever data + * we found in the command line + * + * @throws IOException + */ + private static void createContentOfClParameters() throws IOException { + + try { + if (OutputHandler.doDebug) { + // if the -dbg switch is set, we + // create + // a file that gets all information + // produced by this tool + + OutputHandler.dbgFile = new BufferedWriter(new FileWriter( + new File(new String(filePath + fileName + ".dbg")))); + } + + if (OutputHandler.doLog) {// create a logfile? + //given at command line? + if (EMPTY.equals(logString) || logString == null) { + logString = new String(filePath + fileName + ".log"); + } + log = FileMaker.newFile(logString, overwrite); + OutputHandler.logFile = (new BufferedWriter(new FileWriter( + log))); + } + + if (EMPTY.equals(sourceType) || sourceType == null) { + // not given at command line? + if (!(EMPTY.equals(sourceName) || sourceName == null)) { + sourceType = extractExtension(sourceName); + } else { + throw new ConverterException("Source type is missing"); + } + } + + if(sourceType.equalsIgnoreCase("gsi")){ + + if(EMPTY.equals(Convert.secondSourceName)){ + Convert.secondSourceName=filePath+fileName+".sdf"; + } + //secondSource=new File(Convert.secondSourceName); + + } + + if (EMPTY.equals(sourceName)) { + sourceName = filePath + fileName + "." + sourceType; + } + //no target type given at command line? + if (EMPTY.equals(targetType) || targetType == null) { + if (!(EMPTY.equals(targetName) || targetName == null)) { + targetType = extractExtension(targetName); + } else { + throw new ConverterException("Target type is missing"); + + } + } + //no target File specified at command line + if (EMPTY.equals(targetName) || targetName == null) { + targetName = filePath + fileName + "." + targetType; + if (targetName.equals(Convert.secondSourceName)){ + OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same"); + System.exit(0); + }else if (targetName.equals(Convert.sourceName)){ + OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same"); + System.exit(0); + } + }else if (targetName.equals(Convert.secondSourceName)){ + OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same"); + System.exit(0); + }else if (targetName.equals(Convert.sourceName)){ + OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same"); + System.exit(0); + } + + + } catch (ConverterException e) { + OutputHandler.out(e.getMessage()); + } + + } + + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java new file mode 100755 index 000000000000..7ec09bcb411a --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java @@ -0,0 +1,523 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Converter.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Converter.java + * + * create Source and Target + * for converting + * TODO maybe a factory would be good here + */ + +package com.sun.star.tooling.converter; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.xml.sax.EntityResolver; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +/** + * + * This class handles the creating of the source to read from, + * the target to write to and the appropriate DataHandler + * + * @author Christian Schmidt 2005 + */ +public final class Converter { + + /** + * the used charset f.e. UTF-8 + */ + private final static String CHARSET = new String("UTF-8"); + + private static final String EMPTY = new String(""); + + /** + * The DataHandler use to connect reader and writer + */ + private static DataHandler handler; + + /** + * Counting the lines written by a writer + */ + private static int lineCounter; + + /** + * The target to write to + */ + private static DataWriter theTargetWriter; + + + /** + * Overwrite existing files + */ + private boolean overwrite = false; + /** + * The source to read from + */ + private Source reader; + /** + * The name of the source file + */ + private String sourceString; + /** + * the Type of the Source file(SDF,GSI,XLIFF) + */ + private String sourceType; + /** + * The name of the target fille + */ + private String targetString; + /** + * the Type of the Target file(SDF,GSI,XLIFF) + */ + private String targetType; + /** + * The writer that handles the output + */ + private Target writer; + + /** + * The sourceLanguage + */ + String sourceLanguage = "en-US"; + + /** + * The targetLanguage + */ + String targetLanguage = ""; + + /** + * The name of the second source, needed for GSI to SDF merge + */ + private String secondSourceString=EMPTY; + + + /** + * Get the line counter + * @return Returns the lineCounter. + */ + public static int getLineCounter() { + return lineCounter; + } + + /** + * increment the lineCounter + */ + final static void countLine() { + lineCounter++; + } + + /** + * Creates a new instance of Converter + * + * @param sourceType the type of the sourceFile + * @param sourceString the name of the sourceFile + * @param SourceLanguage the ISO Id of the sourceLanguage + * @param targetType the type of the targetFile + * @param targetString the name of the targetFile + * @param TargetLanguage the ISO Id of the targetLanguage + * @param secondSourceString the name of the second sourceFile (GSI merge only) + * @param overwrite indicates whether overwrite existing files + * @throws IOException + * @throws Exception + */ + public Converter(String sourceType, String sourceString, + String SourceLanguage, String targetType, String targetString, + String TargetLanguage,String secondSourceString, boolean overwrite) throws IOException, + Exception { + + this.sourceType = sourceType; + this.sourceString = sourceString; + this.sourceLanguage = SourceLanguage; + this.targetType = targetType; + this.targetString = targetString; + this.targetLanguage = TargetLanguage; + this.secondSourceString=secondSourceString; + this.overwrite = overwrite; + + handler = new DataHandler(); + + if ("sdf".equalsIgnoreCase(sourceType)) { + reader = new SDFSource(); + } else if ("xliff".equalsIgnoreCase(sourceType)||"dbxliff".equalsIgnoreCase(sourceType)) { + reader = new XLIFFSource(); + } else if ("gsi".equalsIgnoreCase(sourceType)) { + reader = new GSISource(); + } else { + throw new ConverterException("Unknown Source File Type: '"+sourceType+"'"); + } + + if ("sdf".equalsIgnoreCase(targetType)) { + writer = new SDFTarget(); + } else if ("xliff".equalsIgnoreCase(targetType)) { + writer = new XLIFFTarget(); + } else if ("gsi".equalsIgnoreCase(targetType)) { + writer = new GSITarget(); + } else { + throw new ConverterException("Unknown Target File Type: '"+targetType+"'"); + } + + } + + /** + * Do the converting from the source file format to the target file format + * + * @throws IOException + */ + public final void convert() throws IOException { + + try { + + reader.convertTo(writer); + + //TODO this belongs in the Target Class + theTargetWriter.flush(); + theTargetWriter.close(); + } catch (Exception e) { + OutputHandler.out(e.getMessage()); + } + + } + + + /** + * + * Encapsulate the reading from an GSI file + * + * @author Christian Schmidt 2005 + * + */ + private class GSISource implements Source { + DataReader theSourceReader; + /** + * Create a new Instance of GSISource + * + * @throws IOException + * @throws Exception + */ + public GSISource() throws IOException { + + theSourceReader = new GSIandSDFMerger(new File(sourceString),new File(secondSourceString), sourceLanguage, + targetLanguage, CHARSET); + } + + public void convertTo(Target t) { + + try { + theTargetWriter = t.getWriter(); + while (handler.fillDataFrom(theSourceReader)) { + + theTargetWriter.getDatafrom(handler); + theTargetWriter.writeData(); + } + } catch (IOException e) { + OutputHandler.out(e.getMessage()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + } + /** + * + * Encapsulate to write to a GSI file + * + * @author Christian Schmidt 2005 + * + */ + private class GSITarget implements Target { + + File target; + + /** + * Create a new Instance of GSITarget + * + * @throws FileNotFoundException + * @throws IOException + */ + public GSITarget() throws FileNotFoundException, IOException { + + target = FileMaker.newFile(targetString, overwrite); + theTargetWriter = new GSIWriter(new BufferedOutputStream( + new FileOutputStream(target)), CHARSET); + } + + public DataWriter getWriter() { + + return theTargetWriter; + } + + } + /** + * + * Encapsulate the reading from an SDF file + * + * @author Christian Schmidt 2005 + * + */ + private final class SDFSource implements Source { + + DataReader Source; + + /** + * Create a new Instance of SDFSource + * @throws IOException + * @throws Exception + */ + public SDFSource() throws IOException, Exception { + + Source = new SDFReader(new File(sourceString), sourceLanguage, + targetLanguage, CHARSET); + } + + public void convertTo(Target t) { + try { + theTargetWriter = t.getWriter(); + while (handler.fillDataFrom(Source)) { + + theTargetWriter.getDatafrom(handler); + theTargetWriter.writeData(); + } + + } catch (IOException e) { + OutputHandler.out(e.getMessage()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + } + /** + * Encapsulate writing to a SDF file + * + * @author Christian Schmidt 2005 + * + */ + private class SDFTarget implements Target { + + /** + * Create a new Instance of SDFTarget + * + * @throws IOException + */ + public SDFTarget() throws IOException { + File target = FileMaker.newFile(targetString, overwrite); + theTargetWriter = new SDFWriter(new BufferedOutputStream( + new FileOutputStream(target)), CHARSET); + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.Converter.Target#getWriter() + */ + public DataWriter getWriter() { + + return theTargetWriter; + } + + } + + /** + * The interface for all convertable sources + * + * @author Christian Schmidt 2005 + * + */ + private interface Source { + + DataReader Source=null; + /** + * Convert this. to the designated target + * @param target the target of the converting + * @throws IOException + */ + abstract void convertTo(Target target) throws IOException; + } + + /** + * The interface for all creatable targets + * + * @author Christian Schmidt 2005 + * + */ + private interface Target { + /** + * The writer to use + */ + public OutputStream writer = null; + + /** + * Get the writer + * this target uses to write the + * data in the correct format. + * + * @return the used DataWriter + */ + abstract DataWriter getWriter(); + + } + /** + * Encapsulate the reading from an XLIFF file + * + * @author Christian Schmidt 2005 + * + */ + private class XLIFFSource implements Source { + File source; + + /** + * Create a new Instance of XLIFFSource + * + * + */ + public XLIFFSource() { + + source = new File(sourceString); + } + + public void convertTo(Target t) throws IOException { + try { + System.setProperty("entityExpansionLimit", "1000000"); + boolean laden = source.canRead(); + if (laden) { + DefaultHandler contentHandler=null; + if("dbxliff".equalsIgnoreCase(sourceType)){ + contentHandler = new XLIFFReader(handler, t + .getWriter(),false); + }else{ + contentHandler = new XLIFFReader(handler, t + .getWriter()); + } + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware( true ); + factory.setValidating( true ); + + SAXParser parser=factory.newSAXParser(); + XMLReader xliffreader=parser.getXMLReader(); + + + +// XMLReader xliffreader = XMLReaderFactory +// .createXMLReader("org.apache.crimson.parser.XMLReaderImpl"); + xliffreader.setErrorHandler(contentHandler); + xliffreader.setContentHandler(contentHandler); + /* one possibility to resolve an extern entity (DTD) */ + EntityResolver res = new Resolver(); + xliffreader.setEntityResolver(res); + /* + * a second possibility to resolve an extern entity (DTD) + * + * xliffreader.setFeature("xml.org/sax/features/validation",true); + * xliffreader.setEntityResolver(new EntityResolver() { + * public InputSource resolveEntity(java.lang.String + * publicId, java.lang.String systemId) throws SAXException, + * java.io.IOException { if (publicId.equals("-//XLIFF//DTD + * XLIFF//EN")) // this deactivates the open office DTD + * return new InputSource(new ByteArrayInputStream( " " .getBytes())); else + * return null; } }); + * + */ + + xliffreader.parse(sourceString); + + } else { + System.out.println("Datei existiert nicht"); + } + + } catch (SAXParseException e) { + try { + theTargetWriter.flush(); + } catch (IOException e1) { + + e1.printStackTrace(); + } + OutputHandler.out("PARSE ERROR Zeile " + e.getLineNumber() + + ", " + e.getMessage()); + + }catch (SAXException e){ + try { + theTargetWriter.flush(); + } catch (IOException e1) { + + e1.printStackTrace(); + } + OutputHandler.out("PARSE EXCEPTION " + e.getMessage()); + } catch (ParserConfigurationException e) { + OutputHandler.out("PARSER Configuration failed\n " + e.getMessage()); + } + } + + } + /** + * Encapsulate writing to a XLIFF file + * + * @author Christian Schmidt 2005 + * + */ + private class XLIFFTarget implements Target { + File target; + + /** + * Create a new Instance of XLIFFTarget + * + * @throws FileNotFoundException + * @throws IOException + */ + public XLIFFTarget() throws FileNotFoundException, IOException { + target = FileMaker.newFile(targetString, overwrite); + theTargetWriter = new XLIFFWriter(new BufferedOutputStream( + new FileOutputStream(target)), CHARSET); + + } + + public DataWriter getWriter() { + + return theTargetWriter; + } + } + + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java new file mode 100755 index 000000000000..07a3708d4366 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java @@ -0,0 +1,79 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: ConverterException.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * a simple exception + * just to seperate + * it from other + * exceptions + */ +package com.sun.star.tooling.converter; + +/** + * @author Christian Schmidt + * + * Thrown if an error occurs during converting from one file format to another + * that does not belong to an other exception + */ +public class ConverterException extends Exception { + + /** + * + */ + public ConverterException() { + super(); + + } + + /** + * @param arg0 + */ + public ConverterException(String arg0) { + super(arg0); + + } + + /** + * @param arg0 + */ + public ConverterException(Throwable arg0) { + super(arg0); + + } + + /** + * @param arg0 + * @param arg1 + */ + public ConverterException(String arg0, Throwable arg1) { + super(arg0, arg1); + + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java new file mode 100755 index 000000000000..e8b4136f185a --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java @@ -0,0 +1,149 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: DataHandler.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * DataHandler.java + * + * take the data from the reader + * and put it to the Writer + * + */ + +package com.sun.star.tooling.converter; + +import java.util.*; + +/** + * Handle the Data to get it from the Source + * readable to the Target + * + * @author Christian Schmidt + */ +public class DataHandler { + + /** + * An arrays that holds the names that will be + * keys for the HashMap containing the data + * + */ + private final String[] dataNames = { "BlockNr", "Project", + "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", + "Width", "SourceLanguageID", "SourceText", "SourceHText", + "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", + "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; + + private static final String EMPTY = new String(""); + + /** + * The HashMap containing the data + */ + private final Map data = new ExtMap(dataNames, null); + + /** Creates a new instance of DataHandler */ + public DataHandler() { + } + + /** + * fill the data from the desired source + * + * @param source where to get the data from + * @return true if data is read and false if null is read + * @throws IOException + * @throws ConverterException + */ + public boolean fillDataFrom(DataReader source) throws java.io.IOException, + ConverterException { + + Map line = null; + + line = source.getData(); + if (line == null){ + + return false; + }else{ + + this.data.putAll(line); + return true; + } + + + } + + /** + * fill this data with the inData + * + * @param inData the data to handle by this handler + */ + public void fillDataWith(Map inData) { + data.putAll(inData); + } + +// public void transfer(DataWriter target, DataReader source) { +// +// source.setHandler(this); +// +// } + + /** + * The designated output is filled with the content of this handler + * + * @param output an array of Maps [0] should hold the source language data [1] the target language data + * @throws java.io.IOException + */ + public void putDataTo(Map[] output) throws java.io.IOException { + String aKey = EMPTY; + for (int j = 0; j < output.length; j++) { + Set keys = output[j].keySet(); + Iterator iter = keys.iterator(); + while (iter.hasNext()) { + aKey = (String) iter.next(); + output[j].put(aKey, data.get(aKey)); + } + } + + } + /** + * The designated output is filled with the content of this handler + * + * @param output a Map that should hold the source language data and the target language data + * @throws java.io.IOException + */ + public void putDataTo(Map output) throws java.io.IOException { + String aKey = EMPTY; + + Set keys = output.keySet(); + Iterator iter = keys.iterator(); + while (iter.hasNext()) { + aKey = (String) iter.next(); + output.put(aKey, data.get(aKey)); + } + + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java new file mode 100755 index 000000000000..59de7ca7e1f4 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java @@ -0,0 +1,79 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: DataReader.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.tooling.converter; + +import java.io.*; +import java.util.*; + +/** + * Gets Line counting from LineNumberReader all Converter Reader classes inherit + * from this. + * The abstract parent class of all converter reader classes + * + * @author Christian Schmidt + */ +abstract public class DataReader extends LineNumberReader { + + /** + * Creates a new instance of DataReader + * + * @param isr + * InputStreamReader used as Source for this class + */ + public DataReader(InputStreamReader isr) { + super(isr); + } + + /** + + * @throws java.io.IOException + * @throws ConverterException + * + * TODO this should no longer use an array as return type better a Map + * + */ + /** + * The next block of the SDF file is reviewed and the Line including the + * source language and the Line including the target Language are given back + * in an array + * + * + * @return A Map including the source language + * and the target Language content are given back + * + * @throws java.io.IOException + * @throws ConverterException + */ + public Map getData() throws java.io.IOException, ConverterException { + return null; + } + + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java new file mode 100755 index 000000000000..c5d6765e3840 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java @@ -0,0 +1,91 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: DataWriter.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * DataWriter.java + * + * parent of all XXXWriter classes used by + * Converter + */ + +package com.sun.star.tooling.converter; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; + +/** + * The abstract parent class of all converter writer classes + * + * @author Christian Schmidt + */ +abstract public class DataWriter extends OutputStreamWriter { + protected final String seperator = new String("|"); + + /** + * the char sequence used as line seperator + */ + protected final String lineEnd = java.lang.System.getProperty( + "line.seperator", "\n"); + + /** Creates a new instance of DataWriter */ + /** + * @param bos the buffered output stream holding the data + * @param encoding the encoding to use for read from bos + * @throws java.io.UnsupportedEncodingException + */ + public DataWriter(BufferedOutputStream bos, String encoding) + throws java.io.UnsupportedEncodingException { + super(bos, encoding); + } + +// abstract protected void writeData(Map[] data) throws java.io.IOException; + + /** + * get the data that should be written from the DataHandler + * + * @param handler the DataHandler having the data + * @throws java.io.IOException + */ + abstract protected void getDataFrom(DataHandler handler) + throws java.io.IOException; + + /** + * write the Data + * + * @throws java.io.IOException + */ + abstract protected void writeData() throws java.io.IOException; + + /** + * @param handler + * @throws IOException + */ + abstract protected void getDatafrom(DataHandler handler) throws IOException; +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java new file mode 100755 index 000000000000..b05767e93ae3 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java @@ -0,0 +1,97 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: ExtMap.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * A special HashMap, + * can be constructed of + * two Arrays + */ +package com.sun.star.tooling.converter; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Christian Schmidt + * + * Create a Hash Map from two Arrays + * + */ +public class ExtMap extends HashMap { + + /** + * + */ + public ExtMap() { + super(); + + } + + /** + * @see java.util.HashMap + * @param arg0 + */ + public ExtMap(int arg0) { + super(arg0); + + } + + /** + * @param arg0 + * @param arg1 + */ + public ExtMap(int arg0, float arg1) { + super(arg0, arg1); + + } + + /** + * @param arg0 + */ + public ExtMap(Map arg0) { + super(arg0); + + } + + // create a new Map from two string arrays + public ExtMap(String[] names, String[] content) { + super(names.length); + if (content == null) + content = new String[names.length]; + for (int i = 0; i < names.length; i++) { + if (i >= content.length) { + break; + } else { + this.put(names[i], content[i]); + } + } + + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java new file mode 100755 index 000000000000..a21b8daa7b1d --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java @@ -0,0 +1,87 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: FileMaker.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * creates new files + * checks if they exist or + * can be overwritten + * + */ +package com.sun.star.tooling.converter; + +import java.io.File; +import java.io.IOException; + +/** + * Creates new files only if the file does not yet exist + * or overwriting is allowed + * + * @author Christian Schmidt 2005 + * + */ +public final class FileMaker { + + /** + * Create a new file if overwriting is not alowed + * ask if existing files should be overwritten + * + * @param fileName the files name to overwrite + * @param overwrite indicates wether the file can be overwritten + * @return the File created from the fileName + * @throws IOException + */ + public final static File newFile(String fileName, boolean overwrite) + throws IOException { + File file = new File(fileName); + if (file.exists()) { + if (!overwrite) { + char c = 0; + + System.out.print("Warning: File " + fileName + + " already exist.\n" + "Overwrite (y/n) ? :"); + byte[] waste = new byte[10]; + System.in.read(waste); + c = (char) waste[0]; + if (c == 'y') { + OutputHandler.out("...overwriting " + fileName); + } else { + OutputHandler.out( + "\nPlease set '-o' switch at command line to overwrite.\n\nProgramm Aborted."); + System.exit(-1); + } + } else { + OutputHandler.out("...overwriting " + fileName); + } + } else { + OutputHandler.out("...creating new target file " + fileName); + } + return file; + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java new file mode 100755 index 000000000000..adb6e358a74c --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java @@ -0,0 +1,250 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: GSIReader.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.converter; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.Map; + +import com.sun.star.tooling.languageResolver.LanguageResolver; +import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; + +/** + * @author Christian Schmidt 2005 + * + */ +public class GSIReader extends DataReader { + /** + * A Map holding an empty GSIBlock + */ + private Map EmptyGSIBlock; + + /** + * @see LanguageResolver + */ + LanguageResolver languageResolver; + + /** + * The source language identifier + */ + protected String sourceLanguage; + + /** + * The target language identifier + */ + protected String targetLanguage; + + /** + * The number of the last block + */ + private String oldBlockNr; + + /** + * A buffer holding one GSILine + */ + private Map GSILineBuffer; + + /** + * Indicates whether to use the buffered line + */ + private boolean useBuffer = false; + + private static final String EMPTY = new String(""); + + /** + * An empty Map to fill with language depending data + */ + private ExtMap EmptyLanguageMap; + + /** + * Indicates whether the first block is read + */ + private boolean isFirst = true; + + private int lineCounter; + + private int blockCounter; + /** + * Indicates whether the last line is read + */ + private boolean lastLineFound = false; + + /** + * Create a new Instance of GSIReader + * + * @param source + * the file to read from + * @param sourceLanguage + * the sourceLanguage (must not be empty) + * @param targetLanguage + * the targetLanguage + * @param charset + * the charset used to read source + * @throws java.io.IOException + * @throws Exception + */ + public GSIReader(File source, String sourceLanguage, String targetLanguage, + String charset) throws java.io.IOException { + super(new InputStreamReader(new FileInputStream(source), charset)); + this.languageResolver = new LanguageResolver(); + this.sourceLanguage = sourceLanguage; + this.targetLanguage = targetLanguage; + + EmptyLanguageMap = new ExtMap(new String[0], new String[0]); + + } + + /** + * Read the next GSIBlock and return the data + * + * @return A Map containing the data of the read GSIBlock the keys for the language depending data are the language id (numeric) the + * single language are acessible with the keys "BlockNr", "resType", "languageNr", "status","content". + * + * @throws IOException + */ + public Map getGSIData() throws IOException { + String help; + Map helpmap; + Map GSIBlock = new HashMap(); + GSIBlock.put(sourceLanguage, EmptyLanguageMap.clone()); + GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); + String line = EMPTY; + String[] splitLine; + Map GSILine; + String[] GSINames = { "BlockNr", "resType", "languageNr", "status", + "content" }; + + while (useBuffer || (line = readLine()) != null) { + + + + if (useBuffer) { + GSILine = GSILineBuffer; + GSIBlock.put(sourceLanguage, EmptyLanguageMap.clone()); + GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); + GSIBlock.put("BlockNr", GSILine.get("BlockNr")); + useBuffer = false; + } else { + this.lineCounter++; + if ((splitLine = split(line)) == null) { + continue; + } + GSILine = new ExtMap(GSINames, splitLine); + if (isFirst) { + GSIBlock.put("BlockNr", GSILine.get("BlockNr")); + oldBlockNr = (String) GSILine.get("BlockNr"); + isFirst = false; + } + } + if (oldBlockNr == null) { + oldBlockNr = (String) GSILine.get("BlockNr"); + } + if (!oldBlockNr.equals((String) GSILine.get("BlockNr"))) { + GSILineBuffer = GSILine; + oldBlockNr = (String) GSILine.get("BlockNr"); + useBuffer = true; + break; + } + String lang; + try { + // Is there the source language in this line? + if ((lang = languageResolver.getISOfromNr((String) GSILine + .get("languageNr"))).equals(this.sourceLanguage)) { + // ok..store it as Source String under the depending + // ressource type + + ((Map) GSIBlock.get(sourceLanguage)).put("Source" + + ResTypeResolver.getInternKey((String) GSILine + .get("resType")), GSILine.get("content")); + // ..maybe the target language? + } else { + if (targetLanguage.equals(EMPTY)) { + // if no target language is given at command line + targetLanguage = lang; + GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); + } + if (lang.equals(this.targetLanguage)) { + + // ok..store it as target String under the depending + // ressource type + ((Map) GSIBlock.get(targetLanguage)).put("Target" + + ResTypeResolver.getInternKey((String) GSILine + .get("resType")), GSILine + .get("content")); + } + } + } catch (LanguageResolvingException e) { + OutputHandler.out("Can not resolve the language "+e.getMessage()); + } + + } + if (line == null) { + if (lastLineFound){ + OutputHandler.out("\n\n"); + OutputHandler.out("GSI Blocks : " + this.blockCounter); + OutputHandler.out("GSI Lines : " + this.lineCounter); + + return null; + }else{ + lastLineFound = true; + this.blockCounter++; + return GSIBlock; + } + } else { + this.blockCounter++; + return GSIBlock; + } + + } + + /** + * Split a GSILine to single fields + * + * @param line + * The line to split + * @return An array containing the contents of the columns in the given line + */ + private String[] split(String line) { + String[] splitLine = (line.substring(0, line.length() - 1)) + .split("\\(\\$\\$\\)"); + if (splitLine.length != 5) + return null; + else + return splitLine; + } + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java new file mode 100755 index 000000000000..085e26475e09 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java @@ -0,0 +1,246 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: GSIWriter.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.tooling.converter; +import java.io.*; +import java.util.Map; + +import com.sun.star.tooling.languageResolver.LanguageResolver; +import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; +/** + * + * @author cs156069 + */ +public class GSIWriter extends DataWriter { + /** + * The seperator used to seperate GSI columns + */ + final String seperator=new String("($$)"); + + /** + * Holding the keys used by a map holding the content of an GSI Line contianing the source language + */ + final static String[] sourceLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TimeStamp"}; + /** + * Holding the keys used by a map holding the content of an GSI Line contianing the target language + */ + final static String[] targetLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; + /** + * Holding the keys used by a map holding the content of an GSI Line contianing the source and the target language + */ + final static String[] outLineNames= {"BlockNr","Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; + + /** + * A map holding the content of an GSI Line contianing the source language + */ + private ExtMap sourceLine=new ExtMap(sourceLineNames,null); + /** + * A map holding the content of an GSI Line contianing the target language + */ + private ExtMap targetLine=new ExtMap(targetLineNames,null); + /** + * A map holding the content of an GSI Line contianing the source and the target language + */ + private ExtMap outData=new ExtMap(outLineNames, null); + + private static final String EMPTY = new String(""); + /** + * The sourceLanguage to use + */ + private String sourceLanguage; + /** + * The sourceLanguage to use + */ + private String targetLanguage; + + /** + * GSILines have a special Line End + */ + private final static String lineEnd="!"+'\r'+'\n'; + //private boolean SourceIsFirst=false; + + /** + * The blockNr of the current line + */ + private String blockNr; + + + + + /** + * Create a new Instance of GSIWriter + * + * @param bos the Buffered Output Stream to write to + * @param charset the used charset + * @throws java.io.UnsupportedEncodingException + */ + public GSIWriter(BufferedOutputStream bos,String charset) throws java.io.UnsupportedEncodingException { + super(bos,charset); + + + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#writeData() + */ + public final void writeData() throws java.io.IOException { + + StringBuffer buffer=new StringBuffer(""); + if(this.sourceLanguage==null&&this.targetLanguage==null){ + LanguageResolver lang =new LanguageResolver(); + try { + this.sourceLanguage=lang.getNrFromISO((String)outData.get("SourceLanguageID")); + this.targetLanguage=lang.getNrFromISO((String)outData.get("TargetLanguageID")); + } catch (LanguageResolvingException e) { + + OutputHandler.out(e.getMessage()); + System.exit(0); + } + } + + + this.blockNr=(String)outData.get("BlockNr"); + // get the values of the found fields + //create the gsi lines + // + //at first the source language line + buffer.append(getSourceLine("Text")); + buffer.append(getSourceLine("HText")); + buffer.append(getSourceLine("QText")); + buffer.append(getSourceLine("Title")); + + //now the target language line + // put them together for output + buffer.append(getTargetLine("Text")); + buffer.append(getTargetLine("HText")); + buffer.append(getTargetLine("QText")); + buffer.append(getTargetLine("Title")); + //ok...put all to disk; + this.write(buffer.toString()); + + } + + /** + * Create a line containing the source string from the data + * @param resType + * @return The StringBuffer containing the line + */ + private StringBuffer getSourceLine(String resType){ + StringBuffer buffer =new StringBuffer(200); + String resString = "Source"+resType; + + String help; + if(EMPTY.equals((String)outData.get(resString))||" ".equals(outData.get(resString))) return new StringBuffer(EMPTY); + else { + // put them together for output + buffer.append(this.blockNr); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(ResTypeResolver.getExternKey(resType)); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(this.sourceLanguage); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append("int"); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(outData.get(resString)); + + // this line is full + // so close it with '! cr lf' + buffer.append(GSIWriter.lineEnd); + Converter.countLine(); + return buffer; + } + + } + /** + * Create a line containing the target string from the data + * @param resType + * @return The StringBuffer containing the line + */ + private StringBuffer getTargetLine(String resType){ + StringBuffer buffer =new StringBuffer(200); + String resString = "Target"+resType; + + if(EMPTY.equals((String)outData.get(resString))||" ".equals(outData.get(resString))) return new StringBuffer(EMPTY); + else { + // put them together for output + buffer.append(this.blockNr); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(ResTypeResolver.getExternKey(resType)); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(this.targetLanguage); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append("ext"); + // seperate the fields with ($$) + buffer.append(this.seperator); + buffer.append(outData.get(resString)); + + // this line is full + // so close it with '! cr lf' + buffer.append(GSIWriter.lineEnd); + Converter.countLine(); + return buffer; + } + + } + + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#writeData(java.util.Map[]) + */ + protected void writeData(Map[] data) throws IOException { + // TODO redesign DataHandler in the way that this is not nessesary any more + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#getDataFrom(com.sun.star.tooling.converter.DataHandler) + */ + protected void getDataFrom(DataHandler handler) throws IOException { + + handler.putDataTo(this.outData); + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#getDatafrom(com.sun.star.tooling.converter.DataHandler) + */ + protected void getDatafrom(DataHandler handler) throws IOException { + + handler.putDataTo(this.outData); + + } +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java new file mode 100755 index 000000000000..ff0348f97d3d --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java @@ -0,0 +1,167 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: GSIandSDFMerger.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.converter; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Merge GSIFiles back to to the original (!) SDFFile + * + * + * @author Christian Schmidt 2005 + * + */ +public class GSIandSDFMerger extends SDFReader { + + int lineCounter=0; + + GSIReader gsiReader; + + private Map temp=new HashMap(); + private int j; + private boolean skip=true; + Map gsiBlock=null; + Map sdfBlock=null; + + private boolean dontLoadGSI=false; + + private int count; + /** + * Merge the GSIFile back to the original(!) SDFFile + * + * @param source the file to read from + * @param sourceLanguage the source language in the source file + * @param targetLanguage the target language in the source file + * @param charset the charset of the files + * @throws java.io.IOException + * @throws Exception + */ + public GSIandSDFMerger(File source, File secondSource,String sourceLanguage, + String targetLanguage, String charset) throws IOException { + // merging GSI and SDF requieres two Sources + //this. is the SDF source + super(secondSource, sourceLanguage, targetLanguage, charset); + //create the GSI Source + + gsiReader=new GSIReader(source,sourceLanguage,targetLanguage,charset); + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataReader#getData() + */ + public Map getData()throws java.io.IOException{ + do{ + skip=false; + this.temp=matchGSI(); + }while(skip); + if(temp==null){ + OutputHandler.out("Blocks merged : "+this.lineCounter); + } + return temp; + + } + + /** + * Read each block of the GSIFile and check whether there is a matching + * block in the SDFFile. Match depends on the BlockNr and BlockId. + * + * @return A Map that contains the source language content + * and the target language content. + * @throws IOException + * @throws ConverterException + */ + public Map matchGSI() throws IOException{ + + + try { + //System.out.println("Start..."); + + if (dontLoadGSI||(gsiBlock=gsiReader.getGSIData())!=null){ + dontLoadGSI=false; + //check if we must update this block + //if so its BlockNr is in the gsi file + if((sdfBlock = super.getData())!=null){ + + if(((String)sdfBlock.get("BlockNr")).equals((String)gsiBlock.get("BlockNr"))){ + + gsiBlock.remove(EMPTY); + //if the target language string is empty this may be caused by an error in the source sdf File + //I don't want to overwrite a possibly correct translation with an empty string + // so remove the target part from the gsiBlock + Map mp=(Map)gsiBlock.get(gsiReader.targetLanguage); + if (mp.size()!=0&&!((String)mp.get("TargetText")).equals("")){ + + // target language part in this gsiBlock +// if(((String)mp.get("TargetText")).equals("")){ +// gsiBlock.remove(targetLanguage); +// } + // count the merged blocks + lineCounter++; + Map helpMap = (Map)gsiBlock.get(super.targetLanguage);//"ja" + sdfBlock.putAll(helpMap); + skip=false; + }else{ + //no target language part in this gsiBlock + skip=true; +// +// return null; + } + }else{ +// skip=true; +// +// // we cant match this gsi block to the current sdf block + // try matching the next sdf block with this gsi line + dontLoadGSI=true; + } + } + return sdfBlock; + } + + } catch (IOException e) { + + e.printStackTrace(); + } + return null; + } + + + + + + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java new file mode 100755 index 000000000000..6a11360cc472 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java @@ -0,0 +1,81 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: LineErrorException.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Exception for errors in + * SDFLines + */ +package com.sun.star.tooling.converter; + + +/** + * This Exeption is thrown if a DataReader finds an error in a read Line + * f. e. wrong column number + * + * @author Christian Schmidt 2005 + * + */ +public class LineErrorException extends Exception { + + public int tokenCount; + /** + * + */ + public LineErrorException() { + super(); + + } + + /** + * @param arg0 + */ + public LineErrorException(String arg0) { + super(arg0); + + } + + /** + * @param arg0 + */ + public LineErrorException(Throwable arg0) { + super(arg0); + + } + + /** + * @param arg0 + * @param arg1 + */ + public LineErrorException(String arg0, Throwable arg1) { + super(arg0, arg1); + + } + + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java new file mode 100755 index 000000000000..997c05a70b4f --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java @@ -0,0 +1,228 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: OutputHandler.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Creates logfile and file for debug information + * + */ +package com.sun.star.tooling.converter; + +import java.io.BufferedWriter; +import java.io.IOException; + +/** + * Handle the whole output during converting process except the converted files. + * Write output to logfiles and to screen depending on switches given + * at command line. + * @author Christian Schmidt 2005 + * + */ +public class OutputHandler { + + private static final String EMPTY = ""; + + /** + * The logfile to write + */ + public static BufferedWriter logFile; + + /** + * Indicates whether excisting files should be overwritten + */ + public static boolean doLog = false; + + /** + * Indicate whether the debug information should be written + */ + public static boolean doDebug = false; + + /** + * The File to write the debug information to + */ + public static BufferedWriter dbgFile; + + /** + * Write the data to screen and if the switches were set to + * logfile and debugfile + * + * @param out the String to write + */ + final static void out(String out) { + try { + if (doDebug) + OutputHandler.dbg(out); + + if (!doLog || logFile == null) { + System.out.println(out); + } else { + System.out.println(out); + if (EMPTY.equals(out)) { + OutputHandler.log(EMPTY); + } else { + OutputHandler.log(out); + } + } + } catch (IOException e) { + + OutputHandler.log(e.toString()); + } + } + + /** + * make a dot on the screen to show the user that it is going on + */ + final static void printDot() { + System.out.print("."); + + } + + /** + * write the data to log file and if the switch is set + * to the debug file + * + * @param out the String to write + */ + final static void log(String out) { + try { + if(out==null) return; + if (doDebug) + + OutputHandler.dbg(out); + + if (doLog) { + if (!EMPTY.equals(out)) { + logFile.write(out); + } + logFile.newLine(); + logFile.flush(); + } + } catch (IOException e) { + + System.out.println(e.getMessage()); + } + } + + /** + * write the string to the debug file + * + * @param out the String to write + * @throws IOException + */ + final static void dbg(String out) throws IOException { + if(out==null) return; + if (doDebug) { + if (!EMPTY.equals(out)) { + dbgFile.write(out); + + } + dbgFile.newLine(); + dbgFile.flush(); + } + } + + /** + * Set a new value to indicate whether a debug file should be written or not + * + * @param doDebug + * The debug value to set. + */ + private static void setDebug(boolean doDebug) { + OutputHandler.doDebug = doDebug; + } + + // /** + // * @return Returns the doDebug. + // */ + // private static boolean isDebug() { + // return doDebug; + // } + + /** + * Set the debug file to write to. + * + * @param dbgFile + * The debug File to use. + */ + private static void setDbgFile(BufferedWriter dbgFile) { + OutputHandler.dbgFile = dbgFile; + } + + /** + * @return Returns the debug File. + */ + private static BufferedWriter getDbgFile() { + return dbgFile; + } + + /** + * @param doLog + * The log value to set. + */ + private static void setLog(boolean doLog) { + OutputHandler.doLog = doLog; + } + + /** + * @return Returns the log value. + */ + private static boolean isLog() { + return doLog; + } + + /** + * @param logFile + * The logFile to set. + */ + private static void setLogFile(BufferedWriter logFile) { + OutputHandler.logFile = logFile; + } + + /** + * @return Returns the logFile. + */ + private static BufferedWriter getLogFile() { + return logFile; + } + + /** + * @throws IOException + * close log and dbg + */ + public static void closeAll() throws IOException { + if (OutputHandler.logFile != null) { + OutputHandler.logFile.flush(); + OutputHandler.logFile.close(); + } + if (OutputHandler.dbgFile != null) { + OutputHandler.dbgFile.flush(); + OutputHandler.dbgFile.close(); + } + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java new file mode 100755 index 000000000000..f53fe0101275 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java @@ -0,0 +1,71 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: ResTypeResolver.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.converter; + +import java.util.Map; + +/** + * Helps resolving restype descriptors used outside the tool to + * restype descriptors used by this tool + * + * @author Christian Schmidt 2005 + * + */ +public class ResTypeResolver { + final static String[] inFields={"Text","QText","HText","Title"}; + final static String[] outFields={"res","res-quickhelp","res-help","res-title"}; + final static Map internKeys=new ExtMap(inFields,outFields); + final static Map externKeys=new ExtMap(outFields,inFields); + + /** + * Get the intern key depending to the given extern key + * + * @param externKey the externKey {"res","res-quickhelp","res-help","title"} + * @return the depending intern key + */ + public static String getInternKey(String externKey){ + return (String)externKeys.get(externKey); + } + + /** + * Get the extern key to the given intern key + * + * @param internKey the internal key + * @return the external key + */ + public static String getExternKey(String internKey){ + return (String)internKeys.get(internKey); + } + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java new file mode 100755 index 000000000000..29a9ee2e528a --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java @@ -0,0 +1,98 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Resolver.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 27.01.2005 + * + */ +package com.sun.star.tooling.converter; + +import java.io.IOException; +import java.io.InputStream; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Resolve external entities by provide the + * XLIFF DTD stored in the jar file + */ +public class Resolver implements EntityResolver { + + /** + * Resolver constructor. + */ + public Resolver() { + } + + /** + * Allow the application to resolve external entities. + * + * The Parser will call this method before opening any external entity + * except the top-level document entity (including the external DTD subset, + * external entities referenced within the DTD, and external entities + * referenced within the document element): the application may request that + * the parser resolve the entity itself, that it use an alternative URI, or + * that it use an entirely different input source. + */ + + /* (non-Javadoc) + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + + if ((publicId != null) && (publicId.equals("-//XLIFF//DTD XLIFF//EN"))) { + systemId = "dtd:///xliff.dtd"; + } + if (systemId != null) { + if (systemId.startsWith("dtd://")) { + String dtd = "com/sun/star/tooling/converter/dtd" + + systemId.substring(6); + ClassLoader cl = this.getClass().getClassLoader(); + InputStream in = cl.getResourceAsStream(dtd); + InputSource ins = new InputSource(in); + ins.setSystemId(systemId); + return ins; + } /* + * else if ( systemId.startsWith("jar:") ) { try { URL url=new + * URL(systemId); JarURLConnection jarConn = + * (JarURLConnection)url.openConnection(); InputSource ins=new + * InputSource(jarConn.getInputStream()); + * ins.setSystemId(systemId); return ins; } + * catch(MalformedURLException me){ throw new SAXException(me); + * Incorrect URL format used } } + */ + } + return null; + } + +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java new file mode 100755 index 000000000000..4c0c234778ec --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java @@ -0,0 +1,635 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: SDFReader.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * SDFReader.java + * + * + */ + +package com.sun.star.tooling.converter; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.DecimalFormat; +import java.util.*; + +/** + * + * SDFReader is a FileReader that knows about + * the content of SDFFiles + * + * A SDFBlock is read of the given file. A SDFBlock + * consists of all SDFLines that are traanslations of the + * same String and the SDFLine containing the source string + * itself. SDFFile lines are read and checked whether they + * have the allowed column count and don't contain illeagal + * characters (like most unprintable characters below 0x00df). + * If the given source language is not found in the first + * block of SDFLines a ConverterException is thrown at runtime. + * If the given target language is "" (that means not given) + * the first language that is not the given source language + * is taken for target language. The found values are returned in HashMaps that + * use the following keys: + *
+ * "BlockNr" originally coming from reading the sdf file, contains 'block nr in sdf file'+'-'+'hash value of the sdf id fields'.
+ * "Project" first column in sdf file format.
+ * "SourceFile" second column in sdf file format.
+ * "Dummy" third column in sdf file format.
+ * "ResType" 4. column in sdf file format.
+ * "GID" 5. column in sdf file format.
+ * "LID" 6. column in sdf file format.
+ * "HID" 7. column in sdf file format.
+ * "Platform" 8. column in sdf file format.
+ * "Width", 9. column in sdf file format.
+ * "SourceLanguageID" 10. column in sdf file format(in the line with the source language).
+ * "SourceText" 11. column in sdf file format(in the line with the source language).
+ * "SourceHText" 12. column in sdf file format(in the line with the source language).
+ * "SourceQText" 13. column in sdf file format(in the line with the source language).
+ * "SourceTitle" 14. column in sdf file format(in the line with the source language).
+ * "TargetLanguageID" 10. column in sdf file format (in the line with the target language).
+ * "TargetText" 11. column in sdf file format (in the line with the target language).
+ * "TargetHText" 12. column in sdf file format (in the line with the target language).
+ * "TargetQText" 13. column in sdf file format (in the line with the target language).
+ * "TargetTitle", 14. column in sdf file format (in the line with the target language).
+ * "TimeStamp" 15. column in sdf file format.
+ * + * @author Christian Schmidt 2005 + * + */ + +public class SDFReader extends DataReader { + + /** + * an array of the SDF files column names + */ + final static String[] fieldnames = { "Project", "SourceFile", "Dummy", + "ResType", "GID", "LID", "HID", "Platform", "Width", "LanguageID", + "Text", "HText", "QText", "Title", "TimeStamp" }; + + /** + * an array of the SDF files column names if the source language is in + */ + final static String[] sourceLineNames = { "Project", "SourceFile", "Dummy", + "ResType", "GID", "LID", "HID", "Platform", "Width", + "SourceLanguageID", "SourceText", "SourceHText", "SourceQText", + "SourceTitle", "TimeStamp" }; + + /** + * an array of the SDF files column names if the target language is in + */ + final static String[] targetLineNames = { "Project", "SourceFile", "Dummy", + "ResType", "GID", "LID", "HID", "Platform", "Width", + "TargetLanguageID", "TargetText", "TargetHText", "TargetQText", + "TargetTitle", "TimeStamp" }; + + final static String EMPTY = new String(""); + + private int dotCount = 0; + + /** + * a Map containing an SDF line with source language + */ + private Map sourceMap; + + /** + * a Map containing an SDF line with target language + */ + private Map targetMap; + + /** + * a Map containing an SDF + */ + private Map SDFMap; + + /** + * a Map Array containing one SDF source language line and one SDF target + * language line + */ + private Map[] data = { sourceMap, targetMap }; + + /** + * The Id of the current SDFBlock + */ + private String CurrentBlockId; + + /** + * The SDF file to read from + */ + private File sourceFile; + + /** + * The language in the source file that should be handelt as source language + */ + protected String sourceLanguage; + + /** + * The language in the source file that should be handelt as target language + */ + protected String targetLanguage; + + /** + * A counter holding the number of blocks just read + * from this file + */ + private long blockNr = 0;// If we use Integer, more then numbers greater than 128k would be signed + + /** + * A counter holding the number of skipped lines that means + * lines that can not be worked with because they contain an error + */ + private int skippedLines = 0; + + /** + * This switch is set for indicating that all source file lines + * are read and no lines remain buffered. Finding this like 'true' + * means the source file is finished + */ + private boolean endIt = false; + + /** + * Indicates whether the targetLanguage is found in this source file so far + */ + private boolean foundTarget = false; + /** + * Indicates whether the sourceLanguage is found in this source file so far + */ + private boolean foundSource = false; + + /** + * Counts how many lines were skipped because the language is + * neither sourceLanguage nor targetLanguage + */ + private int langMiss; + + /** + * Indicates whether there is a line in the read buffer or not + */ + private boolean useBuffer = false; + + /** + * A buffer for SDFLines + */ + private String lineBuffer; + + /** + * The buffer for the already splitted SDFLines + */ + private String[] splittedLineBuffer; + + /** + * Counts how many Blocks were skipped + * f.e. because no sourceLanguage is found + * in it + */ + private int skippedBlocks; + + /** + * Counts the blocks without targetLanguage + */ + private int targetLangMiss; + + /** + * Counts the blocks without sourceLanguage + */ + private int sourceLangMiss; + + /** + * Counts the lines where no targetLanguage line was found + * and so empty lines were created + */ + private int targetLangCreate; + + + DecimalFormat blockNrFormatter = new DecimalFormat("000000"); + + /** + * The hashcode of the current block + */ + private int CurrentBlockHash; + + private boolean skip; + + /** + * Create a new Instance of SDFREader + * + * @param source the file to read from + * @param sourceLanguage the sourceLanguage (must not be empty) + * @param targetLanguage the targetLanguage + * @param charset the charset used to read source + * @throws java.io.IOException + * @throws Exception + */ + public SDFReader(File source, String sourceLanguage, String targetLanguage, + String charset) throws java.io.IOException { + super(new InputStreamReader(new FileInputStream(source), charset)); + sourceFile = source; + this.sourceLanguage = sourceLanguage; + this.targetLanguage = targetLanguage; + String line; + String[] splitLine; + //read first line to get the first + //SDF block id + mark(16000); + if ((line = readLine()) != null) { + if ((splitLine = split(line)) != null){ + this.CurrentBlockId = getSDFBlockId(splitLine); + this.CurrentBlockHash=this.CurrentBlockId.hashCode(); + //found the first + this.blockNr++; + } + this.splittedLineBuffer = splitLine; + } + reset(); + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataReader#getData() + */ + public Map getData()throws IOException { + + Map map=new HashMap(); +// do { + this.skip=false; + Map[] help=readBlock(); + if(help==null||help[1]==null||help[0]==null){ + return null; +// }else if (help[1].get("TargetLanguageID")==null||help[0].get("SourceLanguageID")==null) { +// OutputHandler.log("Missing Language Id in block "+blockNr+"\nthe block is skipped." ); +// this.skippedBlocks++; +// this.skip=true; + }else{ + map.putAll(help[1]); + map.putAll(help[0]); + + } +// }while(this.skip=true); + return map; + } + + + /** + * Read a Block from the sdf file and return + * @return a Map[] where [0] holds the source and [1] the target language data. + * + * @throws java.io.IOException + */ + public Map[] readBlock() throws java.io.IOException { + String line = EMPTY; + String blockId = EMPTY; + String[] splittedLine = null; + data[0]=new ExtMap(); + data[1]=new ExtMap(); + String help; + String c = null; + //read next line or use buffered line + while (useBuffer || (line = readLine()) != null) { //works because '||' is shortcut + + try { + // buffer used? + if (useBuffer) { + line = this.lineBuffer; + splittedLine = this.splittedLineBuffer; + this.SDFMap = new ExtMap(SDFReader.fieldnames, splittedLine); + + try { + checkLanguage(splittedLine); + } catch (ConverterException e) { + throw e; + }finally{ + + useBuffer = false; + } + } else { + //...are there wrong characters? + if ((check(line)).length() < line.length()) { + throw new LineErrorException(getLineNumber() + + " : Line contains wrong character " + //+ Integer.toHexString(Integer.parseInt(c)) + + " \n" + line); + } + //...is the number of columns ok? + if ((splittedLine = split(line)) == null) { + + throw new LineErrorException(super.getLineNumber() + + " : Line has wrong column number \n" + line); + //continue; + } else { + // TODO makeDot is better in Data Handler + makeDot(); + // ...is this line in a new SDF block ? + if ((blockId = getSDFBlockId(splittedLine)) + .equals(CurrentBlockId)) { + + this.SDFMap = new ExtMap(SDFReader.fieldnames, + splittedLine); + //what language is in it ? + checkLanguage(splittedLine); + + } else { + + /* + * we found the next block , but do we have the + * target text? + */ + + if (!foundTarget) { + createTargetLine(); + } + + blockNr++; + splittedLineBuffer = splittedLine;//read one line + // too much so + // buffer it + lineBuffer = line; + useBuffer = true;//reset(); + + this.CurrentBlockId = blockId; + this.CurrentBlockHash=this.CurrentBlockId.hashCode(); + + /* ...and what about the source text ? */ + if (!foundSource) { + + OutputHandler + .log("Error in Line:" + + getLineNumber() + + "Source Language is missing maybe " + + "previous block has an error.\nBlock " + + (blockNr - 1) + + " is skipped. before line: \n" + + line); + + foundTarget = false;//no target without source + skippedBlocks++; + skippedLines++; + sourceLangMiss++; + continue;// skip output of this block if no + // source language is found + + } + + break; + + } + } + + } + + } catch (LineErrorException e) { + + OutputHandler.log(e.getMessage()); + this.skippedLines++; + } catch (ConverterException e) { + OutputHandler.log(e.getMessage()); + } + + } + // did we read the whole stuff? + if (null != line) { + // no + foundSource = false; + foundTarget = false; + + return this.data; + + } else { + // ok , its the end but is everything written now? + if (!endIt) { + // there is something to write + // but next time we can end it + endIt = true; + if(!foundTarget){ + createTargetLine(); + } + // write + return this.data;//last lines + } else { + + showStat(); + return null; + } + } + // }catch(ConverterException e) { + // Converter.log(e.getMessage()); + // return null; + // } + } + + /** + * + */ + private void createTargetLine() { + targetLangMiss++; + // if not, create one ... + data[1] = new ExtMap(SDFReader.targetLineNames, + splittedLineBuffer); + data[1].put("TargetLanguageID", + this.targetLanguage); + if ((String) data[1].get("TargetText") != EMPTY) + data[1].put("TargetText", EMPTY); + if ((String) data[1].get("TargetHText") != EMPTY) + data[1].put("TargetHText", EMPTY); + if ((String) data[1].get("TargetQText") != EMPTY) + data[1].put("TargetQText", EMPTY); + if ((String) data[1].get("TargetTitle") != EMPTY) + data[1].put("TargetTitle", EMPTY); + this.data[1].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toString(this.CurrentBlockHash)); + targetLangCreate++; + } + + /** + * Show the statistic information got while + * reading the file + * + * @throws IOException + */ + private void showStat() throws IOException { + OutputHandler.out(EMPTY);OutputHandler.out(EMPTY); + // OutputHandler.out("Hashes: " + (theHashes.size()) + " "); + OutputHandler.out("Blocks found: " + blockNr + " "); + OutputHandler.out(EMPTY); + OutputHandler.out("Lines read: " + (getLineNumber()) + " "); + OutputHandler + .dbg("Lines created " + (targetLangCreate) + " "); + OutputHandler.dbg(" -------"); + OutputHandler.dbg("Lines total: " + + (getLineNumber() + targetLangCreate) + " "); + OutputHandler.dbg("Lines skipped: " + skippedLines + " "); + + OutputHandler.dbg("Source Language misses: " + sourceLangMiss + " "); + OutputHandler.dbg("Target Language misses: " + targetLangMiss + " "); + OutputHandler.dbg("Blocks found: " + blockNr + " "); + OutputHandler.dbg("Blocks skipped: " + skippedBlocks + " "); + if ((sourceLangMiss + skippedBlocks + skippedLines) > 0) + OutputHandler.out("\n---! Errors found !--- view Logfile.\n\n" + + "To enable logfile use -l option at command line.\n" + + "For help type 'convert -h {Enter}'.\n"); + } + + /** + * Check the current line whether the source language + * or target language is in it + * + * @throws ConverterException if a not needed language or no target language is found + * in this block + * @throws IOException + * + */ + final private void checkLanguage(String[] splittedLine) + throws ConverterException, IOException { + String langID = (String) SDFMap.get("LanguageID"); + + //maybe the source language is in this line + if (!foundSource && this.sourceLanguage.equals(langID)) { +// found the next source language line + this.data[0] = new ExtMap(SDFReader.sourceLineNames, splittedLine); + +// this.data[0].put("BlockNr", Integer.toHexString(blockNr)); +// this.data[0].put("BlockHash", Integer.toHexString(this.CurrentBlockHash)); + this.data[0].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toHexString(this.CurrentBlockHash)); +// this.data[0].put("BlockHash", blockHashFormatter.format(this.CurrentBlockHash)); + foundSource = true; + return; + + } else { + // or the target language is in this line + if (!foundTarget) { + //no target language is given at command line + if (this.targetLanguage.equals(EMPTY)) { + //try if we can use the current lines language for target + // language + if (!langID.equals(this.sourceLanguage)) { + //yes , we can use this lines laanguage as target + this.targetLanguage = langID; + + //source and target language both are known: show it + OutputHandler.out("Source Language is: " + + this.sourceLanguage + " "); + OutputHandler.out("Target Language is: " + + this.targetLanguage + " "); + OutputHandler.out(EMPTY); + System.out.println("Start"); + + } else { + throw new ConverterException("(" + getLineNumber() + + ") No target language found: " + + this.targetLanguage); + } + } + if (this.targetLanguage.equals(langID)) { + this.data[1] = new ExtMap(SDFReader.targetLineNames, + splittedLine);// found the next target language line + this.data[1].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toHexString(this.CurrentBlockHash)); + foundTarget = true; + + return; + } + }//end !foundTarget + } + //if we go here we dont need the found language... + throw new ConverterException("found not needed language '" + + this.SDFMap.get("LanguageID") + "' in Line: " + + getLineNumber()); + + } + + /** + * Make a dot on the screen to show the user that it is going on + */ + private void makeDot() { + int count = 0; + if ((count = (int) super.getLineNumber() / 1000) > this.dotCount) { + this.dotCount = count; + OutputHandler.printDot(); + } + + } + + /** + * split the SDFLine in its columns + * + * @param line the current SDFLine + * @return the splitted SDFLine as array of String + * or null if an error occours + * @throws IOException + */ + private String[] split(String line) throws IOException { + check(line); + String[] splitLine; + if ((splitLine = line.split("\t")).length == 15) + return splitLine; + else + //an error occured + return null; + } + + /** + * create a block Id from a splitted SDFLine + * the blockId consists of the column one to eight of an SDF File + * + * @param splitLine the line to create a block id from + * @return the blockId as String + */ + private String getSDFBlockId(String[] splitLine) { + StringBuffer BlockId = new StringBuffer(""); + for (int i = 0; i < 8; i++) { + BlockId.append(splitLine[i]); + } + return BlockId.toString(); + } + +// public final boolean canRead() { +// return this.sourceFile.canRead(); +// } + + /** + * Check if there are not allowed characters in this line + * + * @param line the SDFLine to check + * @return if everything, ok the original + * else the wrong character as String + * + * @throws java.io.IOException + */ + private String check(String line) throws java.io.IOException { + char c = ' '; + for (int i = 0; i < line.length(); i++) { + c = line.charAt(i); + if (c < 30 && c != 9) { + return (new Character(c)).toString(); + } + + } + return line; + + } +} \ No newline at end of file diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java new file mode 100755 index 000000000000..98eb8c856e6a --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java @@ -0,0 +1,175 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: SDFWriter.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * SDFWriter.java + * + * + */ + +package com.sun.star.tooling.converter; +import java.io.*; +import java.util.Map; + +/** + * Write data to a SDFFile + * + * @author Christian Schmidt 2005 + * + */ +public class SDFWriter extends DataWriter { + /** + * the seperator the seperate columns + */ + final String seperator=new String("\t"); + /** + * an array of the SDF files column names if the source language is in + */ + final static String[] sourceLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TimeStamp"}; + /** + * an array of the SDF files column names if the target language is in + */ + final static String[] targetLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; + /** + * an array of the SDF files column names if the source and the target language is in + */ + final static String[] outLineNames= {"BlockNr","Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; + + /** + * A Map holding the source language line content + */ + private ExtMap sourceLine=new ExtMap(sourceLineNames,null); + /** + * A Map holding the target language line content + */ + private ExtMap targetLine=new ExtMap(targetLineNames,null); + /** + * A Map holding the whole content for output + */ + private ExtMap outData=new ExtMap(outLineNames, null); +// private ExtMap SDFLine; +// private InputStreamReader isr; + /** + * The language to translate from + */ + private String sourceLanguage; + /** + * The language to translate to + */ + private String targetLanguage; + +// private boolean SourceIsFirst=false; + + + + + /** + * Create a new Instance of SDFWriter + * + * @param bos BufferedWriter to write to + * @param charset the charset to use to write + * @throws java.io.UnsupportedEncodingException + */ + public SDFWriter(BufferedOutputStream bos,String charset) throws java.io.UnsupportedEncodingException { + super(bos,charset); + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#writeData() + */ + public final void writeData() throws java.io.IOException { + + StringBuffer buffer=new StringBuffer(""); + + // get the values of the found fields + //create the two sdf lines + + //at first the source language line + for(int i=0;i + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * XLIFFReader.java + * + * + */ +package com.sun.star.tooling.converter; + +import java.io.IOException; +import java.util.Hashtable; +import java.util.Map; + +import com.sun.star.tooling.languageResolver.LanguageResolver; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.AttributesImpl; +import org.xml.sax.helpers.DefaultHandler; + + +/** + * Parse the given file and extract the content needed. + *
+ * This Reader understands the parts of the + * xliff spezification used to translate + * the strings in Star-Office and Open-Office. + *
+ * The given file is parsed and the content is stored in a HashMap with those keys: + *
+ * "BlockNr" originally coming from reading the sdf file, contains 'block nr in sdf file'+'-'+'hash value of the sdf id fields'.
+ * "Project" first column in sdf file format.
+ * "SourceFile" second column in sdf file format.
+ * "Dummy" third column in sdf file format.
+ * "ResType" 4. column in sdf file format.
+ * "GID" 5. column in sdf file format.
+ * "LID" 6. column in sdf file format.
+ * "HID" 7. column in sdf file format.
+ * "Platform" 8. column in sdf file format.
+ * "Width", 9. column in sdf file format.
+ * "SourceLanguageID" 10. column in sdf file format(in the line with the source language).
+ * "SourceText" 11. column in sdf file format(in the line with the source language).
+ * "SourceHText" 12. column in sdf file format(in the line with the source language).
+ * "SourceQText" 13. column in sdf file format(in the line with the source language).
+ * "SourceTitle" 14. column in sdf file format(in the line with the source language).
+ * "TargetLanguageID" 10. column in sdf file format (in the line with the target language).
+ * "TargetText" 11. column in sdf file format (in the line with the target language).
+ * "TargetHText" 12. column in sdf file format (in the line with the target language).
+ * "TargetQText" 13. column in sdf file format (in the line with the target language).
+ * "TargetTitle", 14. column in sdf file format (in the line with the target language).
+ * "TimeStamp" 15. column in sdf file format.
+ * @ + * @author Christian Schmidt 2005 + * + */ +public class XLIFFReader extends DefaultHandler { + + /** + * A String array holding the keys used by the HashMap holding the Data + */ + private final String[] dataNames = { "BlockNr", "Project", + "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", + "Width", "SourceLanguageID", "SourceText", "SourceHText", + "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", + "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; + + /** + * Used to index in the data array + */ + static int index = 0; + + /** + * The Map that holds the data returned by this class + */ + private Map moveData = new ExtMap(); + + /** + * A Map that holds yet incomplete data + * until all depending transunits are found + */ + private Hashtable DataStore = new Hashtable(); + + /** + * An Elements name + */ + private String name = new String(""); + + /** + *List of Attributes used by an Element + */ + private Attributes attrs; + +// private String tagElement = new String(""); + + /** + * Indicates whether the next found content string should be printed + */ + private boolean printThis = false; + /** + * Indicates whether the next found content string should be stored + */ + private boolean storeIt = false; + + /** + * data holds the information created while parsing + * + */ + private String[] data = new String[26]; + + /** + * The handler used by this class + */ + private final DataHandler handler; + /** + * The target used by this class + */ + private final DataWriter target; + +// private boolean searchForText = false; + + /** + * counts how many dots are made + */ + private int dotCount; + + /** + * Counts how many Trans Units are read + */ + private int transUnitCounter; + + /** + * used source Language + */ + private String sourceLanguage; + + /** + * used target language + */ + private String targetLanguage; + + /** + * indicates whether this is the first Transunit + */ + private boolean isFirst = true; + + private static final String EMPTY = new String(""); + + /** + * the last index in data where something is written + */ + private int oldindex; + +// private boolean isBptEptTag; + +// private String innerString; +// +// private String key; + + /** + * Index for the BlockNr in the data array + */ + private static final int BLOCKNR_IDX = 0; + /** + * Index for the Project in the data array + */ + private static final int PROJECT_IDX = 1; + /** + * Index for the Sourcefile name in the data array + */ + private static final int SOURCEFILE_IDX = 2; + /** + * Index for the 'dummy' in the data array + */ + private static final int DUMMY_IDX = 3; + /** + * Index for the Group Id in the data array + */ + private static final int GID_IDX = 4; + /** + * Index for the Local Id in the data array + */ + private static final int LID_IDX = 5; + /** + * Index for the Help Id in the data array + */ + private static final int HID_IDX = 6; + /** + * Index for the Platform in the data array + */ + private static final int PLATFORM_IDX = 7; + /** + * Index for the 'Width' in the data array + */ + private static final int WIDTH_IDX = 8; + /** + * Index for the Sourcelanguage Id in the data array + */ + private static final int SOURCE_LANGUAGE_ID_IDX = 10; + /** + * Index for the Source Text in the data array + */ + private static final int SOURCE_TEXT_IDX = 11; + /** + * Index for the Source Helptext in the data array + */ + private static final int SOURCE_HELPTEXT_IDX = 12; + /** + * Index for the Source Quickhelp Text in the data array + */ + private static final int SOURCE_QUICK_HELPTEXT_IDX = 13; + /** + * Index for the Source Titletext in the data array + */ + private static final int SOURCE_TITLETEXT_IDX = 14; + /** + * Index for the Timestamp in the data array + */ + private static final int TIMESTAMP_IDX = 15; + /** + * Index for the res type in the data array + */ + private static final int RESTYPE_IDX = 16; + /** + * Index for the Target Language Id in the data array + */ + private static final int TARGET_LANGUAGE_ID_IDX = 20; + /** + * Index for the Target Text in the data array + */ + private static final int TARGET_TEXT_IDX = 21; + /** + * Index for the Target Helptext in the data array + */ + private static final int TARGET_HELP_TEXT_IDX = 22; + /** + * Index for the Target Quickhelp Text in the data array + */ + private static final int TARGET_QUICKHELP_TEXT_IDX = 23; + /** + * Index for the Target Titletext in the data array + */ + private static final int TARGET_TITLE_TEXT_IDX = 24; + /** + * Index for the Found Parts Counter in the data array + */ + private static final int FOUND_PARTS_COUNTER_IDX = 18; + + /** + * used to find the matching ISO or RFC3066 language code + */ + LanguageResolver languageResolver; + + private boolean doBlockCompleteCheck=true; + + + + /** + * Create a new Instance of XLIFFReader + * + * @param handler the DataHandler to use + * @param target the target used + * @throws IOException + */ + public XLIFFReader(DataHandler handler, DataWriter target) throws IOException { + this.languageResolver = new LanguageResolver(); + this.handler = handler; + this.target = target; + } + + /** + * Create a new Instance of XLIFFReader + * + * @param handler the DataHandler to use + * @param target the target used + * @param doBlockCompleteCheck indicates whether every single transunit should be returned or the whole block data is to be collected + * + * @throws IOException + */ + public XLIFFReader(DataHandler handler, DataWriter target,boolean doBlockCompleteCheck) throws IOException { + this(handler, target); + this.languageResolver = new LanguageResolver(); + this.doBlockCompleteCheck=doBlockCompleteCheck; + + } + + /** + * delete and initialize the data content + */ + public void initData() { + for (int i = BLOCKNR_IDX; i < SOURCE_LANGUAGE_ID_IDX; i++) { + data[i] = ""; + } + for (int i = SOURCE_TEXT_IDX; i < TIMESTAMP_IDX; i++) { // skip Time Stamp + data[i] = ""; + } + for (int i = RESTYPE_IDX; i < TARGET_LANGUAGE_ID_IDX; i++) { // skip Source language ID + data[i] = ""; + } + for (int i = TARGET_TEXT_IDX; i < 26; i++) {// skip Target language ID, + data[i] = ""; + } + + data[DUMMY_IDX] = "0";//dummy + data[FOUND_PARTS_COUNTER_IDX] = "1";//parts found + + } + + /** (non-Javadoc) + * @see org.xml.sax.ContentHandler#startDocument() + */ + public void startDocument() { + initData(); + //System.out.print("Start"); + + } + + /** (non-Javadoc) + * @see org.xml.sax.ContentHandler#endDocument() + */ + public void endDocument() { + + try { + showStatistic(); + } catch (IOException e) { + + OutputHandler.log(e.getMessage()); + + } + } + + /** (non-Javadoc) + * @throws SAXException + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + public void startElement(String namespaceURI, String sName, String qName, + Attributes attrs) throws SAXException { + this.name = new String(qName); + this.attrs = new AttributesImpl(attrs); + String resType; + + String attributeName = new String(""); + String attribute = new String(""); + String tagElement = new String(""); + int i; + + if (qName.equals("bpt")||qName.equals("ept")||qName.equals("sub")||qName.equals("ex")) { + //ignore bpt, ept, ex and sub tags + // content of the tags will be stored + + storeIt=true; + return; + + } + if (qName.equals("target")) { + if ((resType = data[RESTYPE_IDX]) == null) { + + } else { + if ("res".equals(resType)) { + index = TARGET_TEXT_IDX; + + storeIt = true; + return; + } + // if("res-Help".equals(resType)){ + // index=TARGET_HELP_TEXT_IDX; + // storeIt=true; + // return; + // } + if ("res-QuickHelp".equals(resType)) { + index = TARGET_QUICKHELP_TEXT_IDX; + + storeIt = true; + return; + } + if ("res-Title".equals(resType)) { + index = TARGET_TITLE_TEXT_IDX; + + storeIt = true; + return; + } + } + + } + if (qName.equals("source")) { + if ((resType = data[RESTYPE_IDX]) == null) { + //throw new SAXException("Ressource type not found"); + } else { + if ("res".equals(resType)) { + index = SOURCE_TEXT_IDX; + + storeIt = true; + return; + } + // if("res-Help".equals(resType)){ + // index=SOURCEHELPTEXT_IDX; + // storeIt=true; + // return; + // } + if ("res-QuickHelp".equals(resType)) { + index = SOURCE_QUICK_HELPTEXT_IDX; + storeIt = true; + return; + } + if ("res-Title".equals(resType)) { + index = SOURCE_TITLETEXT_IDX; + storeIt = true; + return; + } + } + } + + if (qName.equals("file")) { + data[TIMESTAMP_IDX] = attrs.getValue("date"); + //data[17]=(attrs.getValue("original")); + try{ + data[SOURCE_LANGUAGE_ID_IDX] = (languageResolver.getISOFromRFC((String)attrs.getValue("source-language"))); + if(languageResolver.getISOFromRFC((String)attrs.getValue("target-language"))!=null){ + data[TARGET_LANGUAGE_ID_IDX] = (languageResolver.getISOFromRFC((String)attrs.getValue("target-language"))); + } + }catch(Exception e){ + OutputHandler.log(e.getMessage()); + } + return; + } + if (qName.equals("trans-unit")) { + String id = attrs.getValue("id"); + if ((DataStore.get(id)) != null) { + //TODO arraycopy might not be nessessary + System.arraycopy((String[]) DataStore.get(id), 0, data, 0, + data.length); + int help = (new Integer(data[FOUND_PARTS_COUNTER_IDX])).intValue(); //found one more part + help++; // refresh the actual found parts + data[FOUND_PARTS_COUNTER_IDX] = (new Integer(help)).toString(); // belonging to this information + + DataStore.remove(attrs.getValue("id")); // TODO this can be deleted? + } else { + + data[BLOCKNR_IDX] = (attrs.getValue("id")); // a new part + } + data[RESTYPE_IDX] = (attrs.getValue("restype")); + + return; + } + + if (qName.equals("context")) { + + String value = attrs.getValue("context-type"); + + if ("SourceHelpText".equals(value)) { + index = SOURCE_HELPTEXT_IDX; + storeIt = true; + return; + }else if ("TargetHelpText".equals(value)) { + index = TARGET_HELP_TEXT_IDX; + storeIt = true; + return; + }else if ("DBType".equals(value)) { + //index=SOURCEFILE_IDX; + //storeIt=true; + return; + }else if ("Project".equals(value)) { + index = PROJECT_IDX; + storeIt = true; + return; + }else if ("Filename".equals(value)) { + index = SOURCEFILE_IDX; + storeIt = true; + return; + }else if ("Type".equals(value)) { + index = RESTYPE_IDX; + storeIt = true; + return; + }else if ("GID".equals(value)) { + index = GID_IDX; + storeIt = true; + return; + }else if ("LID".equals(value)) { + index = LID_IDX; + storeIt = true; + return; + }else if ("HID".equals(value)) { + index = HID_IDX; + storeIt = true; + return; + }else if ("Platform".equals(value)) { + index = PLATFORM_IDX; + storeIt = true; + return; + }else if ("Width".equals(value)) { + index = WIDTH_IDX; + storeIt = true; + return; + } + + } + + } + + /** (non-Javadoc) + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + public void endElement(String namespaceURI, String sName, String qName) + throws SAXException { + //we ignore bpt and ept tags + if(!(qName.equals("bpt")||qName.equals("ept")||qName.equals("sub")||qName.equals("ex"))){ + storeIt = false; + } + if (qName.equals("trans-unit")) { + showData(); + } + + } + + /** (non-Javadoc) + * @see org.xml.sax.ContentHandler#characters(char[], int, int) + */ + public void characters(char[] ch, int start, int length) { + + // checkContent(); + String str2 = new String(ch, start, length); + + if (storeIt) { + + String str = new String(ch, start, length); + if (index == oldindex) { + data[index] += str; + } else { + data[index] = str; + } + + } + oldindex = index; + + } + + /** (non-Javadoc) + * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) + */ + public void error(SAXParseException e) throws SAXParseException { + + OutputHandler.log(e.getMessage()); + } + + /** (non-Javadoc) + * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) + */ + public void fatalError(SAXParseException e) throws SAXParseException { + + OutputHandler.log("PARSE ERROR in line " + e.getLineNumber() + ", " + + e.getMessage() ); + + } + + /** (non-Javadoc) + * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) + */ + public void warning(SAXParseException e) throws SAXParseException { + //throw e; + OutputHandler.log(e.getMessage()); + } + + /** + * Put the Data to the DataHandler + * tell the Writer to write it + * + * @throws SAXException + */ + public void showData() throws SAXException { + transUnitCounter++; + makeDot(); + if (isComplete()) { + + try { + moveData(); + if (isFirst == true) { + this.sourceLanguage = (String) this.moveData + .get("SourceLanguageID"); + this.targetLanguage = (String) this.moveData + .get("TargetLanguageID"); + OutputHandler.out(EMPTY); + OutputHandler.out("Source Language is: " + + this.sourceLanguage); + OutputHandler.out("Target Language is: " + + this.targetLanguage); + OutputHandler.out(EMPTY); + OutputHandler.out("Start"); + OutputHandler.out(EMPTY); + isFirst = false; + } + target.getDataFrom(handler); + target.writeData(); + + } catch (java.io.IOException e) { + throw new SAXException(e); + } + + } else { + DataStore.put(data[BLOCKNR_IDX], data.clone()); + initData(); + + } + initData(); + } + + + /** + * put the data in an Map in the format that + * DataHandler can handle it + */ + final public void moveData() { + + moveData.put("BlockNr", data[BLOCKNR_IDX]); + + moveData.put("Project", data[PROJECT_IDX]); + + moveData.put("SourceFile", data[SOURCEFILE_IDX]); + + moveData.put("Dummy", "0"); + + moveData.put("ResType", data[RESTYPE_IDX]); + + moveData.put("GID", data[GID_IDX]); + + moveData.put("LID", data[LID_IDX]); + + moveData.put("HID", data[HID_IDX]); + + moveData.put("Platform", data[PLATFORM_IDX]); + + if (EMPTY.equals(data[WIDTH_IDX])) + data[WIDTH_IDX] = "0"; + moveData.put("Width", data[WIDTH_IDX]); + + moveData.put("SourceLanguageID", data[SOURCE_LANGUAGE_ID_IDX]); + + moveData.put("SourceText", data[SOURCE_TEXT_IDX]); + + moveData.put("SourceHText", data[SOURCE_HELPTEXT_IDX]); + + moveData.put("SourceQText", data[SOURCE_QUICK_HELPTEXT_IDX]); + + moveData.put("SourceTitle", data[SOURCE_TITLETEXT_IDX]); + + moveData.put("TargetLanguageID", data[TARGET_LANGUAGE_ID_IDX]); + + moveData.put("TargetText", data[TARGET_TEXT_IDX]); + + moveData.put("TargetHText", data[TARGET_HELP_TEXT_IDX]); + + moveData.put("TargetQText", data[TARGET_QUICKHELP_TEXT_IDX]); + + moveData.put("TargetTitle", data[TARGET_TITLE_TEXT_IDX]); + + moveData.put("TimeStamp", data[TIMESTAMP_IDX]); + + //and give it to the data handler + this.handler.fillDataWith(moveData); + } + + /** + * complete means all depending parts have been found esp. all res types + * that belong to the same SDF Line + * + * @return true if the data is complete + * + */ + final public boolean isComplete() { + + if(!doBlockCompleteCheck){ + return true; + } + + String sParts; + if (data[FOUND_PARTS_COUNTER_IDX] == EMPTY) + data[FOUND_PARTS_COUNTER_IDX] = "1"; //this is the first part + + String sFoundParts = data[FOUND_PARTS_COUNTER_IDX]; + //create the new 'id' + sParts = data[BLOCKNR_IDX].substring(data[BLOCKNR_IDX].lastIndexOf(":") + 1); + + if (sFoundParts.equals(sParts)) { + return true; + } + return false; + } + + // TODO this belongs in OutputHandler + /** + * show the user that it is going + * on by printing dots on the screen + * + */ + private void makeDot() { + int count = 0; + if ((count = (int) this.transUnitCounter / 1000) > this.dotCount) { + this.dotCount = count; + OutputHandler.printDot(); + } + } + + /** + * show the statistic data found while parse this file + * + * @throws IOException + */ + final void showStatistic() throws IOException { + OutputHandler.out(EMPTY); + OutputHandler.out("TransUnits found: " + this.transUnitCounter); + // every data in DataStore is + // skipped 'cause its not complete + // TODO count really every transunit not only the data (might consist of + // more than one + OutputHandler.dbg("TransUnits skip : " + this.DataStore.size()); + //Converter.out(EMPTY); + } +} + diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java new file mode 100755 index 000000000000..42eef42884c1 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java @@ -0,0 +1,535 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: XLIFFWriter.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * + /* + * XLIFFWriter.java + * + * + */ + +package com.sun.star.tooling.converter; + +import java.io.*; +import java.util.*; + +import com.sun.star.tooling.DirtyTags.DirtyTagWrapper; +import com.sun.star.tooling.languageResolver.LanguageResolver; +import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; + +/** + * Write the Data to a wellformed XLIFF File + * + * @author Christian Schmidt + */ +public class XLIFFWriter extends DataWriter { + + /** + * An array holding the keys of the HashMap containing the source language string + */ + private final static String[] sourceLineNames = { "Project", "SourceFile", + "Dummy", "ResType", "GID", "LID", "HID", "Platform", "Width", + "SourceLanguageID", "SourceText", "SourceHText", "SourceQText", + "SourceTitle", "TimeStamp" }; + /** + * An array holding the keys of the HashMap containing the target language string + */ + private final static String[] targetLineNames = { "Project", "SourceFile", + "Dummy", "ResType", "GID", "LID", "HID", "Platform", "Width", + "TargetLanguageID", "TargetText", "TargetHText", "TargetQText", + "TargetTitle", "TimeStamp" }; + /** + * An array holding the keys of the HashMap containing the source and target language string + */ + private final static String[] outLineNames = { "BlockNr", "Project", + "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", + "Width", "SourceLanguageID", "SourceText", "SourceHText", + "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", + "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; + /** + * An Map holding the source and target content + */ + private final Map data = new ExtMap(outLineNames, null); + + + /** + * Indicates if this is the first Transunit to write + */ + boolean isFirst = true; + + LanguageResolver languageResolver; + + + /** + * Create a new Instance of XLIFFWriter + * + * @param bos the Buffered Output Stream to write to + * @param charset the charset to use + * @throws IOException + */ + public XLIFFWriter(BufferedOutputStream bos, String charset) + throws IOException { + super(bos, charset); + this.languageResolver =new LanguageResolver(); + + + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#getDatafrom(com.sun.star.tooling.converter.DataHandler) + */ + public void getDatafrom(DataHandler handler) throws java.io.IOException { + handler.putDataTo(this.data); + } + + /** + * check if the item is an empty String + * + * @param item the string to check + * @return true if it is not empty, false if it is empty + */ + private final boolean isUsed(String item) { + if (!"".equals(item)) + return true; + return false; + } + + /** + * Replaces all characters that mustn't be in XLIFF PCdata + * + * @param string the string to check + * @return the checked string with all characters replaced + * @throws java.io.IOException + */ + private final String xmlString( final String string) throws java.io.IOException { + if (string == null) + return string; // "" + String str = string; +// str = str.replaceAll("&", "&"); +// str = str.replaceAll("<", "<"); +// str = str.replaceAll(">", ">"); +// str = str.replaceAll("\"", """); +// str = str.replaceAll("'", "'"); + for(int i=0;i'){ + str=str.substring(0, i)+">"+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='"'){ + str=str.substring(0, i)+"""+str.substring(i+1); + continue; + } + + if(str.charAt(i)=='\''){ + str=str.substring(0, i)+"'"+str.substring(i+1); + continue; + } + } + + return str; + } + + /* (non-Javadoc) + * @see java.io.Writer#close() + */ + public void close() throws IOException { + this.writeTrailer(); + + super.close(); + } + + /* (non-Javadoc) + * @see com.sun.star.tooling.converter.DataWriter#writeData() + */ + public void writeData() throws IOException { + if (isFirst) { + + writeHeader(); + isFirst = false; + } + try{ + writeTransUnit(); + }catch(DirtyTagWrapper.TagWrapperException e){ + + } + } + + /** + * Write the XLIFFFiles header + * + * @throws IOException + */ + private void writeHeader() throws IOException { + + this.write(getHeader()); + } + + /** + * Write the XLIFFFiles Trailer + * + * @throws IOException + */ + private void writeTrailer() throws IOException { + this.write(getTrailer()); + } + + /** + * Write the next TransUnit + * + * @throws IOException + */ + private void writeTransUnit() throws IOException, DirtyTagWrapper.TagWrapperException { + try{ + StringBuffer writeBuffer = new StringBuffer(1000); + + StringBuffer allLinesEnd = new StringBuffer(200); + String sRessource = ""; + int parts = 0; + if (data == null) { + OutputHandler.out("error");// TBD Exception + } + + if (!(this.data.get("SourceText").equals("") || this.data.get( + "SourceText").equals(" "))) { + parts++; + } + // if(!(this.data.get("SourceHText").equals("")||this.data.get("SourceHText").equals(" + // "))){ + // parts++; + // } + if (!(this.data.get("SourceQText").equals("") || this.data.get( + "SourceQText").equals(" "))) { + parts++; + } + if (!(this.data.get("SourceTitle").equals("") || this.data.get( + "SourceTitle").equals(" "))) { + parts++; + } + if (!(this.data.get("SourceText").equals("") || this.data.get( + "SourceText").equals(" "))) { + sRessource = "res"; // normal TEXT source + + allLinesEnd + .append("\t\t\t\t\n"); + + if (isUsed((String) this.data.get("ResType"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data.get("ResType")) + + "\n"); + if (isUsed((String) this.data.get("Project"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data.get("Project")) + + "\n"); + if (isUsed((String) this.data.get("SourceFile"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data + .get("SourceFile")) + "\n"); + if (isUsed((String) this.data.get("SourceHText"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data + .get("SourceHText")) + "\n"); + if (isUsed((String) this.data.get("TargetHText"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data + .get("TargetHText")) + "\n"); + if (isUsed((String) this.data.get("ResType"))) + allLinesEnd.append("\t\t\t\t\t" + + xmlString((String) this.data.get("ResType")) + + "\n"); + if (isUsed((String) this.data.get("GID"))) + allLinesEnd.append("\t\t\t\t\t" + + xmlString((String) this.data.get("GID")) + + "\n"); + if (isUsed((String) this.data.get("LID"))) + allLinesEnd.append("\t\t\t\t\t" + + xmlString((String) this.data.get("LID")) + + "\n"); + if (isUsed((String) this.data.get("HID"))) + allLinesEnd.append("\t\t\t\t\t" + + xmlString((String) this.data.get("HID")) + + "\n"); + if (isUsed((String) this.data.get("Platform"))) + allLinesEnd + .append("\t\t\t\t\t" + + xmlString((String) this.data.get("Platform")) + + "\n"); + if (isUsed((String) this.data.get("Width"))) + allLinesEnd.append("\t\t\t\t\t" + + xmlString((String) this.data.get("Width")) + + "\n"); + allLinesEnd.append("\t\t\t\t\n" + + "\t\t\t\n"); + + writeBuffer.append("\t\t\t\n"); + if (isUsed((String) this.data.get("SourceText"))) + writeBuffer.append("\t\t\t\t" + + DirtyTagWrapper.wrapString((String) this.data.get("SourceText")) + + "\n"); + + if (isUsed((String) this.data.get("TargetText"))) + writeBuffer + .append("\t\t\t\t" + +DirtyTagWrapper.wrapString((String) this.data + .get("TargetText")) + "\n"); + writeBuffer.append(allLinesEnd); + Converter.countLine(); + + } + // if(!(this.data.get("SourceHText").equals("")||this.data.get("SourceHText").equals(" + // "))){ + // sRessource="res-Help"; //Source is Help + // //sLineNumber=String.valueOf(iLineNumber);// + // writeBuffer.append("\t\t\n");//always translate + // if(isUsed((String)this.data.get("SourceHText"))) + // writeBuffer.append("\t\t\t"+xmlString((String)this.data.get("SourceHText"))+"\n"); + // if(isUsed((String)this.data.get("TargetHText"))) + // writeBuffer.append("\t\t\t"+xmlString((String)this.data.get("TargetHText"))+"\n"); + // writeBuffer.append(allLinesEnd); + // Converter.countLine(); + // } + + if (!(this.data.get("SourceQText").equals("") || this.data.get( + "SourceQText").equals(" "))) { + sRessource = "res-QuickHelp"; // Source is OuickHelp + // sLineNumber=String.valueOf(iLineNumber);// + writeBuffer.append("\t\t\t\n");// always translate + if (isUsed((String) this.data.get("SourceQText"))) + writeBuffer.append("\t\t\t\t" + + DirtyTagWrapper.wrapString((String) this.data.get("SourceQText")) + + "\n"); + if (isUsed((String) this.data.get("TargetQText"))) + writeBuffer + .append("\t\t\t\t" + + DirtyTagWrapper.wrapString((String) this.data + .get("TargetQText")) + "\n"); + writeBuffer.append(allLinesEnd); + Converter.countLine(); + } + + if (!(this.data.get("SourceTitle").equals("") || this.data.get( + "SourceTitle").equals(" "))) { + sRessource = "res-Title"; // Source is Title + + writeBuffer.append("\t\t\t\n");// always translate + if (isUsed((String) this.data.get("SourceTitle"))) + writeBuffer.append("\t\t\t\t" + + DirtyTagWrapper.wrapString((String) this.data.get("SourceTitle")) + + "\n"); + if (isUsed((String) this.data.get("TargetTitle"))) + writeBuffer + .append("\t\t\t\t" + + DirtyTagWrapper.wrapString((String) this.data + .get("TargetTitle")) + "\n"); + writeBuffer.append(allLinesEnd); + Converter.countLine(); + } + this.write(writeBuffer.toString()); + }catch(Exception e){ + OutputHandler.log(e.getMessage()); + } + } + + /** + * Create the XLIFFFiles Header + * + * @return the header as string + * @throws java.io.UnsupportedEncodingException + */ + private String getHeader() throws java.io.UnsupportedEncodingException { + return new String( + (getProcessingInstructionTag() + getDTDLine() + + openVersionLine() + openFileLine() + getHeaderTag() + openBodyTag()) + .getBytes(), "UTF8"); + + } + + /** + * Create the XLIFFFiles Trailer + * + * @return the trailer as string + */ + private String getTrailer() { + return closeBodyTag() + closeFileLine() + closeVersionLine(); + } + + /** + * Create the Processing Instruction Tag used by this XLIFFFile + * @return the Processing Instruction Tag used by this XLIFFFile + */ + private String getProcessingInstructionTag() { + String sPITagStart = ""; + return sPITagStart + sPIName + sPIVersion + sPIEncoding + + /* sPIStandalone+ */sPITagEnd + '\n'; + } + + /** + * Create the line holding the DTD referenced by this XLIFFFile + * @return a string holding the DTD referenced by this XLIFFFile + */ + private String getDTDLine() { + String sDTDTagStart = "";// http://www.oasis-open.org/committees/xliff/documents/ + String sDTSTagEnd = ">"; + return sDTDTagStart + sDTDType + sDTDSource + '\n'; + } + + /** + * Create the beginning of the line holding the version of this XIFFFile + * + * @return a string with the beginning of the line holding the version of this XIFFFile + */ + private String openVersionLine() { + return "\n"; + } + /** + * Create the ending of the line holding the version of this XIFFFile + * + * @return a string with the ending of the line holding the version of this XIFFFile + */ + private String closeVersionLine() { + return ""; + } + /** + * Create the beginning of the line holding the file tag of this XIFFFile + * + * @return a string with the beginning of the file tag of this XIFFFile + */ + private String openFileLine() { + + String FileTagStart = "\t"; + } + /** + * Create a String containing the header tag + * @return the String containing the header tag + */ + private String getHeaderTag() { + return "
\n"; + } + /** + * Create the begining of the line holding the body tag of this XIFFFile + * + * @return a string with the begining of the body tag of this XIFFFile + */ + private String openBodyTag() { + return "\t\t\n"; + } + /** + * Create the ending of the line holding the body tag of this XIFFFile + * + * @return a string with the ending of the body tag of this XIFFFile + */ + private String closeBodyTag() { + return "\t\t"; + } + + /* + * (non-Javadoc) + * + * @see com.sun.star.tooling.converter.DataWriter#writeData(java.util.Map[]) + */ + protected void writeData(Map[] data) throws IOException { + // TODO Auto-generated method stub + + } + + /* + * (non-Javadoc) + * + * @see com.sun.star.tooling.converter.DataWriter#getDataFrom(com.sun.star.tooling.converter.DataHandler) + */ + protected void getDataFrom(DataHandler handler) { } + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd new file mode 100755 index 000000000000..91262ec28204 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd @@ -0,0 +1,391 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java b/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java new file mode 100755 index 000000000000..62ff008156ab --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java @@ -0,0 +1,201 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: LanguageResolver.java,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +/* + * Created on 2005 + * by Christian Schmidt + */ +package com.sun.star.tooling.languageResolver; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.ListIterator; + +/** + * Translate language codes into another format + * between ISO, RFC3066 and numeric + * + * @author Christian Schmidt 2005 + * + */ +public class LanguageResolver { + private final static int ISO =2; + private final static int LANGID =0; + private final static int LANGNAME =1; + private final static int RFC3066 =3; + + ArrayList languages=new ArrayList(); + +// public static void main(String[] args){ +// try { +// LanguageResolver lr=new LanguageResolver(); +// } catch (IOException e) { +// // +// e.printStackTrace(); +// } +// } + + /** + * Create a new Instance of LanguageResolver + * + * @throws IOException + */ + public LanguageResolver() throws IOException{ + String lang = "com/sun/star/tooling/languageResolver/lang.map"; + ClassLoader cl = this.getClass().getClassLoader(); + InputStream in = cl.getResourceAsStream(lang); + BufferedReader languageTable= new BufferedReader(new InputStreamReader(in)); + + String line; + + while((line=(languageTable.readLine()))!=null){ + languages.add(line.split(",")); + } + } + /** + * Get the numeric value of the given ISO Language Code + * + * @param isoCode the ISO Language Code to find + * @return numeric value of the given isoCode + * @throws LanguageResolvingException if the Language ISO Code is not known + */ + public String getNrFromISO(String isoCode) throws LanguageResolvingException{ + if("".equals(isoCode)) return ""; + ListIterator iter=languages.listIterator(); + String[] line=new String[5]; + while(isoCode!="" && iter.hasNext()){ + line=(String[]) iter.next(); + if(line[ISO].equals(isoCode)) return line[LANGID]; + } + throw new LanguageResolvingException("Can not find ISO Code: "+isoCode ); + + } + + /** + * Get the ISO Language Code corresponding with the given Language ID + * + * @param ID the numeric language id to find + * @return the ISO Language Code corresponding with the given Language ID + * @throws LanguageResolvingException if the Language ID is not known + */ + public String getISOfromNr(String ID) throws LanguageResolvingException{ + if("".equals(ID)) return ""; + ListIterator iter=languages.listIterator(); + String[] line=new String[5]; + while(iter.hasNext()){ + line=(String[]) iter.next(); + if(line[LANGID].equals(ID)) return line[ISO]; + } + throw new LanguageResolvingException("Can not find Language Id: "+ID ); + } + + /** + * Get the RFC3066 value of the given ISO Language Code + * + * @param isoCode the ISO Language Code to find + * @return RFC3066 value of the given isoCode + * @throws LanguageResolvingException if the Language ISO Code is not known + */ + public String getRFCFromISO(String isoCode) throws LanguageResolvingException{ + if("".equals(isoCode)) return ""; + ListIterator iter=languages.listIterator(); + String[] line=new String[5]; + while(iter.hasNext()){ + line=(String[]) iter.next(); + if(line[ISO].equals(isoCode)) return line[RFC3066]; + } + throw new LanguageResolvingException("Can not find ISO Code: "+isoCode ); + } + + /** + * Get the ISO Language Code corresponding with the given RFC3066 code + * + * @param RFC RFC3066 language id to find + * @return the ISO Language Code corresponding with the given RFC3066 code + * @throws LanguageResolvingException if the RFC3066 code is not known + */ + public String getISOFromRFC(String RFC) throws LanguageResolvingException{ + if("".equals(RFC)) return ""; + ListIterator iter=languages.listIterator(); + String[] line=new String[5]; + while(iter.hasNext()){ + line=(String[]) iter.next(); + if(line[RFC3066].equals(RFC)) return line[ISO]; + } + throw new LanguageResolvingException("Can not find Language Id: "+RFC ); + } + + + /** + * This Exception is thrown if a Language Identfier is unknown + * + * @author Christian Schmidt 2005 + * + */ + public class LanguageResolvingException extends Exception { + + /** + * + */ + public LanguageResolvingException() { + super(); + // + } + + /** + * @param arg0 + */ + public LanguageResolvingException(String arg0) { + super(arg0); + // + } + + /** + * @param arg0 + * @param arg1 + */ + public LanguageResolvingException(String arg0, Throwable arg1) { + super(arg0, arg1); + // + } + + /** + * @param arg0 + */ + public LanguageResolvingException(Throwable arg0) { + super(arg0); + // + } + + } + +} diff --git a/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map b/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map new file mode 100755 index 000000000000..a43e8f5e0218 --- /dev/null +++ b/l10ntools/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map @@ -0,0 +1,41 @@ +1,English,en-US,en-US,1033 +3,Portuguese,pt,pt-PT,2070 +30,Greek,el,el-GR,1032 +33,French,fr,fr-FR,1036 +35,Finnish,fi,fi-FI,1035 +39,Italian,it,it-IT,1040 +43,Slowak,sk,sk-SK,1051 +46,Swedish,sv,sv-SE,1053 +48,Polish,pl,pl-PL,1045 +55,Portuguese (Brasil),pt-BR,pt-BR,2070 +82,Korean,ko,ko-KR,1042 +88,Chinese (traditional),zh-TW,zh-TW,1028 +96,Arabic,ar,,1025 +97,Hebrew,he,he-IL,1037 +7,Russian,ru,ru-RU,1049 +31,Dutch,nl,nl-NL,1043 +34,Spanish,es,es-ES,1034 +36,Hungarian,hu,hu-HU,1038 +42,Czech,cs,cs-CZ,1029 +45,Danish,da,da-DK,1030 +47,Norwegian (Bokmal),nb,nb-NB,1044 +49,German,de,de-DE,1031 +81,Japanese,ja,ja-JP,1041 +86,Chinese (simple),zh-CN,zh-CN,2052 +90,Turkish,tr,tr-TR,1055 +37,Catalan,ca,, +66,Thai,th,th-TH, +91,Hindi,hi-IN,hi-IN, +77,Estonian,et,et, +50,Slovenian,sl,sl, +79,Norwegian Nynorsk,nn,nn-NN, +53,Welsh,cy,cy, +27,Afrikaans,af,af-ZA, +38,Galician,gl-ES,gl-ES, +58,Lithuanian,lt,lt-LT, +29,Tswana,tn,tn-TN, +76,Khmer ( Cambodia ),km,km, +26,Northern Sotho,ns,ns-ZA, +28,Zulu,zu,zu-ZA, +10,Basque,eu,eu-ES, +93,Kannada,kn,kn-KN, \ No newline at end of file diff --git a/l10ntools/java/l10nconv/makefile.mk b/l10ntools/java/l10nconv/makefile.mk new file mode 100755 index 000000000000..2be2eb391ced --- /dev/null +++ b/l10ntools/java/l10nconv/makefile.mk @@ -0,0 +1,39 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.3 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=../.. +PRJNAME=l10ntools +TARGET=converter + +.INCLUDE : ant.mk + +ALLTAR : ANTBUILD + diff --git a/l10ntools/java/receditor/build.xml b/l10ntools/java/receditor/build.xml new file mode 100755 index 000000000000..34f02128f034 --- /dev/null +++ b/l10ntools/java/receditor/build.xml @@ -0,0 +1,173 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/l10ntools/java/receditor/java/transex3/controller/EditorController.java b/l10ntools/java/receditor/java/transex3/controller/EditorController.java new file mode 100644 index 000000000000..38462d665304 --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/controller/EditorController.java @@ -0,0 +1,334 @@ +package transex3.controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.*; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.Runtime; +import java.util.*; + +import javax.swing.ListSelectionModel; +import javax.swing.WindowConstants; +import javax.swing.event.*; + +import transex3.model.*; + +import java.io.*; +import javax.swing.*; +//import transex3.model.*; +public class EditorController { + public final String[] RESTYPES = { ".src",".hrc",".xcu",".xrm",".xhp" }; + public final String RECFILE = ".recommand"; + // Editor View + static transex3.view.Editor aEditor = null; + // Editor Model + static Vector sdfstrings = new Vector(); + static HashMap hashedsdfstrings = new HashMap(); + int oldindex = 0; + //HashMap hashedfilenames = new HashMap(); + // Search for source Strings + public String fetchSourceStrings( String rootdir ){ + + //String outputfile = "h:\\workspace\\recommandEditor\\null2"; + File tempfile = null; + + try { + tempfile = File.createTempFile( "receditor" , "tmp" ); + } catch (IOException e1) { + // TODO Auto-generated catch block + System.err.println("Can not create temp file\n"); + e1.printStackTrace(); + } + + String outputfile = tempfile.getAbsolutePath(); + try + { + //System.out.println("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile+" -d "+rootdir); + System.out.println("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile ); + java.lang.Process aProc = Runtime.getRuntime().exec("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile); + + //java.lang.Process aProc = Runtime.getRuntime().exec("localize_sl -QQ -e -l en-US -f "+outputfile+" -d "+rootdir); + BufferedReader aBR = new BufferedReader( new InputStreamReader( aProc.getInputStream() ) ); + String line = aBR.readLine(); + while( line != null && line.length() > 0 ){ + //System.out.print( line ); + line = aBR.readLine(); + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return outputfile; + } + // Search for recommand files + public void findRecommandFiles( File rootdir , Vector list ){ + System.out.print("."); + System.out.flush(); + File[] aFileArray = rootdir.listFiles(); + if( aFileArray != null ){ + for( int cnt = 0; aFileArray.length > cnt ; cnt++ ){ + if( aFileArray[ cnt ].isDirectory() && !aFileArray[ cnt ].getAbsolutePath().endsWith(".lnk") ) + findRecommandFiles( aFileArray[ cnt ] , list); + else if( aFileArray[ cnt ].isFile() && isRecommandFile( aFileArray[ cnt ] ) ) + list.add( aFileArray[ cnt ]); + } + } + } + private boolean isResourceType( File aFile ){ + String filename = aFile.getName(); + boolean isResType = false; + for(int cnt = 0; cnt < RESTYPES.length ; cnt++){ + if( filename.endsWith( RESTYPES[ cnt ] ) ) + isResType = true; + } + return isResType; + } + private boolean isRecommandFile( File aFile ){ + return aFile.getName().endsWith( RECFILE ); + } + public void clearAllRows( JTable aTable ){ + for ( int n = 0; n < aTable.getRowCount() ; n++ ){ + aTable.setValueAt( null , n , 0 ); + aTable.setValueAt( null , n , 1 ); + aTable.setValueAt( null , n , 2 ); + aTable.setValueAt( null , n , 3 ); + aTable.setValueAt( null , n , 4 ); + } + } + // Add all data to view + void updateData(){ + JTable recTable =transex3.controller.EditorController.aEditor.getRectable(); + + SdfString aSdfString = (SdfString) sdfstrings.get( oldindex ); + Vector newStrings = new Vector(); + for ( int n = 1; n < recTable.getRowCount() ; n++ ){ + String lang = (String) recTable.getValueAt(n , 0 ); + String text = (String) recTable.getValueAt(n , 1 ); + String htext = (String) recTable.getValueAt(n , 2 ); + String qhtext = (String) recTable.getValueAt(n , 3 ); + String ttext = (String) recTable.getValueAt(n , 4 ); + if( lang != null && text != null ){ + //System.out.println("Data "+ lang + " " + text ); + SdfEntity aSdfEntity = new SdfEntity(); + aSdfEntity.setLangid( lang ); + aSdfEntity.setText( text ); + aSdfEntity.setHelptext( htext ); + aSdfEntity.setQuickhelptext( qhtext ); + aSdfEntity.setTitle( ttext ); + newStrings.add( aSdfEntity ); + aSdfString.setLanguageStrings( newStrings ); + } + } + } + + public void initView(){ + Object[][] sourceStringData = new Object[ sdfstrings.size() ][ 4 ]; + Object[][] firstData = new Object[100][5]; + // Set the files + Iterator aIter = sdfstrings.iterator(); + int counter = 0; + while( aIter.hasNext() ){ + SdfString aSdfString = (SdfString) aIter.next(); + sourceStringData[ counter ][ 0 ] = aSdfString.getSourceString().getProject()+"\\"+aSdfString.getSourceString().getSource_file(); + sourceStringData[ counter ][ 1 ] = aSdfString.getSourceString().getGid(); + sourceStringData[ counter ][ 2 ] = aSdfString.getSourceString().getLid(); + sourceStringData[ counter ][ 3 ] = aSdfString.getSourceString().getText(); + if( counter == 0 ){ + firstData[ 0 ][ 0 ] = "en-US"; + firstData[ 0 ][ 1 ] = aSdfString.getSourceString().getText(); + firstData[ 0 ][ 2 ] = aSdfString.getSourceString().getHelptext(); + firstData[ 0 ][ 3 ] = aSdfString.getSourceString().getQuickhelptext(); + firstData[ 0 ][ 4 ] = aSdfString.getSourceString().getTitle(); + aSdfString = (SdfString) sdfstrings.get( 0 ); + Vector values = aSdfString.getLanguageStrings(); + for( int n = 0; n < values.size() ; n++ ) + { + SdfEntity aEntity = (SdfEntity) values.get( n ); + firstData[ n+1 ][ 0 ] = aEntity.getLangid(); + firstData[ n+1 ][ 1 ] = aEntity.getText(); + firstData[ n+1 ][ 2 ] = aEntity.getHelptext(); + firstData[ n+1 ][ 3 ] = aEntity.getQuickhelptext(); + firstData[ n+1 ][ 4 ] = aEntity.getTitle(); + } + } + counter++; + } + // Set the source srtings + + + //aEditor = new transex3.view.Editor( sourceStringData , filedata.toArray() ); + aEditor = new transex3.view.Editor( sourceStringData , firstData ); + + aEditor.setBounds(100,100,800,900); + aEditor.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE ); + aEditor.setVisible(true); + aEditor.repaint(); + aEditor.addWindowListener( new WindowAdapter(){ + public void windowClosed(WindowEvent e ){ + System.exit( 0 ); + } + }); + + aEditor.getMiExit().addActionListener( new ActionListener(){ + public void actionPerformed( ActionEvent e ){ + System.exit( 0 ); + } + }); + + aEditor.getMiSave().addActionListener( new ActionListener(){ + public void actionPerformed( ActionEvent e ){ + Iterator aIter = sdfstrings.iterator(); + String lastFile=""; + while( aIter.hasNext() ) + { + SdfString aSdfString = (SdfString )aIter.next(); + if( aSdfString.getFileId().compareTo( lastFile ) != 0 ){ + //aSdfString.removeFile(); + } + aSdfString.writeString(); + lastFile = aSdfString.getFileId(); + } + } + }); + + //aEditor.getRectable().putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); + aEditor.getRectable().addFocusListener( new FocusListener(){ + public void focusLost(FocusEvent e){ + //super.focusLost( e ); + //System.out.println("focus lost"); + JTable aTable = aEditor.getRectable(); + if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) + aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); + updateData(); + } + public void focusGained( FocusEvent e){ + //super.focusGained( e ); + //System.out.println("focus gained"); + } + }); + //setDefaultEditor(Object.class, new transex3.view.FocusCellEditor(new JTextField())); + + aEditor.getRectable().getModel().addTableModelListener( new TableModelListener() { + public void tableChanged( TableModelEvent e ){ + //System.out.println( e ); + }}); + + + aEditor.getRectable().getSelectionModel().addListSelectionListener( new ListSelectionListener(){ + public void valueChanged( ListSelectionEvent e ){ + JTable aTable = aEditor.getRectable(); + //if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) + //aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); + + updateData(); + } + }); + + aEditor.getTable().setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); + aEditor.getTable().getSelectionModel().addListSelectionListener( new ListSelectionListener(){ + public void valueChanged( ListSelectionEvent e ){ + //System.out.println("Selected = " +e.getFirstIndex()+"\n"); + JTable table =transex3.controller.EditorController.aEditor.getTable(); + JTable recTable =transex3.controller.EditorController.aEditor.getRectable(); + SdfString aSdfString; + JTable aTable = aEditor.getRectable(); + if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) + aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); + + updateData(); + clearAllRows( recTable ); + + aSdfString = (SdfString) sdfstrings.get( table.getSelectedRow() ); + recTable.setValueAt( "en-US" , 0, 0 ); + recTable.setValueAt( aSdfString.getSourceString().getText() , 0, 1 ); + recTable.setValueAt( aSdfString.getSourceString().getHelptext() , 0, 2 ); + recTable.setValueAt( aSdfString.getSourceString().getQuickhelptext() , 0, 3 ); + recTable.setValueAt( aSdfString.getSourceString().getTitle() , 0, 4 ); + Vector values = aSdfString.getLanguageStrings(); + for( int n = 0; n < values.size() ; n++ ) + { + SdfEntity aEntity = (SdfEntity) values.get( n ); + recTable.setValueAt( aEntity.getLangid() , n+1 , 0 ); + recTable.setValueAt( aEntity.getText() , n+1 , 1 ); + recTable.setValueAt( aEntity.getHelptext() , n+1 , 2 ); + recTable.setValueAt( aEntity.getQuickhelptext() , n+1 , 3 ); + recTable.setValueAt( aEntity.getTitle() , n+1 , 4 ); + } + oldindex = table.getSelectedRow(); + } + }); + //System.out.println("initView successfully"); + } + public void initInitialStrings(){ + String rootdir = java.lang.System.getProperty("SOLARSRC"); + String sourcestringsfile = null; + Vector recList = new Vector(); + sourcestringsfile = fetchSourceStrings( rootdir ); + //findRecommandFiles( new File( rootdir ) , recList ); + readStrings( sourcestringsfile , recList ); + File sfile = new File ( sourcestringsfile ); + sfile.delete(); + initView(); + aEditor.repaint(); + } + // Connect recommand strings with source strings + public void readStrings( String sourcefiles , Vector recfiles ) { + BufferedReader aBR = null; + try { + //System.out.println("DBG: sourcefiles = " +sourcefiles); + aBR = new BufferedReader( new FileReader( sourcefiles ) ); + String current = aBR.readLine(); + SdfString aSdfString = null; + SdfEntity aSdfEntity = null; + while( current != null ){ + aSdfEntity = new SdfEntity(); + aSdfEntity.setProperties( current ); + aSdfString = new SdfString(); + aSdfString.addSourceString( aSdfEntity ); + hashedsdfstrings.put( aSdfString.getId() , aSdfString ); + //System.out.println("Put ID '"+aSdfString.getId()+"'"); + sdfstrings.add( aSdfString ); + current = aBR.readLine(); + + } + Iterator aIter=recfiles.iterator(); + File aFile; + BufferedReader aBR2 = null; + //System.out.println("Connecting strings"); + while( aIter.hasNext() ){ + aFile = (File) aIter.next(); + aBR2 = new BufferedReader( new FileReader( aFile ) ) ; + String current2 = aBR2.readLine(); + + while ( current2 != null ){ + SdfEntity aEntity = new SdfEntity(); + aEntity.setProperties( current2 ); + + if( hashedsdfstrings.containsKey( aEntity.getId() ) ) + { + aSdfString = (SdfString) hashedsdfstrings.get( aEntity.getId() ); + aSdfString.addLanguageString( aEntity ); + } + else + { + System.out.println("DBG: Can't find source string '"+aEntity.getId()+"'" ); + } + current2 = aBR2.readLine(); + } + } + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch ( IOException e){ + e.printStackTrace(); + } + + } +} diff --git a/l10ntools/java/receditor/java/transex3/controller/Main.java b/l10ntools/java/receditor/java/transex3/controller/Main.java new file mode 100644 index 000000000000..e8dd06ce9f85 --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/controller/Main.java @@ -0,0 +1,10 @@ +package transex3.controller; + +public class Main { + + public static void main( String args[] ){ + EditorController aEditor = new EditorController(); + aEditor.initInitialStrings(); + } +} + diff --git a/l10ntools/java/receditor/java/transex3/model/ResourceFile.java b/l10ntools/java/receditor/java/transex3/model/ResourceFile.java new file mode 100644 index 000000000000..51fabb3a4b7a --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/model/ResourceFile.java @@ -0,0 +1,77 @@ +package transex3.model; + +import java.util.*; + +public class ResourceFile { + Vector sdfStrings = new Vector(); + HashMap sdfHashMap = new HashMap(); + String filepathid = null; + String modulename = null; + String filename = null; + + + public String getModuleName(){ + return modulename; + } + public String getFilePath(){ + return filepathid; + } + public String getFileName(){ + return filename; + } +/* public List readSoureStrings( java.io.File aSdfFile ){ + List sdfList=null; + return sdfList; + };*/ + public void addString( SdfString aSdfstring ){ + sdfStrings.add( aSdfstring ); + sdfHashMap.put( aSdfstring.getFileId() , aSdfstring ); + if( filepathid == null ) + filepathid = aSdfstring.getFilePath(); + if( modulename == null ) + modulename = aSdfstring.getModuleName(); + if( filename == null ) + filename = aSdfstring.getFileName(); + } + + + public void ParseString( String aSourceString ){ + //sourceString = new SdfEntity(); + SdfEntity aSdfEntity = new SdfEntity(); + aSdfEntity.setProperties( aSourceString ); + SdfString sdfstring = null; + if( sdfHashMap.containsKey( aSdfEntity.getFileId() ) ){ + sdfstring = (SdfString) sdfHashMap.get( aSdfEntity.getFileId() ); + } + else + { + sdfstring = new SdfString(); + addString( sdfstring ); + } + sdfstring.addLanguageString( aSdfEntity ); + + + } + /*public void ParseSdfFile( java.util.Vector aSdfList ){ + ListIterator aLI = aSdfList.listIterator(); + String current; + String[] splitted; + SdfEntity aSdfEntity; + SdfString aSdfString = new SdfString(); + while( aLI.hasNext() ){ + aSdfEntity = new SdfEntity(); + aSdfEntity.setProperties( (String) aLI.next() ); + SdfString aString; + + if( sdfHashMap.containsKey( aSdfEntity.getFileId() ) ) + aString = (SdfString) sdfHashMap.get( aSdfEntity.getFileId() ); + else + { + aString = new SdfString(); + addString( aString ); + } + aString.addLanguageString( aSdfEntity ); + } + + }*/ +} diff --git a/l10ntools/java/receditor/java/transex3/model/SdfEntity.java b/l10ntools/java/receditor/java/transex3/model/SdfEntity.java new file mode 100644 index 000000000000..4b293421fd28 --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/model/SdfEntity.java @@ -0,0 +1,211 @@ +package transex3.model; + +public class SdfEntity { + private String project; + private String source_file; + private String dummy1; + private String resource_type; + private String gid; + private String lid; + private String helpid; + private String platform; + private String dummy2; + private String langid; + private String text; + private String helptext; + private String quickhelptext; + private String title; + private String date; + + public static int PROJECT_POS = 0; + public static int SOURCE_FILE_POS = 1; + public static int DUMMY1_POS = 2; + public static int RESOURCE_TYPE_POS = 3; + public static int GID_POS = 4; + public static int LID_POS = 5; + public static int HELPID_POS = 6; + public static int PLATFORM_POS = 7; + public static int DUMMY2_POS = 8; + public static int LANGID_POS = 9; + public static int TEXT_POS = 10; + public static int HELPTEXT_POS = 11; + public static int QUICKHELPTEXT_POS = 12; + public static int TITLE_POS = 13; + public static int DATE_POS = 14; + + public SdfEntity(){} + public SdfEntity(String project, String source_file, String dummy1, String resource_type, String gid, String lid, String helpid, String platform, String dummy2, String langid, String text, String helptext, String quickhelptext, String title , String date) { + super(); + this.project = project; + this.source_file = source_file; + this.dummy1 = dummy1; + this.resource_type = resource_type; + this.gid = gid; + this.lid = lid; + this.helpid = helpid; + this.platform = platform; + this.dummy2 = dummy2; + this.langid = langid; + this.text = text; + this.helptext = helptext; + this.quickhelptext = quickhelptext; + this.title = title; + this.date = date; + } + + public void setProperties( String line ){ + + String[] splitted = line.split("\t"); + + setProject( splitted[ SdfEntity.PROJECT_POS ] ); + setSource_file( splitted[ SdfEntity.SOURCE_FILE_POS ] ); + setDummy1( splitted[ SdfEntity.DUMMY1_POS ] ); + setResource_type( splitted[ SdfEntity.RESOURCE_TYPE_POS ] ); + setGid( splitted[ SdfEntity.GID_POS ] ); + setLid( splitted[ SdfEntity.LID_POS ] ); + setHelpid( splitted[ SdfEntity.HELPID_POS ] ); + setPlatform( splitted[ SdfEntity.PLATFORM_POS ] ); + setDummy2( splitted[ SdfEntity.DUMMY2_POS ] ); + setLangid( splitted[ SdfEntity.LANGID_POS ] ); + setText( splitted[ SdfEntity.TEXT_POS ] ); + setHelptext( splitted[ SdfEntity.HELPTEXT_POS ] ); + setQuickhelptext( splitted[ SdfEntity.QUICKHELPTEXT_POS ] ); + setTitle( splitted[ SdfEntity.TITLE_POS ] ); + setDate( splitted[ SdfEntity.DATE_POS ] ); + } + + public String getFileId(){ + return project+"\\"+source_file; + } + public String getResourcePath(){ + return source_file.substring(0 , source_file.lastIndexOf( "\\" )-1 ); + } + public String toString(){ + return project+"\t"+source_file+"\t"+dummy1+"\t"+resource_type+"\t"+gid+"\t" + +lid+"\t"+helpid+"\t"+platform+"\t"+dummy2+"\t"+langid+"\t" + +text+"\t"+helptext+"\t"+quickhelptext+"\t"+title+"\t"+date; + } + public String getId(){ + return project+gid+lid+source_file+resource_type+platform+helpid; + } + + public String getDummy1() { + return dummy1; + } + + public void setDummy1(String dummy1) { + this.dummy1 = dummy1; + } + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public String getDummy2() { + return dummy2; + } + + public void setDummy2(String dummy2) { + this.dummy2 = dummy2; + } + + public String getGid() { + return gid; + } + + public void setGid(String gid) { + this.gid = gid; + } + + public String getHelpid() { + return helpid; + } + + public void setHelpid(String helpid) { + this.helpid = helpid; + } + + public String getHelptext() { + return helptext; + } + + public void setHelptext(String helptext) { + this.helptext = helptext; + } + + public String getLangid() { + return langid; + } + + public void setLangid(String langid) { + this.langid = langid; + } + + public String getLid() { + return lid; + } + + public void setLid(String lid) { + this.lid = lid; + } + + public String getProject() { + return project; + } + + public void setProject(String project) { + this.project = project; + } + + public String getQuickhelptext() { + return quickhelptext; + } + + public void setQuickhelptext(String quickhelptext) { + this.quickhelptext = quickhelptext; + } + + public String getResource_type() { + return resource_type; + } + + public void setResource_type(String resource_type) { + this.resource_type = resource_type; + } + + public String getSource_file() { + return source_file; + } + + public void setSource_file(String source_file) { + this.source_file = source_file; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + public String getDate() { + return date; + } + public void setDate(String date) { + this.date = date; + } + + +} diff --git a/l10ntools/java/receditor/java/transex3/model/SdfString.java b/l10ntools/java/receditor/java/transex3/model/SdfString.java new file mode 100644 index 000000000000..7419aeb5578b --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/model/SdfString.java @@ -0,0 +1,192 @@ +package transex3.model; +import java.util.*; +import java.io.*; +public class SdfString { + private SdfEntity sourceString = null; + //private java.util.HashMap languageStrings = new HashMap(); + private Vector languageList = new Vector(); + private String id = null; + private String fileid = null; + private String filename = null; + private String modulename = null; + private String filepath = null; + + /*public HashMap getLanguageStrings() { + return languageStrings; + }*/ + public Vector getLanguageStrings() { + return languageList; + } + + public void setLanguageStrings(Vector languageStrings) { + this.languageList = languageStrings; + } + + public void addSourceString( SdfEntity aSdfEntity ) + { + if( id == null ) + id = aSdfEntity.getId(); + if ( fileid == null ) + fileid = aSdfEntity.getFileId(); + if( modulename == null ) + modulename = aSdfEntity.getProject(); + if( filename == null ) + filename = aSdfEntity.getSource_file(); + if( filepath == null ) + filepath = aSdfEntity.getResourcePath(); + setSourceString( aSdfEntity ); + } + public void addLanguageString( SdfEntity aSdfEntity ){ + if( !aSdfEntity.getLangid().equals( "en-US" ) ) + { + if( id == null ) + id = aSdfEntity.getId(); + if ( fileid == null ) + fileid = aSdfEntity.getFileId(); + if( modulename == null ) + modulename = aSdfEntity.getProject(); + if( filename == null ) + filename = aSdfEntity.getSource_file(); + if( filepath == null ) + filepath = aSdfEntity.getResourcePath(); + + //if( aSdfEntity.getLangid().equals( "en-US" ) ) + //{ + // setSourceString( aSdfEntity ); + //} + //else + //{ + //languageStrings.put( aSdfEntity.getLangid() , aSdfEntity ); + languageList.add( aSdfEntity ); + //} + id = aSdfEntity.getId(); + } + } + + public SdfEntity getSourceString() { + return sourceString; + } + + public void setSourceString(SdfEntity sourceString) { + this.sourceString = sourceString; + id = sourceString.getId(); + } + public String getFilePath(){ + return filepath; + } + public String getId(){ + //return id; + return sourceString.getId(); + } + public String getFileId(){ + return fileid; + } + + public String getFileName() { + return filename; + } + + public void setFileName(String filename) { + this.filename = filename; + } + + public String getModuleName() { + return modulename; + } + + public void setModuleName(String modulename) { + this.modulename = modulename; + } + /* + public String getRealFileName(){ + //String srcroot = "U:\\cws01\\l10ncleanup\\SRC680\\src.m213";//java.lang.System.getProperty( "SOLARSRC"); + //String isWindows = "4nt";//java.lang.System.getProperty( "USE_SHELL"); + String srcroot = java.lang.System.getProperty( "SOLARSRC" ); + String isWindows = java.lang.System.getProperty( "USE_SHELL" ); + + //System.out.println("srcroot="+srcroot+" isWindows="+isWindows ); + //if( true ) return; + //String relpath = sourceString.getFileId().substring( sourceString.getFileId().lastIndexOf("\\") + // , sourceString.getFileId().length() ); + String filename; + if( isWindows != null && isWindows.compareTo( "4nt") == 0 ) + { + filename = srcroot + "\\" + //sourceString.getProject() + "\\" + + sourceString.getFileId() +".recommand"; + } + else + { + String filepart = sourceString.getFileId(); + filepart = filepart.replaceAll( "\\\\" , "/" ); + filename = srcroot + "/" + //sourceString.getProject() + "//" + + filepart +".recommand"; + } + return filename; + }*/ + public String getRealFileName(){ + String filepart = sourceString.getFileId(); + filepart = filepart.replaceAll( "\\\\" , "_" ); + String filename = "/so/ws/merge/In/" + java.lang.System.getProperty( "WORK_STAMP" ) + "/" + filepart + ".sdf"; + return filename; + } + public void removeFile(){ + String filename = getRealFileName(); + File aFile = new File( filename ); + if( aFile.exists() ){ + if( ! aFile.delete() ) + { + System.out.println("Can't delete File "+filename+"\nWrong access rights?\n"); + } + } + } + public void writeString(){ + String filename = getRealFileName(); + try { + if( languageList.size() > 0 ) + { + System.out.print("\nWrite to "+filename ); + BufferedWriter aBW = new BufferedWriter( new FileWriter( filename , true) ); + aBW.write( sourceString + "\n" ); + Iterator aIter = languageList.iterator(); + while( aIter.hasNext() ){ + SdfEntity aEntity = (SdfEntity)aIter.next(); + aBW.write( sourceString.getProject()+"\t" ); + aBW.write( sourceString.getSource_file()+"\t" ); + aBW.write( sourceString.getDummy1()+"\t" ); + aBW.write( sourceString.getResource_type()+"\t" ); + aBW.write( sourceString.getGid()+"\t" ); + aBW.write( sourceString.getLid()+"\t" ); + aBW.write( sourceString.getHelpid()+"\t" ); + aBW.write( sourceString.getPlatform()+"\t" ); + aBW.write( sourceString.getDummy2()+"\t" ); + if( aEntity.getLangid() == null ) + aBW.write( "\t" ); + else + aBW.write( aEntity.getLangid()+"\t" ); + if( aEntity.getText() == null ) + aBW.write( "\t" ); + else + aBW.write( aEntity.getText()+"\t" ); + if( aEntity.getHelptext() == null ) + aBW.write( "\t" ); + else + aBW.write( aEntity.getHelptext()+"\t" ); + if( aEntity.getQuickhelptext() == null ) + aBW.write( "\t" ); + else + aBW.write( aEntity.getQuickhelptext()+"\t" ); + if( aEntity.getTitle() == null ) + aBW.write( "\t" ); + else + aBW.write( aEntity.getTitle()+"\t" ); + aBW.write( "2002-02-02 02:02:02\n" ); + } + aBW.close(); + } + } catch (IOException e) { + // TODO Auto-generated catch block + //e.printStackTrace(); + System.out.println("\nERROR: Can't write to file '"+filename+"'\nPlease contact RE/Tooling!"); + } + } +} diff --git a/l10ntools/java/receditor/java/transex3/view/Editor.java b/l10ntools/java/receditor/java/transex3/view/Editor.java new file mode 100644 index 000000000000..f46a82a11a2b --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/view/Editor.java @@ -0,0 +1,97 @@ +package transex3.view; +import javax.swing.*; +import java.awt.*; + +public class Editor extends JFrame{ + Object[] columnnames = { "File" , "GID" , "LID" , "String" }; + Object[] stringcolnames = { "Language", "Text", "Helptext" , "Quickhelptext","Title"}; + //Object[][] data = new Object[4][1];//{ { "a " }, { "v " }, { "v " } , { "a " } }; + JTable table = null; + JTable rectable = null; + JComboBox cBox = null; + JMenuBar menubar = null; + JMenu filemenu = null; + JMenuItem miNew = null; + JMenuItem miSave = null; + JMenuItem miExit = null; + //JButton button = null; + + public Editor( Object[][] tabledata , Object[][] firstdata ){ + table = new JTable( tabledata , columnnames ); + rectable = new SdfTable( firstdata , stringcolnames ); + menubar = new JMenuBar(); + filemenu = new JMenu("File"); + //miNew = new JMenuItem("New"); + miSave = new JMenuItem("Save"); + miExit = new JMenuItem("Exit"); + //button = new JButton("Edit"); + //filemenu.add( miNew ); + filemenu.add( miSave ); + filemenu.add( miExit ); + menubar.add( filemenu ); + + Container contentPane = getContentPane(); + //contentPane.add( new ControlPanel() , BorderLayout.NORTH ); + contentPane.add( menubar , BorderLayout.NORTH ); + //JPanel aPanel = new JPanel( new FlowLayout( FlowLayout.CENTER) ); + JPanel aPanel = new JPanel( new GridLayout( 2,1 ) ); + aPanel.add( new JScrollPane( table ) ); + aPanel.add( new JScrollPane( rectable ) ); + contentPane.add( aPanel , BorderLayout.CENTER ); + //contentPane.add( button , BorderLayout.SOUTH ); + //contentPane.add( new JScrollPane( table ), BorderLayout.CENTER ); + //contentPane.add( new JScrollPane( table ), BorderLayout.SOUTH ); + //contentPane.add( new JScrollPane( rectable ), BorderLayout.SOUTH ); + //contentPane.add( new JScrollPane( rectable ), BorderLayout.SOUTH ); + this.repaint(); + + } + + public JTable getRectable() { + return rectable; + } + + public void setRectable(JTable rectable) { + this.rectable = rectable; + } + + public JTable getTable() { + return table; + } + + public void setTable(JTable table) { + this.table = table; + } + + /*public JButton getButton() { + return button; + } + + public void setButton(JButton button) { + this.button = button; + }*/ + + public JMenuItem getMiExit() { + return miExit; + } + + public void setMiExit(JMenuItem miExit) { + this.miExit = miExit; + } + + public JMenuItem getMiSave() { + return miSave; + } + + public void setMiSave(JMenuItem miSave) { + this.miSave = miSave; + } + + /*public void setTableData(){ + + }*/ + +} + +//class ControlPanel extends JPanel{} + diff --git a/l10ntools/java/receditor/java/transex3/view/SdfTable.java b/l10ntools/java/receditor/java/transex3/view/SdfTable.java new file mode 100644 index 000000000000..f0cc7bd84a34 --- /dev/null +++ b/l10ntools/java/receditor/java/transex3/view/SdfTable.java @@ -0,0 +1,24 @@ +package transex3.view; + +import javax.swing.JTable; + +class SdfTable extends JTable{ + //private String tableId; + public SdfTable( Object[][] obj1 , Object[] obj2){ + super(obj1,obj2); + } + //@Override + public boolean isCellEditable(int row, int col) { + if( row == 0 && col == 0 || row == 0 && col == 1 || row == 0 && col == 2 || row == 0 && col == 3 || row == 0 && col == 4 ) + return false; + else + return true; + } + /*public String getTableId() { + return tableId; + } + public void setTableId(String tableId) { + this.tableId = tableId; + }*/ + +} \ No newline at end of file diff --git a/l10ntools/java/receditor/makefile.mk b/l10ntools/java/receditor/makefile.mk new file mode 100755 index 000000000000..dd3f84daccce --- /dev/null +++ b/l10ntools/java/receditor/makefile.mk @@ -0,0 +1,39 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.3 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=../.. +PRJNAME=l10ntools +TARGET=receditor + +.INCLUDE : ant.mk + +ALLTAR : ANTBUILD + diff --git a/l10ntools/java/receditor/receditor.MF b/l10ntools/java/receditor/receditor.MF new file mode 100755 index 000000000000..dced97882df9 --- /dev/null +++ b/l10ntools/java/receditor/receditor.MF @@ -0,0 +1 @@ +Main-Class: transex3.controller.Main diff --git a/l10ntools/layout/README b/l10ntools/layout/README new file mode 100644 index 000000000000..1838e2a94ba0 --- /dev/null +++ b/l10ntools/layout/README @@ -0,0 +1,27 @@ +Tralay - Extract and translate strings in Layout xml files. + +Translatable strings in layout xml files are attributes that have name +which starts with an underscore, eg + + _title="Set Zoom" + _label="Whole Page" + +Here is how it works + + * Extract: generate out.sdf + ../unxlngx6.pro/bin/tralay -l en-US zoom.xml > out.sdf + + * Translate: do: + cat out.sdf > trans.sdf + sed 's/en-US\t/de\tde:/' out.sdf >> trans.sdf + + * Merge: translate + ../unxlngx6.pro/bin/tralay -m trans.sdf -l de zoom.xml > zoom-DE.xml + +Running + + dmake test + +does something similar. + + \ No newline at end of file diff --git a/l10ntools/layout/layoutparse.cxx b/l10ntools/layout/layoutparse.cxx new file mode 100644 index 000000000000..0f43c9a3053f --- /dev/null +++ b/l10ntools/layout/layoutparse.cxx @@ -0,0 +1,139 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: layoutparse.cxx,v $ + * + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "layoutparse.hxx" + +#define STRING( str ) String( str, RTL_TEXTENCODING_UTF8 ) +#define BSTRING( str ) ByteString( str, RTL_TEXTENCODING_UTF8 ) + +LayoutXMLFile::LayoutXMLFile( bool mergeMode ) + : XMLFile() + , mMergeMode( mergeMode ) +{ +} + +void +LayoutXMLFile::SearchL10NElements( XMLParentNode* pCur, int ) +{ + if ( !pCur ) + pCur = this; + + /* Recurse int children, SearchL10NElements does not do that for us. */ + if ( XMLChildNodeList* lst = pCur->GetChildList() ) + for ( ULONG i = 0; i < lst->Count(); i++ ) + if ( lst->GetObject( i )->GetNodeType() == XML_NODE_TYPE_ELEMENT ) + HandleElement( ( XMLElement* )lst->GetObject( i ) ); + else if ( lst->GetObject( i )->GetNodeType() == XML_NODE_TYPE_COMMENT ) + lst->Remove( i-- ); +} + +std::vector +interestingAttributes( XMLAttributeList* lst ) +{ + std::vector interesting; + if ( lst ) + for ( ULONG i = 0; i < lst->Count(); i++ ) + if ( lst->GetObject( i )->Equals( STRING( "id" ) ) ) + interesting.insert( interesting.begin(), lst->GetObject( i ) ); + else if ( ! BSTRING( *lst->GetObject( i ) ).CompareTo( "_", 1 ) ) + interesting.push_back( lst->GetObject( i ) ); + return interesting; +} + +void +LayoutXMLFile::HandleElement( XMLElement* element ) +{ + std::vector interesting = interestingAttributes( element->GetAttributeList() ); + + if ( interesting.size() ) + { + std::vector::iterator i = interesting.begin(); + + ByteString id = BSTRING( (*i++)->GetValue() ); + + if ( mMergeMode ) + InsertL10NElement( id, element ); + else + for ( ; i != interesting.end(); ++i ) + { + ByteString attributeId = id; + ByteString value = BSTRING( ( *i )->GetValue() ); + XMLElement *e = new XMLElement( *element ); + e->RemoveAndDeleteAllChilds(); + /* Copy translatable text to CONTENT. */ + //new XMLData( STRING( ( *i )->GetValue() ), e, true ); + new XMLData( STRING( value ), e, true ); + attributeId += BSTRING ( **i ); + InsertL10NElement( attributeId, e ); + } + } + + SearchL10NElements( (XMLParentNode*) element ); +} + +void LayoutXMLFile::InsertL10NElement( ByteString const& id, XMLElement* element ) +{ + ByteString const language = "en-US"; + LangHashMap* languageMap = 0; + XMLHashMap::iterator pos = XMLStrings->find( id ); + if ( pos != XMLStrings->end() ) + { + languageMap = pos->second; + fprintf( stderr, "error:%s:duplicate translation found, id=%s\n", + id.GetBuffer(), BSTRING( sFileName ).GetBuffer() ); + exit( 1 ); + } + else + { + languageMap = new LangHashMap(); + XMLStrings->insert( XMLHashMap::value_type( id , languageMap ) ); + order.push_back( id ); + } + (*languageMap)[ language ] = element; +} + +BOOL LayoutXMLFile::Write( ByteString &aFilename ) +{ + + if ( aFilename.Len() ) + { + ofstream aFStream( aFilename.GetBuffer() , ios::out | ios::trunc ); + if ( !aFStream ) + fprintf( stderr, "ERROR: cannot open file:%s\n", aFilename.GetBuffer() ); + else + { + XMLFile::Write( aFStream ); + aFStream.close(); + return true; + } + } + return false; +} diff --git a/l10ntools/layout/layoutparse.hxx b/l10ntools/layout/layoutparse.hxx new file mode 100644 index 000000000000..b9cd8f6c18b2 --- /dev/null +++ b/l10ntools/layout/layoutparse.hxx @@ -0,0 +1,55 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: layoutparse.hxx,v $ + * + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef LAYOUTPARSE_HXX +#define LAYOUTPARSE_HXX + +#include "xmlparse.hxx" + +class LayoutXMLFile : public XMLFile +{ + bool mMergeMode; + +public: + LayoutXMLFile( bool mergeMode ); + + void SearchL10NElements( XMLParentNode *pCur, int pos = 0 ); + BOOL Write( ByteString &aFilename ); + void HandleElement( XMLElement* element ); + void InsertL10NElement( ByteString const& id, XMLElement* element ); + + using XMLFile::InsertL10NElement; + using XMLFile::Write; +}; + +std::vector interestingAttributes( XMLAttributeList* lst ); + +#endif /* LAYOUTPARSE_HXX */ diff --git a/l10ntools/layout/loc.sdf b/l10ntools/layout/loc.sdf new file mode 100644 index 000000000000..023357adc420 --- /dev/null +++ b/l10ntools/layout/loc.sdf @@ -0,0 +1,24 @@ +transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 en-US Zoom factor 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 en-US Whole Page 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_PAGE_WIDTH 0 en-US Page Width 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_OPTIMAL 0 en-US Optimal 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_200 0 en-US 200 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_150 0 en-US 15~0 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_100 0 en-US 100 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_75 0 en-US 75 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_50 0 en-US 50 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_USER 0 en-US Variable 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 de deZoom factor 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 de deWhole Page 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_PAGE_WIDTH 0 de dePage Width 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_OPTIMAL 0 de deOptimal 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_200 0 de de200 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_150 0 de de15~0 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_100 0 de de100 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_75 0 de de75 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_50 0 de de50 % 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_USER 0 de deVariable 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 en-US Zoom factor 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 en-US Whole Page 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 de de3:Zoom factor 20080204 13:51:01 +transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 de de3:Whole Page 20080204 13:51:01 diff --git a/l10ntools/layout/makefile.mk b/l10ntools/layout/makefile.mk new file mode 100644 index 000000000000..63dbeae6d9e9 --- /dev/null +++ b/l10ntools/layout/makefile.mk @@ -0,0 +1,81 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.3 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=.. + +INCPRE=$(MISC) + +PRJNAME=l10ntools +TARGET=tralay +#TARGETTYPE=GUI +TARGETTYPE=CUI +LIBTARGET=no + +# --- Settings ----------------------------------------------------- + +ENABLE_EXCEPTIONS=TRUE + +.INCLUDE : settings.mk + +.IF "$(SYSTEM_EXPAT)" == "YES" +CFLAGS+=-DSYSTEM_EXPAT +.ENDIF + +# --- Files -------------------------------------------------------- + +APP1TARGET=$(TARGET) + +OBJFILES =\ + $(OBJ)/export2.obj\ + $(OBJ)/helpmerge.obj\ + $(OBJ)/layoutparse.obj\ + $(OBJ)/merge.obj\ + $(OBJ)/tralay.obj\ + $(OBJ)/xmlparse.obj + +APP1OBJS = $(OBJFILES) + +APP1STDLIBS =\ + $(TOOLSLIB)\ + $(EXPATASCII3RDLIB)\ + $(VOSLIB)\ + $(CPPULIB) \ + $(SALLIB) + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk + +test .PHONY: + ../$(INPATH)/bin/tralay -l en-US -o out.sdf zoom.xml + cat out.sdf > trans.sdf + sed 's/en-US\t/de\tde:/' out.sdf >> trans.sdf + ../$(INPATH)/bin/tralay -m trans.sdf -l de -o zoom-DE.xml zoom.xml diff --git a/l10ntools/layout/tralay.cxx b/l10ntools/layout/tralay.cxx new file mode 100644 index 000000000000..13a7fdb0c5d9 --- /dev/null +++ b/l10ntools/layout/tralay.cxx @@ -0,0 +1,403 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: tralay.cxx,v $ + * + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include +#include + +#include + +#include "export.hxx" +#include "layoutparse.hxx" +#include "helpmerge.hxx" +#include "xmlparse.hxx" + +// Convert a rtl::OUString to a byte string. +#define OUSTRING_CSTR( str ) \ + rtl::OUStringToOString( str, RTL_TEXTENCODING_UTF8 ).getStr() + +#define STRING( str ) String( str, RTL_TEXTENCODING_UTF8 ) +#define BSTRING( str ) ByteString( str, RTL_TEXTENCODING_UTF8 ) + +using ::rtl::OUString; + +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + + +class TranslateLayout : public Application +{ + ByteString mGid1; + ByteString mLanguage; + ByteString mLocalize; + ByteString mOutput; + ByteString mProject; + ByteString mRoot; + bool mMergeMode; + std::vector< ByteString > mLanguages; + std::list< ByteString > mFiles; + +public: + TranslateLayout(); + virtual ~TranslateLayout(); + ByteString GetCommandLineParam( int i ); + ByteString GetOptionArgument( int const i ); + void ExceptionalMain(); + void Main(); + void Merge(); + void MergeLanguage( ByteString const& language ); + void ParseCommandLine(); + void CreateSDF(); + + using Application::GetCommandLineParam; +}; + +static void usage() +{ + fprintf( stderr, "Usage: tralay [OPTION]... XML-FILE\n" ); + fprintf( stderr, "\nOptions:\n" ); + fprintf( stderr, " -h,--help show this help\n" ); + fprintf( stderr, " -l,--language=LANG process this language\n" ); + fprintf( stderr, " -m,--merge=DATABASE.SDF translation database\n" ); + fprintf( stderr, "\nExamples:\n" ); + fprintf( stderr, " tralay -l en-US -o localize.sdf zoom.xml # Extract\n" ); + fprintf( stderr, " tralay -m localize.sdf -l de -l nl -o out zoom.xml # Merge/translate\n" ); + exit( 2 ); +} + +static ByteString ConvertSystemPath( const ByteString& rPath ) +{ + if( rPath.CompareTo( ".", 1 ) == 0 ) + { + OUString sPath( rPath.GetBuffer(), rPath.Len(), RTL_TEXTENCODING_UTF8 ); + + ::rtl::OUString curDirPth, sURL; + osl_getProcessWorkingDir( &curDirPth.pData ); + + ::osl::FileBase::getAbsoluteFileURL( curDirPth, sPath, sURL ); + ::osl::FileBase::getSystemPathFromFileURL( sURL, sPath ); + + return ByteString( rtl::OUStringToOString( sPath, RTL_TEXTENCODING_UTF8 ) ); + } + else + { + return rPath; + } +} + +ByteString TranslateLayout::GetCommandLineParam( int i ) +{ + return ByteString( OUSTRING_CSTR( Application::GetCommandLineParam( sal::static_int_cast< USHORT >( i ) ) ) ); +} + +ByteString TranslateLayout::GetOptionArgument( int const i ) +{ + if ( i >= GetCommandLineParamCount() ) + usage(); + ByteString arg = GetCommandLineParam( i ); + if ( !arg.CompareTo( "-", 1 ) ) + { + fprintf( stderr, "Option needs an argument: %s, found: %s\n", + GetCommandLineParam( i - 1 ).GetBuffer(), + arg.GetBuffer() ); + usage(); + } + return arg; + } + +void TranslateLayout::ParseCommandLine() +{ + for ( int i = 0; i < GetCommandLineParamCount(); i++ ) + { + ByteString aParam = GetCommandLineParam( i ); + if ( aParam.Equals( "-h" ) || aParam.Equals( "--help" ) ) + usage(); + else if ( aParam.Equals( "-l" ) || aParam.Equals( "--language" ) ) + mLanguages.push_back ( GetOptionArgument( ++i ) ); + else if ( aParam.Equals( "-m" ) || aParam.Equals( "--merge" ) ) + { + mMergeMode = true; + mLocalize = GetOptionArgument( ++i ); + } + else if ( aParam.Equals( "-o" ) || aParam.Equals( "--output" ) ) + mOutput = ConvertSystemPath( GetOptionArgument( ++i ) ); + else if ( !aParam.CompareTo( "-", 1 ) ) + { + fprintf( stderr, "error: No such option: %s\n", aParam.GetBuffer() ); + usage(); + } + else + mFiles.push_back( ConvertSystemPath( aParam ) ); + } + if ( !mFiles.size() ) + { + fprintf( stderr, "error: No XML-FILE found\n" ); + usage(); + } +} + +static XMLAttribute* +findAttribute( XMLAttributeList* lst, String const& name ) +{ + for ( ULONG i = 0; i < lst->Count(); i++ ) + if ( lst->GetObject( i )->Equals( name ) ) + return lst->GetObject( i ); + return 0; +} + +static XMLAttribute* +translateAttribute( XMLAttributeList* lst, + String const& name, String const& translation ) +{ + if ( XMLAttribute* a = findAttribute( lst, name ) ) + return lst->Replace ( new XMLAttribute( name.Copy( 1 ), translation ), a ); + return 0; +} + +static void +translateElement( XMLElement* element, ByteString const& lang, + ResData* resData, MergeDataFile& mergeData ) +{ + XMLAttributeList* attributes = element->GetAttributeList(); + std::vector interesting( interestingAttributes( attributes ) ); + + + if( !interesting.empty() ) + { + std::vector::iterator i( interesting.begin() ); + ByteString id = BSTRING( (*i++)->GetValue() ); + for ( ; i != interesting.end(); ++i ) + { + ByteString attributeId = id; + attributeId += BSTRING ( **i ); + resData->sGId = attributeId; + resData->sId = element->GetOldref(); + + if ( PFormEntrys* entry = mergeData.GetPFormEntrys( resData ) ) + { + ByteString translation; + entry->GetText( translation, STRING_TYP_TEXT, lang, true ); + // ByteString original = removeContent( element ); + if ( !translation.Len() ) +#if 0 + translation = original; +#else + translation = BSTRING( ( *i )->GetValue() ); +#endif + delete translateAttribute( attributes, **i , STRING( translation ) ); + } + } + } +} + +static bool is_dir( ByteString const& name ) +{ + DirectoryItem aItem; + OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 ); + FileBase::getFileURLFromSystemPath( sFileURL, sFileURL ); + if( DirectoryItem::get( sFileURL, aItem ) == FileBase::E_None ) + { + FileStatus aStatus(FileStatusMask_Type); + if( aItem.getFileStatus( aStatus ) == FileBase::E_None ) + { + if( aStatus.getFileType() == FileStatus::Directory ) + return true; + } + } + return false; +} + +static void make_directory( ByteString const& name ) +{ + OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 ); + FileBase::getFileURLFromSystemPath( sFileURL, sFileURL ); + Directory::create( sFileURL ); +} + +static void insertMarker( XMLParentNode *p, ByteString const& file ) +{ + if ( XMLChildNodeList* lst = p->GetChildList() ) + if ( lst->Count() ) + { + ULONG i = 1; + // Skip newline, if possible. + if ( lst->Count() > 1 + && lst->GetObject( 2 )->GetNodeType() == XML_NODE_TYPE_DEFAULT ) + i++; + OUString marker = OUString::createFromAscii( "\n NOTE: This file has been generated automagically by transex3/layout/tralay,\n from source template: " ) + + STRING( file ) + + OUString::createFromAscii( ".\n Do not edit, changes will be lost.\n" ); + lst->Insert( new XMLComment( marker, 0 ), i ); + } +} + +void TranslateLayout::MergeLanguage( ByteString const& language ) +{ + ByteString xmlFile = mFiles.front(); + + MergeDataFile mergeData( mLocalize, xmlFile, + FALSE, RTL_TEXTENCODING_MS_1252 ); + + DirEntry aFile( xmlFile ); + SimpleXMLParser aParser; + LayoutXMLFile* layoutXml = new LayoutXMLFile( mMergeMode ); + if ( !aParser.Execute( aFile.GetFull() , STRING( xmlFile ), layoutXml ) ) + { + fprintf(stderr, "error: parsing: %s\n", xmlFile.GetBuffer() ); + return; + } + + layoutXml->Extract(); + insertMarker( layoutXml, xmlFile ); + + ResData resData( "", "", "" ); + resData.sResTyp = mProject; /* mGid1 ?? */ + resData.sFilename = xmlFile; + + XMLHashMap* xmlStrings = layoutXml->GetStrings(); + for ( XMLHashMap::iterator i = xmlStrings->begin(); i != xmlStrings->end(); + ++i ) + { + if ( LangHashMap* languageMap = i->second ) + if ( XMLElement* element = ( *languageMap )[ "en-US" ] ) + translateElement( element, language, &resData, mergeData ); + } + +#ifndef WNT + ByteString outFile = "/dev/stdout"; +#else + ByteString outFile = "\\\\.\\CON"; +#endif + if ( mOutput.Len() ) + { + outFile = mOutput; + if ( is_dir( outFile ) ) + { + ByteString outDir = mOutput; + outDir.Append( "/" ).Append( language ); + if ( !is_dir( outDir ) ) + make_directory( outDir ); + outFile = outDir; + outFile.Append( "/" ).Append( xmlFile ); + } + } + layoutXml->Write( outFile ); + delete layoutXml; +} + +void TranslateLayout::Merge() +{ + if ( mLanguages.size() ) + for ( std::vector::iterator i = mLanguages.begin(); + i != mLanguages.end(); ++i) + MergeLanguage( *i ); + else + MergeLanguage( mLanguage ); +} + +void TranslateLayout::CreateSDF() +{ + ByteString xmlFile = mFiles.front(); +#ifndef WNT + ByteString sdf = "/dev/stdout"; +#else + ByteString sdf = "\\\\.\\CON"; +#endif + if ( mOutput.Len() ) + sdf = mOutput; + Export::SetLanguages( mLanguages ); + HelpParser::CreateSDF( sdf, mProject, mRoot, xmlFile, + new LayoutXMLFile( mMergeMode ), mGid1 ); +} + +void TranslateLayout::ExceptionalMain() +{ + ParseCommandLine(); + if ( mLanguages.size() ) + mLanguage = mLanguages.front(); + if ( mMergeMode ) + Merge(); + else + CreateSDF(); +} + +void TranslateLayout::Main() +{ + try + { + ExceptionalMain(); + } + catch ( xml::sax::SAXException& rExc ) + { + OString aStr( OUStringToOString( rExc.Message, + RTL_TEXTENCODING_ASCII_US ) ); + uno::Exception exc; + if (rExc.WrappedException >>= exc) + { + aStr += OString( " >>> " ); + aStr += OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US ); + } + fprintf( stderr, "error: parsing: '%s'\n", aStr.getStr() ); + OSL_ENSURE( 0, aStr.getStr() ); + } + catch ( uno::Exception& rExc ) + { + OString aStr( OUStringToOString( rExc.Message, + RTL_TEXTENCODING_ASCII_US ) ); + fprintf( stderr, "error: UNO: '%s'\n", aStr.getStr() ); + OSL_ENSURE( 0, aStr.getStr() ); + } +} + +TranslateLayout::TranslateLayout() + : Application() + , mGid1( "layout" ) + , mLanguage( "en-US" ) + , mLocalize( "localize.sdf" ) + , mOutput() + , mProject( "layout" ) + , mRoot() + , mMergeMode( false ) + , mLanguages() + , mFiles() +{ +} + +TranslateLayout::~TranslateLayout() +{ +} + +SAL_IMPLEMENT_MAIN() +{ + TranslateLayout t; + t.Main(); + return 0; +} diff --git a/l10ntools/layout/zoom.xml b/l10ntools/layout/zoom.xml new file mode 100644 index 000000000000..0fb3d27343ff --- /dev/null +++ b/l10ntools/layout/zoom.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/l10ntools/prj/build.lst b/l10ntools/prj/build.lst new file mode 100644 index 000000000000..ff961c096cbd --- /dev/null +++ b/l10ntools/prj/build.lst @@ -0,0 +1,10 @@ +tr l10ntools : tools LIBXSLT:libxslt BERKELEYDB:berkeleydb LUCENE:lucene NULL +tr l10ntools usr1 - all tr_mkout NULL +tr l10ntools\inc nmake - all tr_inc NULL +tr l10ntools\source nmake - all tr_src tr_inc NULL +tr l10ntools\layout nmake - all rt_layout tr_src tr_inc NULL +#tr l10ntools\java\l10nconv nmake - all tr_conv NULL +#tr l10ntools\java\receditor nmake - all tr_rece NULL +tr l10ntools\source\help nmake - all tr_bla_help NULL +tr l10ntools\source\filter\utils nmake - all tr_bla_utils NULL +tr l10ntools\source\filter\merge nmake - all tr_bla_merge tr_bla_utils NULL diff --git a/l10ntools/prj/d.lst b/l10ntools/prj/d.lst new file mode 100644 index 000000000000..f75c16b43764 --- /dev/null +++ b/l10ntools/prj/d.lst @@ -0,0 +1,61 @@ +mkdir: %_DEST%\inc%_EXT%\l10ntools +mkdir: %_DEST%\bin%_EXT% +mkdir: %_DEST%\bin%_EXT%\help +mkdir: %_DEST%\bin%_EXT%\help\com +mkdir: %_DEST%\bin%_EXT%\help\com\sun +mkdir: %_DEST%\bin%_EXT%\help\com\sun\star +mkdir: %_DEST%\bin%_EXT%\help\com\sun\star\help + +..\%__SRC%\bin\cfgex.exe %_DEST%\bin%_EXT%\cfgex.exe +..\%__SRC%\bin\cfgex %_DEST%\bin%_EXT%\cfgex +..\%__SRC%\bin\transex3.exe %_DEST%\bin%_EXT%\transex3.exe +..\%__SRC%\bin\transex3 %_DEST%\bin%_EXT%\transex3 +..\%__SRC%\bin\lngex.exe %_DEST%\bin%_EXT%\lngex.exe +..\%__SRC%\bin\lngex %_DEST%\bin%_EXT%\lngex +..\%__SRC%\bin\localize_sl.exe %_DEST%\bin%_EXT%\localize_sl.exe +..\%__SRC%\bin\localize_sl %_DEST%\bin%_EXT%\localize_sl +..\%__SRC%\bin\xrmex.exe %_DEST%\bin%_EXT%\xrmex.exe +..\%__SRC%\bin\xrmex %_DEST%\bin%_EXT%\xrmex +..\%__SRC%\bin\gsicheck.exe %_DEST%\bin%_EXT%\gsicheck.exe +..\%__SRC%\bin\gsicheck %_DEST%\bin%_EXT%\gsicheck +..\%__SRC%\bin\helpex.exe %_DEST%\bin%_EXT%\helpex.exe +..\%__SRC%\bin\helpex %_DEST%\bin%_EXT%\helpex +..\%__SRC%\bin\ulfex.exe %_DEST%\bin%_EXT%\ulfex.exe +..\%__SRC%\bin\ulfex %_DEST%\bin%_EXT%\ulfex +..\%__SRC%\bin\txtconv.exe %_DEST%\bin%_EXT%\txtconv.exe +..\%__SRC%\bin\txtconv %_DEST%\bin%_EXT%\txtconv +..\%__SRC%\bin\tralay.exe %_DEST%\bin%_EXT%\tralay.exe +..\%__SRC%\bin\tralay %_DEST%\bin%_EXT%\tralay +..\%__SRC%\bin\ulfconv %_DEST%\bin%_EXT%\ulfconv +..\%__SRC%\class\FCFGMerge.jar %_DEST%\bin%_EXT%\FCFGMerge.jar +..\%__SRC%\class\HelpIndexerTool.jar %_DEST%\bin%_EXT%\HelpIndexerTool.jar +..\%__SRC%\bin\HelpLinker %_DEST%\bin%_EXT%\HelpLinker +..\%__SRC%\bin\HelpCompiler %_DEST%\bin%_EXT%\HelpCompiler +..\%__SRC%\bin\HelpCompiler.exe %_DEST%\bin%_EXT%\HelpCompiler.exe +..\%__SRC%\bin\HelpLinker.exe %_DEST%\bin%_EXT%\HelpLinker.exe +..\%__SRC%\bin\HelpLinker* %_DEST%\bin%_EXT% + +..\%__SRC%\class\converter\converter.jar %_DEST%\bin%_EXT%\converter.jar +..\%__SRC%\doc\converter_javadoc.zip %_DEST%\bin%_EXT%\converter_javadoc.zip + +..\%__SRC%\class\receditor\receditor.jar %_DEST%\bin%_EXT%\receditor.jar + +..\scripts\localize.pl %_DEST%\bin%_EXT%\localize.pl +..\scripts\localize_old.pl %_DEST%\bin%_EXT%\localize_old.pl +..\scripts\localize %_DEST%\bin%_EXT%\localize +..\scripts\fast_merge.pl %_DEST%\bin%_EXT%\fast_merge.pl +..\scripts\keyidGen.pl %_DEST%\bin%_EXT%\keyidGen.pl + +..\inc\export.hxx %_DEST%\inc%_EXT%\l10ntools\export.hxx +..\inc\l10ntools\directory.hxx %_DEST%\inc%_EXT%\l10ntools\directory.hxx +..\inc\l10ntools\file.hxx %_DEST%\inc%_EXT%\l10ntools\file.hxx +..\inc\l10ntools\vosapp.hxx %_DEST%\inc%_EXT%\l10ntools\vosapp.hxx + +..\inc\utf8conv.hxx %_DEST%\inc%_EXT%\l10ntools\utf8conv.hxx +..\%__SRC%\lib\transex.lib %_DEST%\lib%_EXT%\transex.lib +..\%__SRC%\lib\libtransex.a %_DEST%\lib%_EXT%\libtransex.a + +..\source\help\compilehelp.hxx %_DEST%\inc%_EXT%\l10ntools\compilehelp.hxx +#..\source\help\helplinkerdllapi.h %_DEST%\inc%_EXT%\l10ntools\helplinkerdllapi.h +..\%__SRC%\lib\* %_DEST%\lib%_EXT%\* +..\%__SRC%\class\com\sun\star\help\* %_DEST%\bin%_EXT%\help\com\sun\star\help\* diff --git a/l10ntools/scripts/fast_merge.pl b/l10ntools/scripts/fast_merge.pl new file mode 100644 index 000000000000..7321a9a42911 --- /dev/null +++ b/l10ntools/scripts/fast_merge.pl @@ -0,0 +1,348 @@ +: +eval 'exec perl -wS $0 ${1+"$@"}' + if 0; +#************************************************************************* +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: fast_merge.pl,v $ +# +# $Revision: 1.1.2.2 $ +# +# last change: $Author: ihi $ $Date: 2007/07/20 10:37:53 $ +# +# The Contents of this file are made available subject to +# the terms of GNU Lesser General Public License Version 2.1. +# +# +# GNU Lesser General Public License Version 2.1 +# ============================================= +# Copyright 2005 by Sun Microsystems, Inc. +# 901 San Antonio Road, Palo Alto, CA 94303, USA +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License version 2.1, as published by the Free Software Foundation. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307 USA +# +#************************************************************************* + +use strict; +use Class::Struct; +use Getopt::Long; +use File::Temp; +use File::Path; + +my @files; +my @file_names; +my $module_name = ''; +my @current; +my @buffer; +my $last_file; +my $last_path; +my $last_localize_file; +my $first_run = "1"; +my $sdf_filename; +my $merge_dir; +my $WIN; +my $state = "none"; + +if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { $WIN = 'TRUE'; } +else { $WIN = ''; } + +$SIG{INT} = 'inthandler'; +$SIG{QUIT} = 'quithandler'; + +struct ( sdf_obj => +{ + module => '$', + file => '$', + dir => '$', + FILEHANDLE => '$', + line => '$', + endoffile => '$' +} +); + +parse_options(); +my $lock_file = $merge_dir."/lock.mk"; +$lock_file =~ s/\//\\/g , if ( $WIN ) ; +acquire_lock(); +read_sdf_file_names(); +init(); +my $reference; +my $path ; +my $localize_file; +while( hasLines() ) +{ + @current = (); + foreach ( @files ) + { + push @current , $_; + } + + $reference = getNextIdentifier( ); + + @current = (); + foreach ( @files ) + { + if( $_->module eq $reference->module && $_->dir eq $reference->dir ) + { + push @current , $_ ; + } + } + write_lines(); +} +if( $#current+1 ne 0 ) +{ + ( $path , $localize_file ) = make_paths(); + add_to_buffer(); + write_buffer( $path , $localize_file ); +} +release_lock(); +exit( 0 ); + +########################################################################################## +sub acquire_lock +{ + if( -e $lock_file ){ + $state = "blocked"; + print "WARNING: Lock file '$lock_file' 'found, waiting ....\n"; + my $cnt = 0; + sleep 10 , while( -e $lock_file && $cnt++ < 180 ); + exit( 0 ); + }else + { + $state = "locked"; + print "Writing lock file '$lock_file'\n"; + open FILE, ">$lock_file" or die "Can't create lock file '$lock_file'"; + print FILE "L10N_LOCK=YES" ; + close ( FILE ); + } +} +sub release_lock +{ + print "Deleting lock file '$lock_file'\n"; + unlink $lock_file, if( -e $lock_file ); + $state = "none"; +} +sub inthandler +{ + release_lock() , if( $state eq "locked" ); + exit( -1 ); +} +sub quithandler +{ + release_lock() , if( $state eq "locked" ); + exit( 0 ); +} + +sub init +{ + foreach my $file ( @file_names ) + { + my $obj = new sdf_obj; + open my $FILEHANDLE , "<$file" or die "Can't open file '$file'"; + $obj->FILEHANDLE ( $FILEHANDLE ) ; + getNextSdfObj( $obj ); + push @files, $obj ; + print "Open file '$file'\n"; + } +} + +# get the next module/file +sub getNextIdentifier +{ + my @sorted = sort { + return $a->module.$a->dir cmp $b->module.$b->dir; + } @current ; + return shift @sorted; +} + +# update the obj with the next line +sub getNextSdfObj +{ + my $obj = shift; + my $line = readline ( $obj->FILEHANDLE ); + if ( $line eq undef ) + { + $obj->endoffile( "true" ); + } + else + { + $line =~ /^(([^\t]*)\t([^\t]*)[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t*)/o ; + if( defined $1 && defined $2 && defined $3 ) + { + $obj->line ( $1 ); + $obj->module( $2 ); + $obj->file ( $3 ); + $obj->dir ( getDir( $3 ) ); + } + else + { + $obj->line ( "" ); + $obj->module( "" ); + $obj->file ( "" ); + $obj->dir ( "" ); + } + } + return $obj; +} +sub getNextSdfObjModule +{ + my $obj = shift; + while( !$obj->endoffile ) + { + my $line = readline ( $obj->FILEHANDLE ); + if ( $line eq undef ) + { + $obj->endoffile( "true" ); + } + else + { + $line =~ /^(([^\t]*)\t([^\t]*).*)/o ; + if( defined $1 && defined $2 && defined $3 ) + { + $obj->line ( $1 ); + $obj->module( $2 ); + $obj->file ( $3 ); + $obj->dir ( getDir( $3 ) ); + } + else + { + $obj->line ( "" ); + $obj->module( "" ); + $obj->file ( "" ); + $obj->dir ( "" ); + } + return $obj , if( $obj->module eq $module_name ) + } + } + #return $obj; +} +sub getDir +{ + my $path = shift ; + $path =~ s/\//\\/g; + my @tmp_path = split /\\/ , $path; + pop @tmp_path; + $path = join '\\' , @tmp_path; + return $path; +} + +sub hasLines +{ + my $hasLines = ""; + my @tmpfiles; + foreach ( @files ) + { + push @tmpfiles , $_, if( !$_->endoffile ); + } + @files = @tmpfiles; + return $#files+1; +} + +sub make_paths +{ + my $localizeFile = $merge_dir."\\".$current[ 0 ]->module."\\".$current[ 0 ]->file; + my $path = getDir( $localizeFile ); + if ( !$WIN ) { $path =~ s/\\/\//g; } + + $localizeFile = $path."\\localize.sdf"; + if ( !$WIN ) { $localizeFile =~ s/\\/\//g; } + + return ( $path , $localizeFile ); +} +sub write_lines +{ + if( $first_run ){ + add_to_buffer(); + my( $path , $localize_file ) = make_paths(); + $last_path = $path; + $last_localize_file = $localize_file; + mkpath $path; + write_buffer( $path , $localize_file ); + $first_run = ''; + } + else + { + return , if ( $#current+1 eq 0 ); + my( $path , $localize_file ) = make_paths(); + if( $path eq $last_path ) + { + add_to_buffer(); + } + else + { + mkpath $path; + write_buffer( $last_path , $last_localize_file ); + add_to_buffer(); + $last_path = $path; + $last_localize_file = $localize_file; + } + } +} +sub add_to_buffer +{ + my $plainline; + my $afile; + my $amodule; + foreach my $elem ( @current ) + { + do { + $amodule=$elem->module; + $afile=$elem->file; + $plainline=$elem->line; + push @buffer, $plainline; + getNextSdfObj( $elem ); + } while ( !$elem->endoffile && $amodule eq $elem->module && $afile eq $elem->file ); + } +} +sub write_buffer +{ + my $path = shift; + my $localize_file = shift; + my $cnt = $#buffer+1; + print "Write to $path $cnt lines\n"; + open FILE , ">>$localize_file" or die "Can't open file '$localize_file'\n"; + foreach ( @buffer ) + { + print FILE $_."\n"; + } + @buffer = (); +} +sub parse_options +{ + my $success = GetOptions( 'sdf_files=s' => \$sdf_filename , 'merge_dir=s' => \$merge_dir ); #, 'module=s' => \$module_name ); + if( ! ( $sdf_filename && $merge_dir && $success ) ) + { + usage(); + exit( -1 ); + } +} + +sub usage +{ + print "Usage: fast_merge -sdf_files -merge_dir \n" ; +} + +sub read_sdf_file_names +{ + open FILE , "<$sdf_filename" or die "Can't open file '$sdf_filename'\n"; + while ( ) + { + push @file_names , split " " , $_ ; + } + close ( FILE ); +} + + diff --git a/l10ntools/scripts/keyidGen.pl b/l10ntools/scripts/keyidGen.pl new file mode 100644 index 000000000000..acb5137e3f7c --- /dev/null +++ b/l10ntools/scripts/keyidGen.pl @@ -0,0 +1,189 @@ +: +eval 'exec perl -S $0 ${1+"$@"}' + if 0; +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: keyidGen.pl,v $ +# +# $Revision: 1.3 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* +# +# add keyids to sdf file +# + +use Compress::Zlib(); + +print "\nkeyidGen version 1.0 \n\n"; + +my ( $infile,$outfile,$dbimport ); +get_options(); + +print_help() if ( !defined $infile || $help ); +exit 1 if ( !defined $infile ); +if ( ! defined $outfile ) +{ + $outfile = $infile; + $outfile =~ s/\.sdf$//i; + $outfile .= "_KeyID.sdf"; +} + +$collisions = 0; +%hashcodes = (); +$count = 0; +print "writing to $outfile\n"; +open INFILE,"<$infile" || die "could not open $infile $! $^E\n"; +open OUTFILE,">$outfile" || die "could not open $outfile $! $^E\n"; + +while ( ) +{ + $line = $_; + chomp $line; + $hash = 0; + if ( $line =~ /^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)$/ ) + { + $string="$1 $2 $4 $5 $6 $7 $8"; + $hashp = makeID( $string ); + + if ( defined ($hashcodes{ $hashp } ) ) + { + $collisions ++ unless $hashcodes{ $hashp } eq $string; + } + $hashcodes{ $hashp } = $string; + $count++; + if ( $dbimport ) + { + my ( $pre, $post, $old ); + $pre = "$1\t$2\t"; + $post = "\t$4\t$5\t$6\t$7\t$8\t$9\t$10\t$11\t$12\t$13\t$14\t$15\n"; + $old = $3; + $old =~ s/;{0,1}keyid:......;{0,1}//; + $old =~ s/^0$//; + if ( $old ne "" ) { $old .= ";"; } + print OUTFILE "$pre${old}keyid:$hashp$post"; + } + else + { + print OUTFILE "$1\t$2\t$3\t$4\t$5\t$6\t$7\t$8\t$9\t$10\t".makekidstr($hashp,$11)."\t".makekidstr($hashp,$12)."\t$13\t".makekidstr($hashp,$14)."\t$15\n"; + } + } +} +print "$count entries\n"; +print "$collisions collisions\n"; + +close INFILE; +close OUTFILE; + +sub makeID +{ + my ( $String ) = shift; + my ( $hash ); + # hardcoded to prevent windows installer to choke on bad directoryname :-(( + if ( $String eq "scp2 source\\ooo\\directory_ooo.ulf LngText STR_DIR_KAPITEL " ) + { + return "keyid1"; + } + + $hash = Compress::Zlib::crc32( $String, undef ); + return makenumber( $hash ); +} + +sub makenumber +{ + $h = shift; + # 1 2 3 4 + # 1234567890123456789012345678901234567890 + $symbols="0123456789abcdefghijklmnopqrstuvwxyz+-<=>"; + $order = length($symbols); + $result = ""; + while ( length( $result ) < 6 ) + { + $result .= substr( $symbols, ($h % $order), 1 ); + $h = int( $h / $order ); + } + die "makenumber failed because number is too big (this cannot be so this is a strange error)" if $h > 0; + + return reverse $result; +} + + +sub makekidstr +{ + $kid = shift; + $str = shift; + + if ( $str ne "" ) + { + # special handling for strings starting with font descriptions like {&Tahoma8} (win system integration) + if ( $str =~ s/^(\{\&[^\}]+\})// ) + { + return "$1$kid‖$str"; + } + else + { + return "$kid‖$str"; + } + } + else + { + return ""; + } +# return "default"; +} + +sub print_help +{ + print "\n\n"; + print "keyidGen 0.5 for sdf files\n"; + print "--------------------------\n"; + print "Usage:\n"; + print "keyidGen [] [-dbimport]\n"; + print " add keyids to the entries and write them to a file with\n"; + print " _KeyID added to the name\n"; + print " -dbimport Add KeyID to a new column instead of to the strings.\n"; + print " This is needed to import the IDs into tha database.\n"; + print "\n\n"; +} + + +sub get_options { + my ($arg,$has_infile); + + while ($arg = shift @ARGV) { + $arg =~ /^-dbimport$/ and $dbimport = 1 and next; + $arg =~ /^-help$/ and $help = 1 and next; #show help + + if ( !$has_infile ) + { + $infile = $arg; + $has_infile = 1; + } + else + { + $outfile = $arg; + } + } +} diff --git a/l10ntools/scripts/localize.pl b/l10ntools/scripts/localize.pl new file mode 100755 index 000000000000..0f6a19effc38 --- /dev/null +++ b/l10ntools/scripts/localize.pl @@ -0,0 +1,1201 @@ +: +eval 'exec perl -wS $0 ${1+"$@"}' + if 0; + + +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: localize.pl,v $ +# +# $Revision: 1.18.6.2 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +use strict; +use Getopt::Long; +use IO::Handle; +use File::Find; +use File::Temp; +use File::Path; +use File::Copy; +use File::Glob qw(:glob csh_glob); +use Cwd; + +my $CVS_BINARY = "/usr/bin/cvs"; +# ver 1.1 +# +#### module lookup +#use lib ("$ENV{SOLARENV}/bin/modules", "$ENV{COMMON_ENV_TOOLS}/modules"); + +#### module lookup +# OOo conform +my @lib_dirs; +BEGIN { + if ( !defined($ENV{SOLARENV}) ) { + die "No environment found (environment variable SOLARENV is undefined)"; + } + push(@lib_dirs, "$ENV{SOLARENV}/bin/modules"); + push(@lib_dirs, "$ENV{COMMON_ENV_TOOLS}/modules") if defined($ENV{COMMON_ENV_TOOLS}); +} +use lib (@lib_dirs); + +#### globals #### +my $sdffile = ''; +my $no_sort = ''; +my $create_dirs = ''; +my $multi_localize_files = ''; +my $module_to_merge = ''; +my $sort_sdf_before = ''; +my $outputfile = ''; +my $no_gsicheck = ''; +my $mode = ''; +my $bVerbose = "0"; +my $srcpath = ''; +my $WIN; +my $languages; +#my %sl_modules; # Contains all modules where en-US and de is source language +my $use_default_date = '0'; +my $force_ooo_module = '0'; +my %is_ooo_module; +my %is_so_module; +my $DELIMITER; + + # ( leftpart ) ( rightpart ) + # prj file dummy type gid lid helpid pform width lang text helptext qhelptext title timestamp +my $sdf_regex = "((([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*))\t([^\t]*)\t(([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t)([^\t]*))"; +my $file_types = "(src|hrc|xcs|xcu|lng|ulf|xrm|xhp|xcd|xgf|xxl|xrb)"; +# Always use this date to prevent cvs conflicts +my $default_date = "2002-02-02 02:02:02"; +my @sdfparticles; + +#### main #### +parse_options(); +check_modules_scm(); + +if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { + $WIN = 'TRUE'; + $DELIMITER = "\\"; +} + else { + $WIN = ''; + $DELIMITER = "/"; +} + +my $binpath = ''; +if( defined $ENV{UPDMINOREXT} ) +{ + $binpath = $ENV{SOLARVER}.$DELIMITER.$ENV{INPATH}.$DELIMITER."bin".$ENV{UPDMINOREXT}.$DELIMITER ; +} +else +{ + $binpath = $ENV{SOLARVER}.$DELIMITER.$ENV{INPATH}.$DELIMITER."bin".$DELIMITER ; +} + +#%sl_modules = fetch_sourcelanguage_dirlist(); + + +if ( $mode eq "merge" ) { + if ( ! $no_gsicheck ){ + merge_gsicheck(); + } + splitfile( $sdffile ); + if ( ! $no_gsicheck ){ + unlink $sdffile; # remove temp file! + } +} +elsif( $mode eq "extract" ) { + collectfiles( $outputfile ); +} +else { + usage(); +} + +exit(0); + +######################################################### +sub splitfile{ + + my $lastFile = ''; + my $currentFile = ''; + my $cur_sdffile = ''; + my $last_sdffile = ''; + my $delim; + my $badDelim; + my $start = 'TRUE'; + my %index = (); + my %block; + + STDOUT->autoflush( 1 ); + + #print STDOUT "Open File $sdffile\n"; + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + +# my %lang_hash; + my %string_hash_ooo; + my %string_hash_so; + my %so_modules; + $so_modules{ "extras_full" } = "TRUE"; + + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + next if( $prj eq "binfilter" ); # Don't merge strings into binfilter module + chomp( $line ); + + if( is_openoffice_module( $prj ) ) + { + $string_hash_ooo { $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line; + } + else + { + $string_hash_so{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line; + } + } + } + close( MYFILE ); + + if( !defined $ENV{SRC_ROOT} ){ + print "Error, no SRC_ROOT in env found.\n"; + exit( -1 ); + } + my $src_root = $ENV{SRC_ROOT}; + #print $WIN eq "TRUE" ? $src_root."\\l10n_so\n" : $src_root."/l10n_so\n"; + my $so_l10n_path = $WIN eq "TRUE" ? $src_root."\\l10n_so\\source" : $src_root."/l10n_so/source"; + my $ooo_l10n_path = $WIN eq "TRUE" ? $src_root."\\l10n\\source" : $src_root."/l10n/source"; + + #print "$so_l10n_path\n"; + #print "$ooo_l10n_path\n"; + + write_sdf( \%string_hash_so , $so_l10n_path ); + write_sdf( \%string_hash_ooo , $ooo_l10n_path ); + +} +sub check_modules_scm +{ + #my @ooo_modules; + #my @so_modules; + my $src_path = $ENV{ SRC_ROOT } ; + my $last_dir = getcwd(); + chdir $src_path ; + my @modules = <*/.svn/entries>; + + foreach my $module ( @modules ) + { + #print "$module \n"; + if( open ( FILE , "<$module" ) ) + { + while( ) + { + + my @path = split ( "/" , $module ) ; + + if( /svn.services.openoffice.org/ ) + { + my $mod = $path[ 0 ]; + #push @ooo_modules , $mod; + $is_ooo_module{ $mod } = "true"; + # print "$module -> ooo "; + } + elsif ( /jumbo2.germany.sun.com/ ) + { + my $mod = $path[ 0 ]; + #push @so_modules , $mod; + # print "$module -> so "; + #$so_lookup_hash{ $mod } = "true"; + } + #else + #{ + # print "ERROR: Is $module a SO or OOo module? Can not parese the $module/.svn/entries file ... please check mwsfinnish/merge/splitsdf.pl line 280\n"; + # exit -1; + #} + } + } + } + chdir $last_dir ; + #print "OOO\n"; + #print @ooo_modules; + #print "\nSO\n"; + #print @so_modules; +} + + +#sub parse +#{ +# my $command = "$CVS_BINARY -d:pserver:anoncvs\@anoncvs.services.openoffice.org:/cvs co -c"; +# my $output = `$command`; +# my $rc = $? << 8; +# if ( $output eq "" || $rc < 0 ){ +# print STDERR "ERROR: Can not fetch cvs alias list, please login to the cvs server and press at the password prompt just return\ncvs -d:pserver:anoncvs\@anoncvs.services.openoffice.org:/cvs login\n"; +# exit ( -1 ); +# } +# my @list = split /\n/ , $output ; +# foreach my $string( @list ) +# { +# +# # print "Found '$1'\n" , if( $string =~ /^(\w*)/ && $1 ne "" ); +# +# $is_ooo_module{ $1 } = "TRUE", if( $string =~ /^(\w*)/ && $1 ne "" ); +# } +# # foreach my $key( keys( %is_ooo_module ) ) +# #{ +# # print "$key\n"; +# #} +#} +sub is_openoffice_module +{ + my $module = shift; + return "TRUE", if ( $force_ooo_module || defined $is_ooo_module{ $module } ); + return ""; +} + +sub write_sdf +{ + my $string_hash = shift; + my $l10n_file = shift; + + foreach my $lang( keys( %{ $string_hash } ) ) + { + my @sdf_file; + + # mkdir!!!! + my $current_l10n_file = $WIN eq "TRUE" ? $l10n_file."\\$lang\\localize.sdf" : $l10n_file."/$lang/localize.sdf"; + print "Writing '$current_l10n_file'\n"; + if( open DESTFILE , "< $current_l10n_file" ){ + + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + if ( defined $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } ) + { + # Changed String! + push @sdf_file , $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } ; + $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = undef; + } + else + { + # No new string + push @sdf_file , $line; + } + } + } + } + close( DESTFILE ); + #Now just append the enw strings + #FIXME!!! Implement insertion in the correct order + foreach my $key ( keys ( %{ $string_hash->{ $lang } } ) ) + { + push @sdf_file , $string_hash->{ $lang }{ $key } , if ( defined $string_hash->{ $lang }{ $key } ); + #print "WARNING: Not defined = ".$string_hash->{ $lang }{ $key }."\n", if( ! defined $string_hash->{ $lang }{ $key } ); + } + + # Write the new file + my ( $TMPFILE , $tmpfile ) = File::Temp::tempfile(); + if( open DESTFILE , "+> $tmpfile " ){ + print DESTFILE get_license_header(); + foreach my $string( @sdf_file ){ + print DESTFILE "$string\n"; + } + close ( DESTFILE ); + if( move( $current_l10n_file , $current_l10n_file.".backup" ) ){ + if( copy( $tmpfile , $current_l10n_file ) ){ + unlink $l10n_file.".backup"; + } else { print STDERR "Can't open/create '$l10n_file', original file is renamed to $l10n_file.backup\n"; } + } else { print STDERR "Can't open/create '$l10n_file'\n"; } + }else{ + print STDERR "WARNING: Can't open/create '$l10n_file'\n"; + } + unlink $tmpfile; + } +} + +######################################################### + +sub get_license_header{ + return +"#\n". +"# #### ### # # ### ##### ##### #### ##### ##### \n". +"# # # # # ## # # # # # # # # # \n". +"# # # # # # # # # # # ### # # # # \n". +"# # # # # # ## # # # # # # # # \n". +"# #### ### # # ### # ##### #### ##### # \n". +"#\n". +"# DO NOT EDIT! This file will be overwritten by localisation process\n". +"#\n". +"#*************************************************************************\n". +"#\n". +"# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n". +"# \n". +"# Copyright 2008 by Sun Microsystems, Inc.\n". +"#\n". +"# OpenOffice.org - a multi-platform office productivity suite\n". +"#\n". +"# \$RCSfile:". +"localize.pl,v \$\n". +"#\n". +"# \$Revision: ". +"1.17.4.1 \$\n". +"#\n". +"# This file is part of OpenOffice.org.\n". +"#\n". +"# OpenOffice.org is free software: you can redistribute it and/or modify\n". +"# it under the terms of the GNU Lesser General Public License version 3\n". +"# only, as published by the Free Software Foundation.\n". +"#\n". +"# OpenOffice.org is distributed in the hope that it will be useful,\n". +"# but WITHOUT ANY WARRANTY; without even the implied warranty of\n". +"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n". +"# GNU Lesser General Public License version 3 for more details\n". +"# (a copy is included in the LICENSE file that accompanied this code).\n". +"#\n". +"# You should have received a copy of the GNU Lesser General Public License\n". +"# version 3 along with OpenOffice.org. If not, see\n". +"# \n". +"# for a copy of the LGPLv3 License.\n". +"#\n". +"#*************************************************************************\n"; +} +######## Check input sdf file and use only the correct part +sub merge_gsicheck{ + my $command = ''; + my ( $TMPHANDLE , $tmpfile ) = File::Temp::tempfile(); + close ( $TMPHANDLE ); + + if( $ENV{WRAPCMD} ){ + $command = "$ENV{WRAPCMD} gsicheck"; + }else{ + $command = "gsicheck"; + } + my $errfile = $sdffile.".err"; + $command .= " -k -c -wcf $tmpfile -wef $errfile -l \"\" $sdffile"; + #my $rc = system( $command ); + my $output = `$command`; + my $rc = $? << 8; + if ( $output ne "" ){ + print STDOUT "### gsicheck ###\n"; + print STDOUT "### The file $errfile have been written containing the errors in your sdf file. Those lines will not be merged: ###\n\n"; + print STDOUT "$output\n"; + print STDOUT "################\n"; + + }else{ + # Remove the 0 Byte file + unlink $errfile; + } + $sdffile = $tmpfile; +} +######################################################### +# find search function +sub wanted +{ + my $file = $File::Find::name; + if( -f $file && $file =~ /.*localize.sdf$/ && !( $file =~ /.*\.svn.*/ ) ) { + push @sdfparticles , $file; + if( $bVerbose eq "1" ) { print STDOUT "$file\n"; } + else { print "."; } + } +} + +sub add_paths +{ + my $langhash_ref = shift; + my $root_dir = $ENV{ SRC_ROOT }; + my $ooo_l10n_dir = "$root_dir"."$DELIMITER"."l10n"."$DELIMITER"."source"; + my $so_l10n_dir = "$root_dir"."$DELIMITER"."l10n_so"."$DELIMITER"."source"; + + if( -e $ooo_l10n_dir ) + { + foreach my $lang ( keys( %{ $langhash_ref } ) ) + { + my $loc_file = "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; + if( -e $loc_file ) + { + push @sdfparticles , "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; + } + else { print "WARNING: $loc_file not found ....\n"; } + } + } + else { die "ERROR: Can not find directory $ooo_l10n_dir!!!" } + if( -e $so_l10n_dir ) + { + foreach my $lang ( keys( %{ $langhash_ref } ) ) + { + my $loc_file = "$so_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; + if( -e $loc_file ) + { + push @sdfparticles , "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; + } + else { #print "WARNING: $loc_file not found ....\n"; + } + } + + } +} +sub collectfiles{ + print STDOUT "### Localize\n"; + my $localizehash_ref; + my ( $bAll , $bUseLocalize, $langhash_ref , $bHasSourceLanguage , $bFakeEnglish ) = parseLanguages(); + + # Enable autoflush on STDOUT + # $| = 1; + STDOUT->autoflush( 1 ); + + ### Search sdf particles + #print STDOUT "### Searching sdf particles\n"; + my $working_path = getcwd(); + #chdir $srcpath; + #find ( { wanted => \&wanted , follow => 1 }, getcwd() ); + #chdir $working_path; + add_paths( $langhash_ref ); + #my $nFound = $#sdfparticles +1; + #print "\n $nFound files found !\n"; + + my ( $LOCALIZEPARTICLE , $localizeSDF ) = File::Temp::tempfile(); + close( $LOCALIZEPARTICLE ); + + my ( $ALLPARTICLES_MERGED , $particleSDF_merged ) = File::Temp::tempfile(); + close( $ALLPARTICLES_MERGED ); + my ( $LOCALIZE_LOG , $my_localize_log ) = File::Temp::tempfile(); + close( $LOCALIZE_LOG ); + + ## Get the localize en-US extract + if( $bAll || $bUseLocalize ){ + print "### Fetching source language strings\n"; + my $command = ""; + my $args = ""; + + if( $ENV{WRAPCMD} ){ + $command = $ENV{WRAPCMD}.$binpath."localize_sl"; + }else{ + $command = $binpath."localize_sl"; + } + print $command; + # -e + # if ( -x $command ){ + if( $command ){ + if( !$bVerbose ){ $args .= " -QQ "; } + $args .= " -e -f $localizeSDF -l "; + my $bFlag=""; + if( $bAll ) {$args .= " en-US";} + else{ + my @list; + foreach my $isokey ( keys( %{ $langhash_ref } ) ){ + push @list , $isokey; + if( $langhash_ref->{ $isokey } ne "" ){ + push @list , $langhash_ref->{ $isokey }; + } + } + remove_duplicates( \@list ); + foreach my $isokey ( @list ){ + switch :{ + ( $isokey=~ /^en-US$/i ) + && do{ + if( $bFlag eq "TRUE" ){ $args .= ",en-US"; } + else { + $args .= "en-US"; $bFlag = "TRUE"; + } + }; + + } #switch + } #foreach + } # if + } # if +# if ( !$bVerbose ){ +# if ( $WIN eq "TRUE" ) { $args .= " > $my_localize_log"; } +# else { $args .= " >& $my_localize_log"; } +# } + if ( $bVerbose ) { print STDOUT $command.$args."\n"; } + + my $rc = system( $command.$args ); + + if( $rc < 0 ){ print STDERR "ERROR: localize rc = $rc\n"; exit( -1 ); } + ( $localizehash_ref ) = read_file( $localizeSDF , $langhash_ref ); + + } + ## Get sdf particles +#***************** + open ALLPARTICLES_MERGED , "+>> $particleSDF_merged" + or die "Can't open $particleSDF_merged"; + + ## Fill fackback hash + my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); + my %block; + my $cur_fallback; + if( !$bAll) { + foreach my $cur_lang ( keys( %{ $langhash_ref } ) ){ + #print STDOUT "DBG: G1 cur_lang=$cur_lang\n"; + $cur_fallback = $langhash_ref->{ $cur_lang }; + if( $cur_fallback ne "" ){ + # Insert fallback strings + #print STDOUT "DBG: Renaming $cur_fallback to $cur_lang in fallbackhash\n"; + rename_language( $fallbackhashhash_ref , $cur_fallback , $cur_lang ); + } + foreach my $currentfile ( @sdfparticles ){ + if ( open MYFILE , "< $currentfile" ) { + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + + if ( $lang eq $cur_lang ){ + # Overwrite fallback strings with collected strings + #if( ( !has_two_sourcelanguages( $cur_lang) && $cur_lang eq "de" ) || $cur_lang ne "en-US" ){ + $fallbackhashhash_ref->{ $cur_lang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + #} + + } + } + } + }else { print STDERR "WARNING: Can't open file $currentfile"; } + } + + foreach my $line ( keys( %{$fallbackhashhash_ref->{ $cur_lang } } )) { + if( #$cur_lang ne "de" && + $cur_lang ne "en-US" ){ + print ALLPARTICLES_MERGED ( $fallbackhashhash_ref->{ $cur_lang }{ $line }, "\n" ); + } + } + } + } else { + foreach my $currentfile ( @sdfparticles ){ + if ( open MYFILE , "< $currentfile" ) { + while( ){ + print ALLPARTICLES_MERGED ( $_, "\n" ); # recheck de / en-US ! + } + } + else { print STDERR "WARNING: Can't open file $currentfile"; } + } + } + close ALLPARTICLES_MERGED; +#*************** + + # Hash of array + my %output; + my @order; + + ## Join both + if( $outputfile ){ + if( open DESTFILE , "+> $outputfile" ){ + if( !open LOCALIZEPARTICLE , "< $localizeSDF" ) { print STDERR "ERROR: Can't open file $localizeSDF\n"; } + if( !open ALLPARTICLES_MERGED , "< $particleSDF_merged" ) { print STDERR "ERROR: Can't open file $particleSDF_merged\n"; } + + # Insert localize + my $extract_date=""; + while ( ){ + if( /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + my $timestamp = defined $18 ? $18 : ''; + + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + #my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + + if( $use_default_date ) + { + $extract_date = "$default_date\n" ; + } + elsif( $extract_date eq "" ) { + $extract_date = $timestamp ; + $extract_date =~ tr/\r\n//d; + $extract_date .= "\n"; + } + + if( $bAll ){ print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } + else { + foreach my $sLang ( keys( %{ $langhash_ref } ) ){ + if( $sLang=~ /all/i ) { + push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + } + #if( $sLang eq "de" && $lang eq "de" ) { + # push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + #} + if( $sLang eq "en-US" && $lang eq "en-US" ) { + push @order , $prj.$gid.$lid.$file.$type.$plattform.$helpid; + if( !$bFakeEnglish ){ push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + } + + } + } + } + } + # Insert particles + while ( ){ + if( /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $prj = defined $3 ? $3 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + my $timestamp = defined $18 ? $18 : ''; + + #my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + #my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + + if( $use_default_date ) + { + $extract_date = "$default_date\n" ; + } + elsif( $extract_date eq "" ) + { + $extract_date = $timestamp; + } + + if( ! ( $prj =~ /binfilter/i ) ) { + push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + } + } + } + + # Write! + foreach my $curkey ( @order ){ + foreach my $curlist ( $output{ $curkey } ){ + foreach my $line ( @{$curlist} ){ + print DESTFILE $line; + } + } + } + + }else { print STDERR "Can't open $outputfile";} + } + close DESTFILE; + close LOCALIZEPARTICLE; + close ALLPARTICLES_MERGED; + + #print STDOUT "DBG: \$localizeSDF $localizeSDF \$particleSDF_merged $particleSDF_merged\n"; + unlink $localizeSDF , $particleSDF_merged , $my_localize_log; + + #sort_outfile( $outputfile ); + #remove_obsolete( $outputfile ) , if $bHasSourceLanguage ne ""; + } + +######################################################### +sub remove_obsolete{ + my $outfile = shift; + my @lines; + my $enusleftpart; + my @good_lines; + + print STDOUT "### Removing obsolete strings\n"; + + # Kick out all strings without en-US reference + if ( open ( SORTEDFILE , "< $outfile" ) ){ + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $language = defined $12 ? $12 : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + my $leftpart = $prj.$gid.$lid.$file.$type.$plattform.$helpid; + + if( $language eq "en-US" ){ # source string found, 1. entry + $enusleftpart = $leftpart; + push @good_lines , $line; + }else{ + if( !defined $enusleftpart or !defined $leftpart ){ + print STDERR "BADLINE: $line\n"; + print STDERR "\$enusleftpart = $enusleftpart\n"; + print STDERR "\$leftpart = $leftpart\n"; + } + if( $enusleftpart eq $leftpart ){ # matching language + push @good_lines , $line; + } + #else{ + # print STDERR "OUT: \$enusleftpart=$enusleftpart \$leftpart=$leftpart \$line=$line\n"; + #} + } + } + } + close SORTEDFILE; + } else { print STDERR "ERROR: Can't open file $outfile\n";} + + # Write file + if ( open ( SORTEDFILE , "> $outfile" ) ){ + foreach my $newline ( @good_lines ) { + print SORTEDFILE $newline; + } + close SORTEDFILE; + } else { print STDERR "ERROR: Can't open file $outfile\n";} + +} +######################################################### +sub sort_outfile{ + my $outfile = shift; + print STDOUT "### Sorting ... $outfile ..."; + my @lines; + my @sorted_lines; + + + #if ( open ( SORTEDFILE , "< $outputfile" ) ){ + if ( open ( SORTEDFILE , "< $outfile" ) ){ + my $line; + while ( ){ + $line = $_; + if( $line =~ /^[^\#]/ ){ + push @lines , $line; + } + } + close SORTEDFILE; + @sorted_lines = sort { + my $xa_lang = ""; + my $xa_left_part = ""; + my $xa_right_part = ""; + my $xa_timestamp = ""; + my $xb_lang = ""; + my $xb_left_part = ""; + my $xb_right_part = ""; + my $xb_timestamp = ""; + my $xa = ""; + my $xb = ""; + my @alist; + my @blist; + + if( $a=~ /$sdf_regex/ ){ + $xa_left_part = defined $2 ? $2 : ''; + $xa_lang = defined $12 ? $12 : ''; + $xa_right_part = defined $13 ? $13 : ''; + $xa_left_part = remove_last_column( $xa_left_part ); + + } + if( $b=~ /$sdf_regex/ ){ + $xb_left_part = defined $2 ? $2 : ''; + $xb_lang = defined $12 ? $12 : ''; + $xb_right_part = defined $13 ? $13 : ''; + $xb_left_part = remove_last_column( $xb_left_part ); + + + } + if( ( $xa_left_part cmp $xb_left_part ) == 0 ){ # Left part equal + if( ( $xa_lang cmp $xb_lang ) == 0 ){ # Lang equal + return ( $xa_right_part cmp $xb_right_part ); # Right part compare + } + elsif( $xa_lang eq "en-US" ) { return -1; } # en-US wins + elsif( $xb_lang eq "en-US" ) { return 1; } # en-US wins + else { return $xa_lang cmp $xb_lang; } # lang compare + } + else { + return $xa_left_part cmp $xb_left_part; # Left part compare + } + } @lines; + + if ( open ( SORTEDFILE , "> $outfile" ) ){ + print SORTEDFILE get_license_header(); + foreach my $newline ( @sorted_lines ) { + print SORTEDFILE $newline; + #print STDOUT $newline; + } + } + close SORTEDFILE; + } else { print STDERR "WARNING: Can't open file $outfile\n";} + print "done\n"; + +} +######################################################### +sub remove_last_column{ + my $string = shift; + my @alist = split ( "\t" , $string ); + pop @alist; + return join( "\t" , @alist ); +} + +######################################################### +sub rename_language{ + my $fallbackhashhash_ref = shift; + my $cur_fallback = shift; + my $cur_lang = shift; + my $line; + + foreach my $key( keys ( %{ $fallbackhashhash_ref->{ $cur_fallback } } ) ){ + $line = $fallbackhashhash_ref->{ $cur_fallback }{ $key }; + if( $line =~ /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + + $fallbackhashhash_ref->{ $cur_lang }{ $key } = $leftpart."\t".$cur_lang."\t".$rightpart; + } + } +} + +############################################################ +sub remove_duplicates{ + my $list_ref = shift; + my %tmphash; + foreach my $key ( @{ $list_ref } ){ $tmphash{ $key } = '' ; } + @{$list_ref} = keys( %tmphash ); +} + +############################################################## +sub fetch_fallback{ + my $sdfparticleslist_ref = shift; + my $localizeSDF = shift; + my $langhash_ref = shift; + my %fallbackhashhash; + my $cur_lang; + my @langlist; + + foreach my $key ( keys ( %{ $langhash_ref } ) ){ + $cur_lang = $langhash_ref->{ $key }; + if ( $cur_lang ne "" ) { + push @langlist , $cur_lang; + } + } + remove_duplicates( \@langlist ); + foreach $cur_lang ( @langlist ){ + if( $cur_lang eq "en-US" ){ + read_fallbacks_from_source( $localizeSDF , $cur_lang , \%fallbackhashhash ); + } + } + + # remove de / en-US + my @tmplist; + foreach $cur_lang( @langlist ){ + if( $cur_lang ne "en-US" ){ + push @tmplist , $cur_lang; + + } + } + @langlist = @tmplist; + if ( $#langlist +1 ){ + read_fallbacks_from_particles( $sdfparticleslist_ref , \@langlist , \%fallbackhashhash ); + + } + return (\%fallbackhashhash); +} + +######################################################### +sub write_file{ + + my $localizeFile = shift; + my $index_ref = shift; + + if( open DESTFILE , "+> $localizeFile" ){ + foreach my $key( %{ $index_ref } ){ + print DESTFILE ($index_ref->{ $key }, "\n" ); + } + close DESTFILE; + }else { + print STDERR "Can't open/create '$localizeFile'"; + } +} + +######################################################### +sub read_file{ + + my $sdffile = shift; + my $langhash_ref = shift; + my %block = (); + + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $plattform = defined $10 ? $10 : ''; + my $lang = defined $12 ? $12 : ''; + my $helpid = defined $9 ? $9 : ''; + + foreach my $isolang ( keys ( %{ $langhash_ref } ) ){ + if( $isolang=~ /$lang/i || $isolang=~ /all/i ) { $block{$prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; } + } + } + } + return (\%block); +} + +######################################################### +sub read_fallbacks_from_particles{ + + my $sdfparticleslist_ref = shift; + my $isolanglist_ref = shift; + my $fallbackhashhash_ref = shift; + my $block_ref; + foreach my $currentfile ( @{ $sdfparticleslist_ref } ){ + if ( open MYFILE , "< $currentfile" ) { + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + + foreach my $isolang ( @{$isolanglist_ref} ){ + if( $isolang=~ /$lang/i ) { + $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + } + } + } + } + }else { print STDERR "WARNING: Can't open file $currentfile"; } + } +} + +######################################################### +sub read_fallbacks_from_source{ + + my $sdffile = shift; + my $isolang = shift; + my $fallbackhashhash_ref = shift; + my $block_ref; + # read fallback for single file + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $helpid = defined $9 ? $9 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + + chomp( $line ); + if( $isolang=~ /$lang/i ) { $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + } + } + } +} + +######################################################### +sub parseLanguages{ + + my $bAll; + my $bUseLocalize; + my $bHasSourceLanguage=""; + my $bFakeEnglish=""; + my %langhash; + my $iso=""; + my $fallback=""; + + #### -l all + if( $languages=~ /all/ ){ + $bAll = "TRUE"; + $bHasSourceLanguage = "TRUE"; + } + ### -l fr=de,de + elsif( $languages=~ /.*,.*/ ){ + my @tmpstr = split "," , $languages; + for my $lang ( @tmpstr ){ + if( $lang=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ + $iso = $1; + $fallback = $4; + + if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { + $bUseLocalize = "TRUE"; + } + if( ( $iso && $iso=~ /(en-US)/i ) ) { + $bHasSourceLanguage = "TRUE"; + } + if( $fallback ) { $langhash{ $iso } = $fallback; } + else { $langhash{ $iso } = ""; } + } + } + } + ### -l de + else{ + if( $languages=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ + $iso = $1; + $fallback = $4; + + if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { + $bUseLocalize = "TRUE"; + + } + if( ( $iso && $iso=~ /(en-US)/i ) ) { + $bHasSourceLanguage = "TRUE"; + } + + if( $fallback ) { $langhash{ $iso } = $fallback; } + else { $langhash{ $iso } = ""; } + } + } + # HACK en-US always needed! + if( !$bHasSourceLanguage ){ + #$bHasSourceLanguage = "TRUE"; + $bUseLocalize = "TRUE"; + $bFakeEnglish = "TRUE"; + $langhash{ "en-US" } = ""; + } + return ( $bAll , $bUseLocalize , \%langhash , $bHasSourceLanguage, $bFakeEnglish); +} + +######################################################### +sub parse_options{ + + my $help; + my $merge; + my $extract; + my $success = GetOptions('f=s' => \$sdffile , 'l=s' => \$languages , 's=s' => \$srcpath , 'h' => \$help , 'v' => \$bVerbose , + 'm' => \$merge , 'e' => \$extract , 'x' => \$no_sort , 'd' => \$use_default_date , 'c' => \$create_dirs , + 'n' => \$no_gsicheck , 'o' => \$force_ooo_module ); + $outputfile = $sdffile; + + #print STDOUT "DBG: lang = $languages\n"; + if( !$srcpath ){ + $srcpath = "$ENV{SRC_ROOT}"; + if( !$srcpath ){ + print STDERR "No path to the source root found!\n\n"; + usage(); + exit(1); + } + } + if( $help ){ + usage(); + exit(0); + } + if( !$success || $#ARGV > 1 || ( !$sdffile ) ){ + usage(); + exit(1); + } + if( $merge && $sdffile && ! ( -r $sdffile)){ + print STDERR "Can't open file '$sdffile'\n"; + exit(1); + } + if( !( $languages=~ /[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?(,[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?)*/ ) ){ + print STDERR "Please check the -l iso code\n"; + exit(1); + } + if( ( !$merge && !$extract ) || ( $merge && $extract ) ){ usage();exit( -1 );} + if( $extract ){ $mode = "extract"; } + else { $mode = "merge"; } +} +#my $multi_localize_files = ''; h +#my $module_to_merge = ''; i +#my $sort_sdf_before = ''; g + +######################################################### +sub usage{ + + print STDERR "Usage: localize.pl\n"; + print STDERR "Split or collect SDF files\n"; + print STDERR " merge: -m -f -l l1[=f1][,l2[=f2]][...] [ -s ] [ -c ]\n"; + print STDERR " extract: -e -f -l [ -s ] [-d]\n"; + print STDERR "Options:\n"; + print STDERR " -h help\n"; + print STDERR " -m Merge mode\n"; + print STDERR " -e Extract mode\n"; + print STDERR " -f To split a big SDF file into particles\n"; + print STDERR " To collect and join all particles to one big file\n"; + print STDERR " -s Path to the modules, if no \$SRC_ROOT is set\n"; + print STDERR " -l ( all | | =fallback ) comma seperated languages\n"; + print STDERR " -d Use default date in extracted sdf file\n"; + print STDERR " -c Create needed directories\n"; + print STDERR " -g Sort sdf file before mergeing\n"; + print STDERR " -h File with localize.sdf's\n!"; + print STDERR " -n No gsicheck\n"; + print STDERR " -i Module to merge\n"; + print STDERR " -o force using ooo localization from the l10n module instead of l10n_so; \n"; + print STDERR " useful if the type can't be detected by the .svn tags; \n"; + print STDERR " -v Verbose\n"; + print STDERR "\nExample:\n"; + print STDERR "\nlocalize -e -l en-US,pt-BR=en-US -f my.sdf\n( Extract en-US and pt-BR with en-US fallback )\n"; + print STDERR "\nlocalize -m -l cs -f my.sdf\n( Merge cs translation into the sourcecode ) \n"; +} + +# my $line = defined $_ ? $_ : ''; +# my $leftpart = defined $2 ? $2 : ''; +# my $prj = defined $3 ? $3 : ''; +# my $file = defined $4 ? $4 : ''; +# my $dummy = defined $5 ? $5 : ''; +# my $type = defined $6 ? $6 : ''; +# my $gid = defined $7 ? $7 : ''; +# my $lid = defined $8 ? $8 : ''; +# my $helpid = defined $9 ? $9 : ''; +# my $plattform = defined $10 ? $10 : ''; +# my $width = defined $11 ? $11 : ''; +# my $lang = defined $12 ? $12 : ''; +# my $rightpart = defined $13 ? $13 : ''; +# my $text = defined $14 ? $14 : ''; +# my $helptext = defined $15 ? $15 : ''; +# my $quickhelptext = defined $16 ? $16 : ''; +# my $title = defined $17 ? $17 : ''; +# my $timestamp = defined $18 ? $18 : ''; + diff --git a/l10ntools/scripts/localize_old.pl b/l10ntools/scripts/localize_old.pl new file mode 100755 index 000000000000..151399d22002 --- /dev/null +++ b/l10ntools/scripts/localize_old.pl @@ -0,0 +1,1130 @@ +: +eval 'exec perl -wS $0 ${1+"$@"}' + if 0; + + +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: localize.pl,v $ +# +# $Revision: 1.18 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +use strict; +use Getopt::Long; +use IO::Handle; +use File::Find; +use File::Temp; +use File::Copy; +use File::Glob qw(:glob csh_glob); +use Cwd; + +# ver 1.1 +# +#### module lookup +#use lib ("$ENV{SOLARENV}/bin/modules", "$ENV{COMMON_ENV_TOOLS}/modules"); + +#### module lookup +# OOo conform +my @lib_dirs; +BEGIN { + if ( !defined($ENV{SOLARENV}) ) { + die "No environment found (environment variable SOLARENV is undefined)"; + } + push(@lib_dirs, "$ENV{SOLARENV}/bin/modules"); + push(@lib_dirs, "$ENV{COMMON_ENV_TOOLS}/modules") if defined($ENV{COMMON_ENV_TOOLS}); +} +use lib (@lib_dirs); + +#### globals #### +my $sdffile = ''; +my $no_sort = ''; +my $outputfile = ''; +my $mode = ''; +my $bVerbose="0"; +my $srcpath = ''; +my $WIN; +my $languages; +#my %sl_modules; # Contains all modules where en-US and de is source language +my $use_default_date = '0'; + + # ( leftpart ) ( rightpart ) + # prj file dummy type gid lid helpid pform width lang text helptext qhelptext title timestamp +my $sdf_regex = "((([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*))\t([^\t]*)\t(([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t)([^\t]*))"; +my $file_types = "(src|hrc|xcs|xcu|lng|ulf|xrm|xhp|xcd|xgf|xxl|xrb)"; +# Always use this date to prevent cvs conflicts +my $default_date = "2002-02-02 02:02:02"; + +#### main #### +parse_options(); + +if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { + $WIN = 'TRUE'; +} + else { + $WIN = ''; +} + +#%sl_modules = fetch_sourcelanguage_dirlist(); + + +if ( $mode eq "merge" ) { + merge_gsicheck(); + splitfile( $sdffile ); + unlink $sdffile; # remove temp file! +} +elsif( $mode eq "extract" ) { + collectfiles( $outputfile ); +} +else { + usage(); +} + +exit(0); + +######################################################### +sub splitfile{ + + my $lastFile = ''; + my $currentFile = ''; + my $cur_sdffile = ''; + my $last_sdffile = ''; + my $delim; + my $badDelim; + my $start = 'TRUE'; + my %index = (); + my %block; + + STDOUT->autoflush( 1 ); + + #print STDOUT "Open File $sdffile\n"; + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + next if( $prj eq "binfilter" ); # Don't merge strings into binfilter module + chomp( $line ); + $currentFile = $srcpath . '\\' . $prj . '\\' . $file; + if ( $WIN ) { $currentFile =~ s/\//\\/g; } + else { $currentFile =~ s/\\/\//g; } + + $cur_sdffile = $currentFile; + #if( $cur_sdffile =~ /\.$file_types[\s]*$/ ){ + if( $WIN ) { $cur_sdffile =~ s/\\[^\\]*\.$file_types[\s]*$/\\localize.sdf/; } + else { $cur_sdffile =~ s/\/[^\/]*\.$file_types[\s]*$/\/localize.sdf/; } + #} + + # Set default date + if( $line =~ /(.*)\t[^\t\$]*$/ ){ + $line = $1."\t".$default_date; + } + + if( $start ){ + $start=''; + $lastFile = $currentFile; # ? + $last_sdffile = $cur_sdffile; + } + + if( $lang eq "en-US" ){} + elsif( $cur_sdffile eq $last_sdffile ) + { + $block{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; + } + else + { + writesdf( $lastFile , \%block ); + $lastFile = $currentFile; #? + $last_sdffile = $cur_sdffile; + %block = (); + #if( ! $lang eq "en-US" ) { + $block{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; + #} + + } + } #else { print STDOUT "splitfile REGEX kaputt\n";} + + } + writesdf( $lastFile , \%block ); + %block = (); + close( MYFILE ); + +} +######################################################### + +#sub fetch_sourcelanguage_dirlist +#{ +# +# my $working_path = getcwd(); +# my %sl_dirlist; +# +# chdir $srcpath; +# my @all_dirs = csh_glob( "*" ); +# +# foreach my $file ( @all_dirs ) +# { +# if( -d $file ) +# { +# my $module = $file; +# $file .= "/prj/l10n"; +# $file =~ s/\//\\/ , if( $WIN ) ; +# +# if( -f $file ) # Test file /prj/l10n +# { +# $sl_dirlist{ $module } = 1; +# if( $bVerbose eq "1" ) { print STDOUT "$module: de and en-US source language detected\n"; } +# } +# } +# } +# +# chdir $working_path; +# +# return %sl_dirlist; +#} + +#sub has_two_sourcelanguages +#{ +# my $module = shift; +# return defined $sl_modules{ $module } ; +#} +sub writesdf{ + + my $lastFile = shift; + my $blockhash_ref = shift; + my $localizeFile = $lastFile; + my %index=(); + + if( $localizeFile =~ /\.$file_types[\s]*$/ ){ + if( $WIN ) { $localizeFile =~ s/\\[^\\]*\.$file_types[\s]*$/\\localize.sdf/; } + else { $localizeFile =~ s/\/[^\/]*\.$file_types[\s]*$/\/localize.sdf/; } + }else { + print STDERR "Strange filetype found '$localizeFile'\n"; + return; + } + if( open DESTFILE , "< $localizeFile" ){ + + #or die "Can't open/create '\$localizeFile'"; + + #### Build hash + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + $index{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; + + } #else { print STDOUT "writesdf REGEX kaputt $_\n";} + + } + close( DESTFILE ); + } + #### Copy new strings + my @mykeys = keys( %{ $blockhash_ref } ); + my $isDirty = "FALSE"; + foreach my $key( @mykeys ){ + if( ! defined $index{ $key } ){ + # Add new entry + $index{ $key } = $blockhash_ref->{ $key} ; + $isDirty = "TRUE"; + }elsif( $index{ $key } ne $blockhash_ref->{ $key } ){ + # Overwrite old entry + $index{ $key } = $blockhash_ref->{ $key }; + $isDirty = "TRUE"; + }else { + } + } + + #### Write file + + if( !$bVerbose ){ print STDOUT "."; } + if( $isDirty eq "TRUE" ){ + if( $bVerbose ){ print STDOUT "$localizeFile\n"; } + if( open DESTFILE , "+> $localizeFile" ){ + print DESTFILE get_license_header(); + @mykeys = sort keys( %index ); + foreach my $key( @mykeys ){ + print DESTFILE ( $index{ $key } , "\n" ); + } + close DESTFILE; + }else { + print STDOUT "WARNING: File $localizeFile is not writable , try to merge ...\n"; + my ( $TMPFILE , $tmpfile ) = File::Temp::tempfile(); + if( open DESTFILE , "+> $tmpfile " ){ + @mykeys = keys( %index ); + foreach my $key( @mykeys ){ + print DESTFILE ( $index{ $key } , "\n" ); + } + close DESTFILE; + if( move( $localizeFile , $localizeFile.".backup" ) ){ + if( copy( $tmpfile , $localizeFile ) ){ + unlink $localizeFile.".backup"; + } else { print STDERR "Can't open/create '$localizeFile', original file is renamed to $localizeFile.backup\n"; } + } else { print STDERR "Can't open/create '$localizeFile'\n"; } + }else{ + print STDERR "WARNING: Can't open/create '$localizeFile'\n"; + } + unlink $tmpfile; + } + } +# if( $no_sort eq '' ){ +# sort_outfile( $localizeFile ); +# } +} + +sub get_license_header{ + return +"#\n". +"# #### ### # # ### ##### ##### #### ##### ##### \n". +"# # # # # ## # # # # # # # # # \n". +"# # # # # # # # # # # ### # # # # \n". +"# # # # # # ## # # # # # # # # \n". +"# #### ### # # ### # ##### #### ##### # \n". +"#\n". +"# DO NOT EDIT! This file will be overwritten by localisation process\n". +"#\n". +"#*************************************************************************\n". +"#\n". +"# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n". +"# \n". +"# Copyright 2008 by Sun Microsystems, Inc.\n". +"#\n". +"# OpenOffice.org - a multi-platform office productivity suite\n". +"#\n". +"# \$RCSfile:". +"localize.pl,v \$\n". +"#\n". +"# \$Revision: ". +"1.17.4.1 \$\n". +"#\n". +"# This file is part of OpenOffice.org.\n". +"#\n". +"# OpenOffice.org is free software: you can redistribute it and/or modify\n". +"# it under the terms of the GNU Lesser General Public License version 3\n". +"# only, as published by the Free Software Foundation.\n". +"#\n". +"# OpenOffice.org is distributed in the hope that it will be useful,\n". +"# but WITHOUT ANY WARRANTY; without even the implied warranty of\n". +"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n". +"# GNU Lesser General Public License version 3 for more details\n". +"# (a copy is included in the LICENSE file that accompanied this code).\n". +"#\n". +"# You should have received a copy of the GNU Lesser General Public License\n". +"# version 3 along with OpenOffice.org. If not, see\n". +"# \n". +"# for a copy of the LGPLv3 License.\n". +"#\n". +"#*************************************************************************\n"; +} +######## Check input sdf file and use only the correct part +sub merge_gsicheck{ + my $command = ''; + my ( $TMPHANDLE , $tmpfile ) = File::Temp::tempfile(); + my ( $TMPHANDLE2 , $tmpfile2 ) = File::Temp::tempfile(); + close ( $TMPHANDLE ); + close ( $TMPHANDLE2 ); + + unlink $tmpfile2; + my $output2 = `cat $sdffile | sort > $tmpfile2`; + my $rc2 = $? << 8; + if( $rc2 ne 0 ){ + printf("ERROR: Failed -> cat $sdffile | sort > $tmpfile2\n$output2\n"); + exit( -1 ); + } + +# if( $ENV{WRAPCMD} ){ +# $command = "$ENV{WRAPCMD} gsicheck"; +# }else{ +# $command = "gsicheck"; +# } +# my $errfile = $tmpfile.".err"; +# $command .= " -k -c -wcf $tmpfile -wef $errfile -l \"\" $tmpfile2"; +# my $output = `$command`; +# my $rc = $? << 8; +# if ( $output ne "" ){ +# print STDOUT "### gsicheck ###\n"; +# print STDOUT "### The file $errfile have been written containing the errors in your sdf file. Those lines will not be merged: ###\n\n"; +# print STDOUT "$output\n"; +# print STDOUT "################\n"; +# +# }else{ +# # Remove the 0 Byte file +# unlink $errfile; +# } + $sdffile = $tmpfile2; +# unlink $tmpfile2; +} +######################################################### +sub collectfiles{ + print STDOUT "### Localize\n"; + my @sdfparticles; + my $localizehash_ref; + my ( $bAll , $bUseLocalize, $langhash_ref , $bHasSourceLanguage , $bFakeEnglish ) = parseLanguages(); + + # Enable autoflush on STDOUT + # $| = 1; + STDOUT->autoflush( 1 ); + + ### Search sdf particles + print STDOUT "### Searching sdf particles\n"; + my $working_path = getcwd(); + chdir $srcpath; + find sub { + my $file = $File::Find::name; + if( -f && $file =~ /.*localize.sdf$/ ) { + push @sdfparticles , $file; + if( $bVerbose eq "1" ) { print STDOUT "$file\n"; } + else { print "."; } + + } + } , getcwd() ;#"."; #$srcpath; + chdir $working_path; + + my $nFound = $#sdfparticles +1; + print "\n $nFound files found !\n"; + + my ( $LOCALIZEPARTICLE , $localizeSDF ) = File::Temp::tempfile(); + close( $LOCALIZEPARTICLE ); + + my ( $ALLPARTICLES_MERGED , $particleSDF_merged ) = File::Temp::tempfile(); + close( $ALLPARTICLES_MERGED ); + my ( $LOCALIZE_LOG , $my_localize_log ) = File::Temp::tempfile(); + close( $LOCALIZE_LOG ); + + ## Get the localize de,en-US extract + if( $bAll || $bUseLocalize ){ + print "### Fetching source language strings\n"; + my $command = ""; + my $args = ""; + + if( $ENV{WRAPCMD} ){ + $command = "$ENV{WRAPCMD} localize_sl"; + }else{ + $command = "localize_sl"; + } + + # -e + # if ( -x $command ){ + if( $command ){ + if( !$bVerbose ){ $args .= " -QQ -skip_links "; } + $args .= " -e -f $localizeSDF -l "; + my $bFlag=""; + if( $bAll ) {$args .= " en-US";} + else{ + my @list; + foreach my $isokey ( keys( %{ $langhash_ref } ) ){ + push @list , $isokey; + if( $langhash_ref->{ $isokey } ne "" ){ + push @list , $langhash_ref->{ $isokey }; + } + } + remove_duplicates( \@list ); + foreach my $isokey ( @list ){ + switch :{ + #( $isokey=~ /^de$/i ) + # && do{ + # if( $bFlag eq "TRUE" ){ $args .= ",de"; } + # else { + # $args .= "de"; $bFlag = "TRUE"; + # } + # }; + ( $isokey=~ /^en-US$/i ) + && do{ + if( $bFlag eq "TRUE" ){ $args .= ",en-US"; } + else { + $args .= "en-US"; $bFlag = "TRUE"; + } + }; + + } #switch + } #foreach + } # if + } # if +# if ( !$bVerbose ){ +# if ( $WIN eq "TRUE" ) { $args .= " > $my_localize_log"; } +# else { $args .= " >& $my_localize_log"; } +# } + if ( $bVerbose ) { print STDOUT $command.$args."\n"; } + + my $rc = system( $command.$args ); + + #my $output = `$command.$args`; + #my $rc = $? << 8; + + if( $rc < 0 ){ print STDERR "ERROR: localize rc = $rc\n"; exit( -1 ); } + ( $localizehash_ref ) = read_file( $localizeSDF , $langhash_ref ); + + } + ## Get sdf particles + open ALLPARTICLES_MERGED , "+>> $particleSDF_merged" + or die "Can't open $particleSDF_merged"; + + ## Fill fackback hash + my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); +# my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); + my %block; + my $cur_fallback; + if( !$bAll) { + foreach my $cur_lang ( keys( %{ $langhash_ref } ) ){ + #print STDOUT "DBG: G1 cur_lang=$cur_lang\n"; + $cur_fallback = $langhash_ref->{ $cur_lang }; + if( $cur_fallback ne "" ){ + # Insert fallback strings + #print STDOUT "DBG: Renaming $cur_fallback to $cur_lang in fallbackhash\n"; + rename_language( $fallbackhashhash_ref , $cur_fallback , $cur_lang ); + } + foreach my $currentfile ( @sdfparticles ){ + if ( open MYFILE , "< $currentfile" ) { + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + + if ( $lang eq $cur_lang ){ + # Overwrite fallback strings with collected strings + #if( ( !has_two_sourcelanguages( $cur_lang) && $cur_lang eq "de" ) || $cur_lang ne "en-US" ){ + $fallbackhashhash_ref->{ $cur_lang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + #} + + } + } + } + }else { print STDERR "WARNING: Can't open file $currentfile"; } + } + + foreach my $line ( keys( %{$fallbackhashhash_ref->{ $cur_lang } } )) { + if( #$cur_lang ne "de" && + $cur_lang ne "en-US" ){ + print ALLPARTICLES_MERGED ( $fallbackhashhash_ref->{ $cur_lang }{ $line }, "\n" ); + } + } + } + } else { + foreach my $currentfile ( @sdfparticles ){ + if ( open MYFILE , "< $currentfile" ) { + while( ){ + print ALLPARTICLES_MERGED ( $_, "\n" ); # recheck de / en-US ! + } + } + else { print STDERR "WARNING: Can't open file $currentfile"; } + } + } + close ALLPARTICLES_MERGED; + + + # Hash of array + my %output; + my @order; + + ## Join both + if( $outputfile ){ + if( open DESTFILE , "+> $outputfile" ){ + if( !open LOCALIZEPARTICLE , "< $localizeSDF" ) { print STDERR "ERROR: Can't open file $localizeSDF\n"; } + if( !open ALLPARTICLES_MERGED , "< $particleSDF_merged" ) { print STDERR "ERROR: Can't open file $particleSDF_merged\n"; } + + # Insert localize + my $extract_date=""; + while ( ){ + if( /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + my $timestamp = defined $18 ? $18 : ''; + + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + #my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + + if( $use_default_date ) + { + $extract_date = "$default_date\n" ; + } + elsif( $extract_date eq "" ) { + $extract_date = $timestamp ; + $extract_date =~ tr/\r\n//d; + $extract_date .= "\n"; + } + + if( $bAll ){ print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } + else { + foreach my $sLang ( keys( %{ $langhash_ref } ) ){ + if( $sLang=~ /all/i ) { + push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + } + #if( $sLang eq "de" && $lang eq "de" ) { + # push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + #} + if( $sLang eq "en-US" && $lang eq "en-US" ) { + push @order , $prj.$gid.$lid.$file.$type.$plattform.$helpid; + if( !$bFakeEnglish ){ push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; + } + + } + } + } + } + # Insert particles + while ( ){ + if( /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $prj = defined $3 ? $3 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + my $timestamp = defined $18 ? $18 : ''; + + #my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + #my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + + if( $use_default_date ) + { + $extract_date = "$default_date\n" ; + } + elsif( $extract_date eq "" ) + { + $extract_date = $timestamp; + } + + if( ! ( $prj =~ /binfilter/i ) ) { + push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; + } + } + } + + # Write! + foreach my $curkey ( @order ){ + foreach my $curlist ( $output{ $curkey } ){ + foreach my $line ( @{$curlist} ){ + print DESTFILE $line; + } + } + } + + }else { print STDERR "Can't open $outputfile";} + } + close DESTFILE; + close LOCALIZEPARTICLE; + close ALLPARTICLES_MERGED; + + #print STDOUT "DBG: \$localizeSDF $localizeSDF \$particleSDF_merged $particleSDF_merged\n"; + unlink $localizeSDF , $particleSDF_merged , $my_localize_log; + + #sort_outfile( $outputfile ); + #remove_obsolete( $outputfile ) , if $bHasSourceLanguage ne ""; + } + +######################################################### +sub remove_obsolete{ + my $outfile = shift; + my @lines; + my $enusleftpart; + my @good_lines; + + print STDOUT "### Removing obsolete strings\n"; + + # Kick out all strings without en-US reference + if ( open ( SORTEDFILE , "< $outfile" ) ){ + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $language = defined $12 ? $12 : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + my $leftpart = $prj.$gid.$lid.$file.$type.$plattform.$helpid; + + if( $language eq "en-US" ){ # source string found, 1. entry + $enusleftpart = $leftpart; + push @good_lines , $line; + }else{ + if( !defined $enusleftpart or !defined $leftpart ){ + print STDERR "BADLINE: $line\n"; + print STDERR "\$enusleftpart = $enusleftpart\n"; + print STDERR "\$leftpart = $leftpart\n"; + } + if( $enusleftpart eq $leftpart ){ # matching language + push @good_lines , $line; + } + #else{ + # print STDERR "OUT: \$enusleftpart=$enusleftpart \$leftpart=$leftpart \$line=$line\n"; + #} + } + } + } + close SORTEDFILE; + } else { print STDERR "ERROR: Can't open file $outfile\n";} + + # Write file + if ( open ( SORTEDFILE , "> $outfile" ) ){ + foreach my $newline ( @good_lines ) { + print SORTEDFILE $newline; + } + close SORTEDFILE; + } else { print STDERR "ERROR: Can't open file $outfile\n";} + +} +######################################################### +sub sort_outfile{ + my $outfile = shift; + print STDOUT "### Sorting ... $outfile ..."; + my @lines; + my @sorted_lines; + + + #if ( open ( SORTEDFILE , "< $outputfile" ) ){ + if ( open ( SORTEDFILE , "< $outfile" ) ){ + my $line; + while ( ){ + $line = $_; + if( $line =~ /^[^\#]/ ){ + push @lines , $line; + } + } + close SORTEDFILE; + @sorted_lines = sort { + my $xa_lang = ""; + my $xa_left_part = ""; + my $xa_right_part = ""; + my $xa_timestamp = ""; + my $xb_lang = ""; + my $xb_left_part = ""; + my $xb_right_part = ""; + my $xb_timestamp = ""; + my $xa = ""; + my $xb = ""; + my @alist; + my @blist; + + if( $a=~ /$sdf_regex/ ){ + $xa_left_part = defined $2 ? $2 : ''; + $xa_lang = defined $12 ? $12 : ''; + $xa_right_part = defined $13 ? $13 : ''; + $xa_left_part = remove_last_column( $xa_left_part ); + + } + if( $b=~ /$sdf_regex/ ){ + $xb_left_part = defined $2 ? $2 : ''; + $xb_lang = defined $12 ? $12 : ''; + $xb_right_part = defined $13 ? $13 : ''; + $xb_left_part = remove_last_column( $xb_left_part ); + + + } + if( ( $xa_left_part cmp $xb_left_part ) == 0 ){ # Left part equal + if( ( $xa_lang cmp $xb_lang ) == 0 ){ # Lang equal + return ( $xa_right_part cmp $xb_right_part ); # Right part compare + } + elsif( $xa_lang eq "en-US" ) { return -1; } # en-US wins + elsif( $xb_lang eq "en-US" ) { return 1; } # en-US wins + else { return $xa_lang cmp $xb_lang; } # lang compare + } + else { + return $xa_left_part cmp $xb_left_part; # Left part compare + } + } @lines; + + if ( open ( SORTEDFILE , "> $outfile" ) ){ + print SORTEDFILE get_license_header(); + foreach my $newline ( @sorted_lines ) { + print SORTEDFILE $newline; + #print STDOUT $newline; + } + } + close SORTEDFILE; + } else { print STDERR "WARNING: Can't open file $outfile\n";} + print "done\n"; + +} +######################################################### +sub remove_last_column{ + my $string = shift; + my @alist = split ( "\t" , $string ); + pop @alist; + return join( "\t" , @alist ); +} + +######################################################### +sub rename_language{ + my $fallbackhashhash_ref = shift; + my $cur_fallback = shift; + my $cur_lang = shift; + my $line; + + foreach my $key( keys ( %{ $fallbackhashhash_ref->{ $cur_fallback } } ) ){ + $line = $fallbackhashhash_ref->{ $cur_fallback }{ $key }; + if( $line =~ /$sdf_regex/ ){ + my $leftpart = defined $2 ? $2 : ''; + my $lang = defined $12 ? $12 : ''; + my $rightpart = defined $13 ? $13 : ''; + + $fallbackhashhash_ref->{ $cur_lang }{ $key } = $leftpart."\t".$cur_lang."\t".$rightpart; + } + } +} + +############################################################ +sub remove_duplicates{ + my $list_ref = shift; + my %tmphash; + foreach my $key ( @{ $list_ref } ){ $tmphash{ $key } = '' ; } + @{$list_ref} = keys( %tmphash ); +} + +############################################################## +sub fetch_fallback{ + my $sdfparticleslist_ref = shift; + my $localizeSDF = shift; + my $langhash_ref = shift; + my %fallbackhashhash; + my $cur_lang; + my @langlist; + + foreach my $key ( keys ( %{ $langhash_ref } ) ){ + $cur_lang = $langhash_ref->{ $key }; + if ( $cur_lang ne "" ) { + push @langlist , $cur_lang; + } + } + remove_duplicates( \@langlist ); + foreach $cur_lang ( @langlist ){ + if( $cur_lang eq "en-US" ){ + read_fallbacks_from_source( $localizeSDF , $cur_lang , \%fallbackhashhash ); + } + } + + # remove de / en-US + my @tmplist; + foreach $cur_lang( @langlist ){ + if( $cur_lang ne "en-US" ){ + push @tmplist , $cur_lang; + + } + } + @langlist = @tmplist; + if ( $#langlist +1 ){ + read_fallbacks_from_particles( $sdfparticleslist_ref , \@langlist , \%fallbackhashhash ); + + } + return (\%fallbackhashhash); +} + +######################################################### +sub write_file{ + + my $localizeFile = shift; + my $index_ref = shift; + + if( open DESTFILE , "+> $localizeFile" ){ + foreach my $key( %{ $index_ref } ){ + print DESTFILE ($index_ref->{ $key }, "\n" ); + } + close DESTFILE; + }else { + print STDERR "Can't open/create '$localizeFile'"; + } +} + +######################################################### +sub read_file{ + + my $sdffile = shift; + my $langhash_ref = shift; + my %block = (); + + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $plattform = defined $10 ? $10 : ''; + my $lang = defined $12 ? $12 : ''; + my $helpid = defined $9 ? $9 : ''; + + foreach my $isolang ( keys ( %{ $langhash_ref } ) ){ + if( $isolang=~ /$lang/i || $isolang=~ /all/i ) { $block{$prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; } + } + } + } + return (\%block); +} + +######################################################### +sub read_fallbacks_from_particles{ + + my $sdfparticleslist_ref = shift; + my $isolanglist_ref = shift; + my $fallbackhashhash_ref = shift; + my $block_ref; + foreach my $currentfile ( @{ $sdfparticleslist_ref } ){ + if ( open MYFILE , "< $currentfile" ) { + while(){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + my $helpid = defined $9 ? $9 : ''; + + chomp( $line ); + + foreach my $isolang ( @{$isolanglist_ref} ){ + if( $isolang=~ /$lang/i ) { + $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + } + } + } + } + }else { print STDERR "WARNING: Can't open file $currentfile"; } + } +} + +######################################################### +sub read_fallbacks_from_source{ + + my $sdffile = shift; + my $isolang = shift; + my $fallbackhashhash_ref = shift; + my $block_ref; + # read fallback for single file + open MYFILE , "< $sdffile" + or die "Can't open '$sdffile'\n"; + + while( ){ + if( /$sdf_regex/ ){ + my $line = defined $_ ? $_ : ''; + my $prj = defined $3 ? $3 : ''; + my $file = defined $4 ? $4 : ''; + my $type = defined $6 ? $6 : ''; + my $gid = defined $7 ? $7 : ''; + my $lid = defined $8 ? $8 : ''; + my $helpid = defined $9 ? $9 : ''; + my $lang = defined $12 ? $12 : ''; + my $plattform = defined $10 ? $10 : ''; + + chomp( $line ); + if( $isolang=~ /$lang/i ) { $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; + } + } + } +} + +######################################################### +sub parseLanguages{ + + my $bAll; + my $bUseLocalize; + my $bHasSourceLanguage=""; + my $bFakeEnglish=""; + my %langhash; + my $iso=""; + my $fallback=""; + + #### -l all + if( $languages=~ /all/ ){ + $bAll = "TRUE"; + $bHasSourceLanguage = "TRUE"; + } + ### -l fr=de,de + elsif( $languages=~ /.*,.*/ ){ + my @tmpstr = split "," , $languages; + for my $lang ( @tmpstr ){ + if( $lang=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ + $iso = $1; + $fallback = $4; + + if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { + $bUseLocalize = "TRUE"; + } + if( ( $iso && $iso=~ /(en-US)/i ) ) { + $bHasSourceLanguage = "TRUE"; + } + if( $fallback ) { $langhash{ $iso } = $fallback; } + else { $langhash{ $iso } = ""; } + } + } + } + ### -l de + else{ + if( $languages=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ + $iso = $1; + $fallback = $4; + + if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { + $bUseLocalize = "TRUE"; + + } + if( ( $iso && $iso=~ /(en-US)/i ) ) { + $bHasSourceLanguage = "TRUE"; + } + + if( $fallback ) { $langhash{ $iso } = $fallback; } + else { $langhash{ $iso } = ""; } + } + } + # HACK en-US always needed! + if( !$bHasSourceLanguage ){ + #$bHasSourceLanguage = "TRUE"; + $bUseLocalize = "TRUE"; + $bFakeEnglish = "TRUE"; + $langhash{ "en-US" } = ""; + } + return ( $bAll , $bUseLocalize , \%langhash , $bHasSourceLanguage, $bFakeEnglish); +} + +######################################################### +sub parse_options{ + + my $help; + my $merge; + my $extract; + my $success = GetOptions('f=s' => \$sdffile , 'l=s' => \$languages , 's=s' => \$srcpath , 'h' => \$help , 'v' => \$bVerbose , + 'm' => \$merge , 'e' => \$extract , 'x' => \$no_sort , 'd' => \$use_default_date ); + $outputfile = $sdffile; + + #print STDOUT "DBG: lang = $languages\n"; + if( !$srcpath ){ + #$srcpath = "$ENV{SRC_ROOT}"; + if( !$srcpath ){ + print STDERR "No path to the source root found!\n\n"; + usage(); + exit(1); + } + } + if( $help || !$success || $#ARGV > 1 || ( !$sdffile ) ){ + usage(); + exit(1); + } + if( $merge && $sdffile && ! ( -r $sdffile)){ + print STDERR "Can't open file '$sdffile'\n"; + exit(1); + } + if( !( $languages=~ /[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?(,[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?)*/ ) ){ + print STDERR "Please check the -l iso code\n"; + exit(1); + } + if( ( !$merge && !$extract ) || ( $merge && $extract ) ){ usage();exit( -1 );} + if( $extract ){ $mode = "extract"; } + else { $mode = "merge"; } +} + +######################################################### +sub usage{ + + print STDERR "Usage: localize.pl\n"; + print STDERR "Split or collect SDF files\n"; + print STDERR " merge: -m -f -l l1[=f1][,l2[=f2]][...] [ -s ]\n"; + print STDERR " extract: -e -f -l [ -s ] [-d]\n"; + print STDERR "Options:\n"; + print STDERR " -h help\n"; + print STDERR " -m Merge mode\n"; + print STDERR " -e Extract mode\n"; + print STDERR " -f To split a big SDF file into particles\n"; + print STDERR " To collect and join all particles to one big file\n"; + print STDERR " -s Path to the modules, if no \$SRC_ROOT is set\n"; + print STDERR " -l ( all | | =fallback ) comma seperated languages\n"; + print STDERR " -d Use default date in extracted sdf file\n"; + print STDERR " -v Verbose\n"; + print STDERR "\nExample:\n"; + print STDERR "\nlocalize -e -l en-US,pt-BR=en-US -f my.sdf\n( Extract en-US and pt-BR with en-US fallback )\n"; + print STDERR "\nlocalize -m -l cs -f my.sdf\n( Merge cs translation into the sourcecode ) \n"; +} + +# my $line = defined $_ ? $_ : ''; +# my $leftpart = defined $2 ? $2 : ''; +# my $prj = defined $3 ? $3 : ''; +# my $file = defined $4 ? $4 : ''; +# my $dummy = defined $5 ? $5 : ''; +# my $type = defined $6 ? $6 : ''; +# my $gid = defined $7 ? $7 : ''; +# my $lid = defined $8 ? $8 : ''; +# my $helpid = defined $9 ? $9 : ''; +# my $plattform = defined $10 ? $10 : ''; +# my $width = defined $11 ? $11 : ''; +# my $lang = defined $12 ? $12 : ''; +# my $rightpart = defined $13 ? $13 : ''; +# my $text = defined $14 ? $14 : ''; +# my $helptext = defined $15 ? $15 : ''; +# my $quickhelptext = defined $16 ? $16 : ''; +# my $title = defined $17 ? $17 : ''; +# my $timestamp = defined $18 ? $18 : ''; + diff --git a/l10ntools/source/cfg_yy_wrapper.c b/l10ntools/source/cfg_yy_wrapper.c new file mode 100644 index 000000000000..ac678d17f399 --- /dev/null +++ b/l10ntools/source/cfg_yy_wrapper.c @@ -0,0 +1,2 @@ +// Helper to suppress warnings in lex generated c code, see #i57362# +#include "cfg_yy.c" diff --git a/l10ntools/source/cfglex.l b/l10ntools/source/cfglex.l new file mode 100644 index 000000000000..dd2d9a45ab59 --- /dev/null +++ b/l10ntools/source/cfglex.l @@ -0,0 +1,232 @@ +%{ +/* + * lexer for parsing cfg source files + * + */ + + +/* enlarge token buffer to tokenize whole strings */ +#undef YYLMAX +#define YYLMAX 64000 + +/* to enable debug output define LEXDEBUG */ +#define LEXDEBUG 1 +#ifdef LEXDEBUG +#define OUTPUT fprintf +#else +#define OUTPUT(Par1,Par2); +#endif + +/* table of possible token ids */ +#include "tokens.h" +#include +#include + +#if defined __GNUC__ +#pragma GCC system_header +#elif defined __SINPRO_CC +#pragma disable_warn +#elif defined _MSC_VER +#pragma warning(push, 1) +#endif + +/* external functions (C++ code, declared as extren "C" */ +extern int WorkOnTokenSet( int, char* ); +extern int InitCfgExport( char * , char *); +extern int EndCfgExport(); +extern int GetError(); +extern int SetError(); +extern char *GetOutputFile( int argc, char* argv[]); +extern FILE *GetCfgFile(); +extern int isQuiet(); +extern void removeTempFile(); +extern char* getFilename(); +/* forwards */ +void YYWarning(); + +int bText=0; +%} + +%p 24000 +%e 1200 +%n 500 + +%% + +\<[^\>]*"xml:lang="\""x-no-translate"\"[^\<]*\/\> { + bText = 0; + WorkOnTokenSet( CFG_TOKEN_NO_TRANSLATE, yytext ); +} + +\<.*\/\> { + bText = 0; + WorkOnTokenSet( ANYTOKEN, yytext ); +} + +\<[^\>]*"xml:lang="\".*\"[^\<]*\> { + bText = 1; + WorkOnTokenSet( CFG_TEXT_START, yytext ); +} + + +\<[^\/\!][^\>]*\> { + bText = 0; + WorkOnTokenSet( CFG_TAG, yytext ); +} + +"]*\> { + bText = 0; + WorkOnTokenSet( CFG_TAG, yytext ); +} + + +\<\!\-\- { + char c1 = 0, c2 = 0, c3 = input(); + char pChar[2]; + pChar[1] = 0x00; + pChar[0] = c3; + + WorkOnTokenSet( COMMEND, yytext ); + WorkOnTokenSet( COMMEND, pChar ); + + for(;;) { + if ( c3 == EOF ) + break; + if ( c1 == '-' && c2 == '-' && c3 == '>' ) + break; + c1 = c2; + c2 = c3; + c3 = input(); + pChar[0] = c3; + WorkOnTokenSet( COMMEND, pChar ); + } +} + +\<\/[^\>]*\> { + bText = 0; + WorkOnTokenSet( CFG_CLOSETAG, yytext ); +} + +\<[^\>\!]*\> { + bText = 0; + if ( yytext[ 1 ] == '!' && yytext[ 2 ] == '-' && yytext[ 3 ] == '-' ) + WorkOnTokenSet( COMMEND, yytext ); + else + WorkOnTokenSet( CFG_UNKNOWNTAG, yytext ); +} + +.|\n { + if ( bText == 1 ) + WorkOnTokenSet( CFG_TEXTCHAR, yytext ); + else + WorkOnTokenSet( UNKNOWNCHAR, yytext ); +} + + +%% + +/*****************************************************************************/ +int yywrap(void) +/*****************************************************************************/ +{ + return 1; +} + +/*****************************************************************************/ +void YYWarning( char *s ) +/*****************************************************************************/ +{ + /* write warning to stderr */ + fprintf( stderr, + "Warning: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); +} + +/*****************************************************************************/ +#ifdef GCC +void yyerror ( char *s, ... ) +#else +void yyerror ( char *s ) +#endif +/*****************************************************************************/ +{ + /* write error to stderr */ + fprintf( stderr, + "Error: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); + SetError(); +} + +/*****************************************************************************/ +int +#ifdef WNT +_cdecl +#endif +main( int argc, char* argv[]) +/*****************************************************************************/ +{ + /* error level */ + int nRetValue = 0; + char *pOutput; + FILE *pFile; + + pOutput = GetOutputFile( argc, argv ); + if( !isQuiet() ){ + fprintf( stdout, "\nCfgEx 0.9 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); + fprintf( stdout, "======================================================================\n" ); + } + + if ( !pOutput ) { + fprintf( stdout, "Syntax: CFGEX[-p Prj][-r PrjRoot]-i FileIn [-o FileOut][-m DataBase][-e][-b][-u][-f][-d DoneFile][-g[:dtd] ][-L l1,l2,...]\n" ); + fprintf( stdout, " Prj: Project\n" ); + fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); + fprintf( stdout, " FileIn: Source files (*.src)\n" ); + fprintf( stdout, " FileOut: Destination file (*.*)\n" ); + fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); + fprintf( stdout, " -QQ: quiet output\n" ); + fprintf( stdout, " -e: Disable writing errorlog\n" ); + fprintf( stdout, " -b: Break when Token \"HelpText\" found in source\n" ); + fprintf( stdout, " -u: [english] and [german] are allowed, Id is Taken from DataBase \n" ); + fprintf( stdout, " -f: force extraction and merge even if only one language is existent\n" ); + fprintf( stdout, " -g[:dtd]: enables generation of properties (dtds if :dtd is set) - in this case FileOut is the output path\n" ); + fprintf( stdout, " -d: enables generation of *.don if work is done\n" ); + fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); + fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); + fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); + fprintf( stdout, " Example: -L de,es=en-US\n" ); + fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); + return 1; + } + + pFile = GetCfgFile(); + InitCfgExport( pOutput , getFilename() ); + if ( !pFile ) + return 1; + + yyin = pFile; + + /* create global instance of class CfgExport */ + //InitCfgExport( pOutput ); + + /* start parser */ + yylex(); + + /* get error info. and end export */ + nRetValue = GetError(); + EndCfgExport(); + + if( !isQuiet() ){ + fprintf( stdout, "\n===================================\n\n" ); + } + + removeTempFile(); +/* return error level */ + return nRetValue; +} + +/*""]*"-->" { + bText = 0; + WorkOnTokenSet( COMMEND, yytext ); +}*/ +/*" { + bText = 0; + WorkOnTokenSet( CFG_TAG, yytext ); +}*/ diff --git a/l10ntools/source/cfgmerge.cxx b/l10ntools/source/cfgmerge.cxx new file mode 100644 index 000000000000..5d85a4835843 --- /dev/null +++ b/l10ntools/source/cfgmerge.cxx @@ -0,0 +1,886 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: cfgmerge.cxx,v $ + * $Revision: 1.46 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +#include + +// local includes +#include "export.hxx" +#include "cfgmerge.hxx" +#include "tokens.h" +#include "utf8conv.hxx" + +extern "C" { int yyerror( char * ); } +extern "C" { int YYWarning( char * ); } + +// defines to parse command line +#define STATE_NON 0x0001 +#define STATE_INPUT 0x0002 +#define STATE_OUTPUT 0x0003 +#define STATE_PRJ 0x0004 +#define STATE_ROOT 0x0005 +#define STATE_MERGESRC 0x0006 +#define STATE_ERRORLOG 0x0007 +#define STATE_UTF8 0x0008 +#define STATE_LANGUAGES 0X0009 +#define STATE_ISOCODE99 0x000A +#define STATE_FORCE 0x000B + +// set of global variables +BOOL bEnableExport; +BOOL bMergeMode; +BOOL bErrorLog; +BOOL bForce; +BOOL bUTF8; +bool bQuiet; +ByteString sPrj; +ByteString sPrjRoot; +ByteString sInputFileName; +ByteString sActFileName; +ByteString sFullEntry; +ByteString sOutputFile; +ByteString sMergeSrc; +String sUsedTempFile; + +CfgParser *pParser; + +extern "C" { +// the whole interface to lexer is in this extern "C" section + +/*****************************************************************************/ +extern char *GetOutputFile( int argc, char* argv[]) +/*****************************************************************************/ +{ + bEnableExport = FALSE; + bMergeMode = FALSE; + bErrorLog = TRUE; + bForce = FALSE; + bUTF8 = TRUE; + bQuiet = false; + sPrj = ""; + sPrjRoot = ""; + sInputFileName = ""; + sActFileName = ""; + + USHORT nState = STATE_NON; + BOOL bInput = FALSE; + + // parse command line + for( int i = 1; i < argc; i++ ) { + ByteString sSwitch( argv[ i ] ); + sSwitch.ToUpperAscii(); + + if ( sSwitch == "-I" ) { + nState = STATE_INPUT; // next token specifies source file + } + else if ( sSwitch == "-O" ) { + nState = STATE_OUTPUT; // next token specifies the dest file + } + else if ( sSwitch == "-P" ) { + nState = STATE_PRJ; // next token specifies the cur. project + } + else if ( sSwitch == "-R" ) { + nState = STATE_ROOT; // next token specifies path to project root + } + else if ( sSwitch == "-M" ) { + nState = STATE_MERGESRC; // next token specifies the merge database + } + else if ( sSwitch == "-E" ) { + nState = STATE_ERRORLOG; + bErrorLog = FALSE; + } + else if ( sSwitch == "-UTF8" ) { + nState = STATE_UTF8; + bUTF8 = TRUE; + } + else if ( sSwitch == "-NOUTF8" ) { + nState = STATE_UTF8; + bUTF8 = FALSE; + } + else if ( sSwitch == "-F" ) { + nState = STATE_FORCE; + bForce = TRUE; + } + else if ( sSwitch == "-QQ" ) { + bQuiet = true; + } + else if ( sSwitch == "-L" ) { + nState = STATE_LANGUAGES; + } + else if ( sSwitch.ToUpperAscii() == "-ISO99" ) { + nState = STATE_ISOCODE99; + } + else { + switch ( nState ) { + case STATE_NON: { + return NULL; // no valid command line + } + case STATE_INPUT: { + sInputFileName = argv[ i ]; + bInput = TRUE; // source file found + } + break; + case STATE_OUTPUT: { + sOutputFile = argv[ i ]; // the dest. file + } + break; + case STATE_PRJ: { + sPrj = ByteString( argv[ i ]); +// sPrj.ToLowerAscii(); // the project + } + break; + case STATE_ROOT: { + sPrjRoot = ByteString( argv[ i ]); // path to project root + } + break; + case STATE_MERGESRC: { + sMergeSrc = ByteString( argv[ i ]); + bMergeMode = TRUE; // activate merge mode, cause merge database found + } + break; + case STATE_LANGUAGES: { + Export::sLanguages = ByteString( argv[ i ]); + } + break; + } + } + } + + if ( bInput ) { + // command line is valid + bEnableExport = TRUE; + char *pReturn = new char[ sOutputFile.Len() + 1 ]; + strcpy( pReturn, sOutputFile.GetBuffer()); // #100211# - checked + return pReturn; + } + + // command line is not valid + return NULL; +} +int isQuiet(){ + if( bQuiet ) return 1; + else return 0; +} +/*****************************************************************************/ +int InitCfgExport( char *pOutput , char* pFilename ) +/*****************************************************************************/ +{ + // instanciate Export + ByteString sOutput( pOutput ); + ByteString sFilename( pFilename ); + Export::InitLanguages(); + + if ( bMergeMode ) + pParser = new CfgMerge( sMergeSrc, sOutputFile, sFilename ); + else if ( sOutputFile.Len()) + pParser = new CfgExport( sOutputFile, sPrj, sActFileName ); + + return 1; +} + +/*****************************************************************************/ +int EndCfgExport() +/*****************************************************************************/ +{ + delete pParser; + + return 1; +} + +void removeTempFile(){ + if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ + DirEntry aTempFile( sUsedTempFile ); + aTempFile.Kill(); + } +} +extern const char* getFilename() +{ + return sInputFileName.GetBuffer(); +} +/*****************************************************************************/ +extern FILE *GetCfgFile() +/*****************************************************************************/ +{ + FILE *pFile = 0; + // look for valid filename + if ( sInputFileName.Len()) { + if( Export::fileHasUTF8ByteOrderMarker( sInputFileName ) ){ + DirEntry aTempFile = Export::GetTempFile(); + DirEntry aSourceFile( String( sInputFileName , RTL_TEXTENCODING_ASCII_US ) ); + aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); + String sTempFile = aTempFile.GetFull(); + Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); + pFile = fopen( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ).GetBuffer(), "r" ); + sUsedTempFile = sTempFile; + }else{ + // able to open file? + pFile = fopen( sInputFileName.GetBuffer(), "r" ); + sUsedTempFile = String::CreateFromAscii(""); + } + if ( !pFile ){ + fprintf( stderr, "Error: Could not open file %s\n", + sInputFileName.GetBuffer()); + exit( 13 ); + } + else { + // this is a valid file which can be opened, so + // create path to project root + DirEntry aEntry( String( sInputFileName, RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + sFullEntry= ByteString( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( sPrjRoot ); + ByteString sPrjEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + // create file name, beginnig with project root + // (e.g.: source\ui\src\menue.src) +// printf("sFullEntry = %s\n",sFullEntry.GetBuffer()); + sActFileName = sFullEntry.Copy( sPrjEntry.Len() + 1 ); +// printf("sActFileName = %s\n",sActFileName.GetBuffer()); + if( !bQuiet ) + fprintf( stdout, "\nProcessing File %s ...\n", sInputFileName.GetBuffer()); + + sActFileName.SearchAndReplaceAll( "/", "\\" ); + + return pFile; + } + } + // this means the file could not be opened + return NULL; +} + +/*****************************************************************************/ +int WorkOnTokenSet( int nTyp, char *pTokenText ) +/*****************************************************************************/ +{ + pParser->Execute( nTyp, pTokenText ); + + return 1; +} + + +/*****************************************************************************/ +int SetError() +/*****************************************************************************/ +{ + return 1; +} + +/*****************************************************************************/ +int GetError() +/*****************************************************************************/ +{ + return 0; +} +} + +// +// class CfgStackData +// + +CfgStackData* CfgStack::Push( const ByteString &rTag, const ByteString &rId ) +{ + CfgStackData *pD = new CfgStackData( rTag, rId ); + Insert( pD, LIST_APPEND ); + return pD; +} + +// +// class CfgStack +// + +/*****************************************************************************/ +CfgStack::~CfgStack() +/*****************************************************************************/ +{ + for ( ULONG i = 0; i < Count(); i++ ) + delete GetObject( i ); +} + +/*****************************************************************************/ +ByteString CfgStack::GetAccessPath( ULONG nPos ) +/*****************************************************************************/ +{ + if ( nPos == LIST_APPEND ) + nPos = Count() - 1; + + ByteString sReturn; + for ( ULONG i = 0; i <= nPos; i++ ) { + if ( i ) + sReturn += "."; + sReturn += GetStackData( i )->GetIdentifier(); + } + + return sReturn; +} + +/*****************************************************************************/ +CfgStackData *CfgStack::GetStackData( ULONG nPos ) +/*****************************************************************************/ +{ + if ( nPos == LIST_APPEND ) + nPos = Count() - 1; + + return GetObject( nPos ); +} + +// +// class CfgParser +// + +/*****************************************************************************/ +CfgParser::CfgParser() +/*****************************************************************************/ + : pStackData( NULL ), + bLocalize( FALSE ) +{ +} + +/*****************************************************************************/ +CfgParser::~CfgParser() +/*****************************************************************************/ +{ +} + + +/*****************************************************************************/ +BOOL CfgParser::IsTokenClosed( const ByteString &rToken ) +/*****************************************************************************/ +{ + return rToken.GetChar( rToken.Len() - 2 ) == '/'; +} + +/*****************************************************************************/ +void CfgParser::AddText( + ByteString &rText, + const ByteString &rIsoLang, + const ByteString &rResTyp +) +/*****************************************************************************/ +{ + USHORT nTextLen = 0; + while ( rText.Len() != nTextLen ) { + nTextLen = rText.Len(); + rText.SearchAndReplaceAll( "\n", " " ); + rText.SearchAndReplaceAll( "\r", " " ); + rText.SearchAndReplaceAll( "\t", " " ); + rText.SearchAndReplaceAll( " ", " " ); + } + pStackData->sResTyp = rResTyp; + WorkOnText( rText, rIsoLang ); + + pStackData->sText[ rIsoLang ] = rText; +} + + +/*****************************************************************************/ +void CfgParser::WorkOnRessourceEnd() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +int CfgParser::ExecuteAnalyzedToken( int nToken, char *pToken ) +/*****************************************************************************/ +{ + ByteString sToken( pToken ); + + if ( sToken == " " || sToken == "\t" ) + sLastWhitespace += sToken; + + ByteString sTokenName; + ByteString sTokenId; + + BOOL bOutput = TRUE; + + switch ( nToken ) { + case CFG_TOKEN_PACKAGE: + case CFG_TOKEN_COMPONENT: + case CFG_TOKEN_TEMPLATE: + case CFG_TOKEN_CONFIGNAME: + case CFG_TOKEN_OORNAME: + case CFG_TOKEN_OORVALUE: + case CFG_TAG: + case ANYTOKEN: + case CFG_TEXT_START: + { + sTokenName = sToken.GetToken( 1, '<' ).GetToken( 0, '>' ).GetToken( 0, ' ' ); + + if ( !IsTokenClosed( sToken )) { + ByteString sSearch; + switch ( nToken ) { + case CFG_TOKEN_PACKAGE: + sSearch = "package-id="; + break; + case CFG_TOKEN_COMPONENT: + sSearch = "component-id="; + break; + case CFG_TOKEN_TEMPLATE: + sSearch = "template-id="; + break; + case CFG_TOKEN_CONFIGNAME: + sSearch = "cfg:name="; + break; + case CFG_TOKEN_OORNAME: + sSearch = "oor:name="; + bLocalize = TRUE; + break; + case CFG_TOKEN_OORVALUE: + sSearch = "oor:value="; + break; + case CFG_TEXT_START: { + if ( sCurrentResTyp != sTokenName ) { + WorkOnRessourceEnd(); + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + pStackData->sText[ sCur ] = ByteString(""); + } + } + sCurrentResTyp = sTokenName; + + ByteString sTemp = sToken.Copy( sToken.Search( "xml:lang=" )); + sCurrentIsoLang = sTemp.GetToken( 1, '\"' ).GetToken( 0, '\"' ); + + if ( sCurrentIsoLang == NO_TRANSLATE_ISO ) + bLocalize = FALSE; + + pStackData->sTextTag = sToken; + + sCurrentText = ""; + } + break; + } + if ( sSearch.Len()) { + ByteString sTemp = sToken.Copy( sToken.Search( sSearch )); + sTokenId = sTemp.GetToken( 1, '\"' ).GetToken( 0, '\"' ); + } + pStackData = aStack.Push( sTokenName, sTokenId ); + + if ( sSearch == "cfg:name=" ) { + ByteString sTemp( sToken ); + sTemp.ToUpperAscii(); + bLocalize = (( sTemp.Search( "CFG:TYPE=\"STRING\"" ) != STRING_NOTFOUND ) && + ( sTemp.Search( "CFG:LOCALIZED=\"TRUE\"" ) != STRING_NOTFOUND )); + } + } + else if ( sTokenName == "label" ) { + if ( sCurrentResTyp != sTokenName ) { + WorkOnRessourceEnd(); + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + pStackData->sText[ sCur ] = ByteString(""); + } + } + sCurrentResTyp = sTokenName; + } + } + break; + case CFG_CLOSETAG: + sTokenName = sToken.GetToken( 1, '/' ).GetToken( 0, '>' ).GetToken( 0, ' ' ); + if ( aStack.GetStackData() && ( aStack.GetStackData()->GetTagType() == sTokenName )) { + if ( ! sCurrentText.Len()) + WorkOnRessourceEnd(); + aStack.Pop(); + pStackData = aStack.GetStackData(); + } + else { + ByteString sError( "Missplaced close tag: " ); + ByteString sInFile(" in file "); + sError += sToken; + sError += sInFile; + sError += sFullEntry; + Error( sError ); + exit ( 13 ); + } + break; + + case CFG_TEXTCHAR: + sCurrentText += sToken; + bOutput = FALSE; + break; + + case CFG_TOKEN_NO_TRANSLATE: + bLocalize = FALSE; + break; + } + + if ( sCurrentText.Len() && nToken != CFG_TEXTCHAR ) { + AddText( sCurrentText, sCurrentIsoLang, sCurrentResTyp ); + Output( sCurrentText ); + sCurrentText = ""; + pStackData->sEndTextTag = sToken; + } + + if ( bOutput ) + Output( sToken ); + + if ( sToken != " " && sToken != "\t" ) + sLastWhitespace = ""; + + return 1; +} + +/*****************************************************************************/ +void CfgExport::Output( const ByteString& rOutput ) +/*****************************************************************************/ +{ + // Dummy operation to suppress warnings caused by poor class design + ByteString a( rOutput ); +} + +/*****************************************************************************/ +int CfgParser::Execute( int nToken, char * pToken ) +/*****************************************************************************/ +{ + ByteString sToken( pToken ); + + switch ( nToken ) { + case CFG_TAG: + if ( sToken.Search( "package-id=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_PACKAGE, pToken ); + else if ( sToken.Search( "component-id=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_COMPONENT, pToken ); + else if ( sToken.Search( "template-id=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_TEMPLATE, pToken ); + else if ( sToken.Search( "cfg:name=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_OORNAME, pToken ); + else if ( sToken.Search( "oor:name=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_OORNAME, pToken ); + else if ( sToken.Search( "oor:value=" ) != STRING_NOTFOUND ) + return ExecuteAnalyzedToken( CFG_TOKEN_OORVALUE, pToken ); + break; + } + return ExecuteAnalyzedToken( nToken, pToken ); +} + + +/*****************************************************************************/ +void CfgParser::Error( const ByteString &rError ) +/*****************************************************************************/ +{ +// ByteString sError( rError ); +// sError.Append("Error: In file "); +// sError.Append( sActFileName ); + yyerror(( char * ) rError.GetBuffer()); +} + + +// +// class CfgOutputParser +// + +/*****************************************************************************/ +CfgOutputParser::CfgOutputParser( const ByteString &rOutputFile ) +/*****************************************************************************/ +{ + pOutputStream = + new SvFileStream( + String( rOutputFile, RTL_TEXTENCODING_ASCII_US ), + STREAM_STD_WRITE | STREAM_TRUNC + ); + pOutputStream->SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); + + if ( !pOutputStream->IsOpen()) { + ByteString sError( "ERROR: Unable to open output file: " ); + sError += rOutputFile; + Error( sError ); + delete pOutputStream; + pOutputStream = NULL; + exit( 13 ); + } +} + +/*****************************************************************************/ +CfgOutputParser::~CfgOutputParser() +/*****************************************************************************/ +{ + if ( pOutputStream ) { + pOutputStream->Close(); + delete pOutputStream; + } +} + +// +// class CfgExport +// + +/*****************************************************************************/ +CfgExport::CfgExport( + const ByteString &rOutputFile, + const ByteString &rProject, + const ByteString &rFilePath +) +/*****************************************************************************/ + : CfgOutputParser( rOutputFile ), + sPrj( rProject ), + sPath( rFilePath ) +{ + Export::InitLanguages( false ); + aLanguages = Export::GetLanguages(); +} + +/*****************************************************************************/ +CfgExport::~CfgExport() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +void CfgExport::WorkOnRessourceEnd() +/*****************************************************************************/ +{ + if ( pOutputStream && bLocalize ) { + if (( pStackData->sText[ ByteString("en-US") ].Len() + ) || + ( bForce && + ( pStackData->sText[ ByteString("de") ].Len() || + pStackData->sText[ ByteString("en-US") ].Len() ))) + { + ByteString sFallback = pStackData->sText[ ByteString("en-US") ]; + + //if ( pStackData->sText[ ByteString("en-US") ].Len()) + // sFallback = pStackData->sText[ ByteString("en-US") ]; + + ByteString sLocalId = pStackData->sIdentifier; + ByteString sGroupId; + if ( aStack.Count() == 1 ) { + sGroupId = sLocalId; + sLocalId = ""; + } + else { + sGroupId = aStack.GetAccessPath( aStack.Count() - 2 ); + } + + ByteString sTimeStamp( Export::GetTimeStamp()); + + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sText = pStackData->sText[ sCur ]; + if ( !sText.Len()) + sText = sFallback; + + Export::UnquotHTML( sText ); + + ByteString sOutput( sPrj ); sOutput += "\t"; + sOutput += sPath; + sOutput += "\t0\t"; + sOutput += pStackData->sResTyp; sOutput += "\t"; + sOutput += sGroupId; sOutput += "\t"; + sOutput += sLocalId; sOutput += "\t\t\t0\t"; + sOutput += sCur; + sOutput += "\t"; + + sOutput += sText; sOutput += "\t\t\t\t"; + sOutput += sTimeStamp; + + //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sPrj ) ) ) + pOutputStream->WriteLine( sOutput ); + } + } + } +} + +/*****************************************************************************/ +void CfgExport::WorkOnText( + ByteString &rText, + const ByteString &rIsoLang +) +/*****************************************************************************/ +{ + if( rIsoLang.Len() ) Export::UnquotHTML( rText ); +} + + +// +// class CfgMerge +// + +/*****************************************************************************/ +CfgMerge::CfgMerge( + const ByteString &rMergeSource, const ByteString &rOutputFile, + ByteString &rFilename ) +/*****************************************************************************/ + : CfgOutputParser( rOutputFile ), + pMergeDataFile( NULL ), + pResData( NULL ), + bGerman( FALSE ), + sFilename( rFilename ), + bEnglish( FALSE ) +{ + if ( rMergeSource.Len()){ + pMergeDataFile = new MergeDataFile( + rMergeSource, sInputFileName , bErrorLog, RTL_TEXTENCODING_MS_1252, true ); + if( Export::sLanguages.EqualsIgnoreCaseAscii("ALL") ){ + Export::SetLanguages( pMergeDataFile->GetLanguages() ); + aLanguages = pMergeDataFile->GetLanguages(); + } + else aLanguages = Export::GetLanguages(); + }else + aLanguages = Export::GetLanguages(); +} + +/*****************************************************************************/ +CfgMerge::~CfgMerge() +/*****************************************************************************/ +{ + delete pMergeDataFile; + delete pResData; +} + +/*****************************************************************************/ +void CfgMerge::WorkOnText( + ByteString &rText, + const ByteString& nLangIndex +) +/*****************************************************************************/ +{ + + if ( pMergeDataFile && bLocalize ) { + if ( !pResData ) { + ByteString sLocalId = pStackData->sIdentifier; + ByteString sGroupId; + if ( aStack.Count() == 1 ) { + sGroupId = sLocalId; + sLocalId = ""; + } + else { + sGroupId = aStack.GetAccessPath( aStack.Count() - 2 ); + } + + ByteString sPlatform( "" ); + + pResData = new ResData( sPlatform, sGroupId , sFilename ); + pResData->sId = sLocalId; + pResData->sResTyp = pStackData->sResTyp; + } + + //if ( nLangIndex.EqualsIgnoreCaseAscii("de") ) + // bGerman = TRUE; + if (( nLangIndex.EqualsIgnoreCaseAscii("en-US") )) + bEnglish = TRUE; + + PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrysCaseSensitive( pResData ); + if ( pEntrys ) { + ByteString sContent; + pEntrys->GetText( sContent, STRING_TYP_TEXT, nLangIndex ); + + if ( Export::isAllowed( nLangIndex ) && + ( sContent != "-" ) && ( sContent.Len())) + { +#ifdef MERGE_SOURCE_LANGUAGES + if( nLangIndex.EqualsIgnoreCaseAscii("de") || nLangIndex.EqualsIgnoreCaseAscii("en-US") ) + rText = sContent; +#endif + Export::QuotHTML( rText ); + } + } + } +} + +/*****************************************************************************/ +void CfgMerge::Output( const ByteString& rOutput ) +/*****************************************************************************/ +{ + if ( pOutputStream ) + pOutputStream->Write( rOutput.GetBuffer(), rOutput.Len()); +} + +ULONG CfgStack::Push( CfgStackData *pStackData ) +{ + Insert( pStackData, LIST_APPEND ); + return Count() - 1; +} + +/*****************************************************************************/ +void CfgMerge::WorkOnRessourceEnd() +/*****************************************************************************/ +{ + + if ( pMergeDataFile && pResData && bLocalize && (( bEnglish ) || bForce )) { + PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrysCaseSensitive( pResData ); + if ( pEntrys ) { + ByteString sCur; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sContent; + pEntrys->GetText( sContent, STRING_TYP_TEXT, sCur , TRUE ); + if ( + // (!sCur.EqualsIgnoreCaseAscii("de") ) && + ( !sCur.EqualsIgnoreCaseAscii("en-US") ) && + + ( sContent != "-" ) && ( sContent.Len())) + { + + ByteString sText = sContent; + Export::QuotHTML( sText ); + + ByteString sAdditionalLine( "\t" ); + + ByteString sTextTag = pStackData->sTextTag; + ByteString sTemp = sTextTag.Copy( sTextTag.Search( "xml:lang=" )); + + ByteString sSearch = sTemp.GetToken( 0, '\"' ); + sSearch += "\""; + sSearch += sTemp.GetToken( 1, '\"' ); + sSearch += "\""; + + ByteString sReplace = sTemp.GetToken( 0, '\"' ); + sReplace += "\""; + sReplace += sCur; + sReplace += "\""; + + sTextTag.SearchAndReplace( sSearch, sReplace ); + + sAdditionalLine += sTextTag; + sAdditionalLine += sText; + sAdditionalLine += pStackData->sEndTextTag; + + sAdditionalLine += "\n"; + sAdditionalLine += sLastWhitespace; + + Output( sAdditionalLine ); + } + } + } + } + delete pResData; + pResData = NULL; + bGerman = FALSE; + bEnglish = FALSE; +} diff --git a/l10ntools/source/directory.cxx b/l10ntools/source/directory.cxx new file mode 100644 index 000000000000..21d0a5878d66 --- /dev/null +++ b/l10ntools/source/directory.cxx @@ -0,0 +1,276 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: directory.cxx,v $ + * $Revision: 1.6 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include "tools/string.hxx" +#include +#include +#include + +namespace transex +{ + +Directory::Directory( const rtl::OUString sFullpath ) : bSkipLinks( false ) +{ + sFullName = sFullpath; +} + +Directory::Directory( const rtl::OUString sFullPath , const rtl::OUString sEntry ) : bSkipLinks( false ) +{ + sFullName = sFullPath; + sDirectoryName = sEntry; +} + + +Directory::Directory( const ByteString sFullPath ) : bSkipLinks( false ) +{ + sDirectoryName = rtl::OUString( sFullPath.GetBuffer() , RTL_TEXTENCODING_UTF8 , sFullPath.Len() ); +} + +bool Directory::lessDir ( const Directory& rKey1, const Directory& rKey2 ) +{ + rtl::OUString sName1( ( static_cast< Directory >( rKey1 ) ).getDirectoryName() ); + rtl::OUString sName2( ( static_cast< Directory >( rKey2 ) ).getDirectoryName() ); + + return sName1.compareTo( sName2 ) < 0 ; +} + + +void Directory::dump() +{ + + for( std::vector< transex::File >::iterator iter = aFileVec.begin() ; iter != aFileVec.end() ; ++iter ) + { + std::cout << "FILE " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n"; + } + + for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() ; ++iter ) + { + std::cout << "DIR " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n"; + } + +} + +void Directory::scanSubDir( int nLevels ) +{ + readDirectory( sFullName ); + dump(); + if( nLevels > 0 ) { + for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() || nLevels > 0 ; ++iter , nLevels-- ) + { + ( *iter ).scanSubDir(); + } + } +} + +void Directory::setSkipLinks( bool is_skipped ) +{ + bSkipLinks = is_skipped; +} + +void Directory::readDirectory() +{ + readDirectory( sFullName ); +} + +#ifdef WNT +#include +#include +#include + +void Directory::readDirectory ( const rtl::OUString& sFullpath ) +{ + BOOL fFinished; + HANDLE hList; + TCHAR szDir[MAX_PATH+1]; + TCHAR szSubDir[MAX_PATH+1]; + WIN32_FIND_DATA FileData; + + rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ); + const char *dirname = sFullpathext.getStr(); + + // Get the proper directory path + sprintf(szDir, "%s\\*", dirname); + + // Get the first file + hList = FindFirstFile(szDir, &FileData); + if (hList == INVALID_HANDLE_VALUE) + { + //FindClose(hList); + //printf("No files found %s\n", szDir ); return; + } + else + { + fFinished = FALSE; + while (!fFinished) + { + + sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName); + rtl::OString myfile( FileData.cFileName ); + rtl::OString mydir( szSubDir ); + + if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if ( (strcmp(FileData.cFileName, ".") != 0 ) && + (strcmp(FileData.cFileName, "..") != 0 ) ) + { + //sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName); + transex::Directory aDir( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ), + rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) ); + aDirVec.push_back( aDir ); + } + } + else + { + transex::File aFile( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ), + rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) ); + aFileVec.push_back( aFile ); + } + if (!FindNextFile(hList, &FileData)) + { + if (GetLastError() == ERROR_NO_MORE_FILES) + { + fFinished = TRUE; + } + } + } + } + + FindClose(hList); + + ::std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile ); + ::std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir ); +} + +#else + +class dirholder +{ +private: + DIR *mpDir; +public: + dirholder(DIR *pDir) : mpDir(pDir) {} + int close() { int nRet = mpDir ? closedir(mpDir) : 0; mpDir = NULL; return nRet; } + ~dirholder() { close(); } +}; + +void Directory::readDirectory( const rtl::OUString& sFullpath ) +{ + struct stat statbuf; + struct stat statbuf2; + struct dirent *dirp; + DIR *dir; + //int ret; + //char *ptr; + + if( sFullpath.getLength() < 1 ) return; + + rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ).getStr(); + //printf("%s\n",sFullpathext.getStr()); + const char* path = sFullpathext.getStr(); + + // stat + if( stat( path , &statbuf ) < 0 ){ printf("warning: Can not stat %s" , path ); return; }// error } + + if( S_ISDIR(statbuf.st_mode ) == 0 ) { return; }// error } return; // not dir + + if( (dir = opendir( path ) ) == NULL ) {printf("readerror 2 in %s \n",path); return; } // error } return; // error + dirholder aHolder(dir); + + sFullpathext += rtl::OString( "/" ); + + const rtl::OString sDot ( "." ) ; + const rtl::OString sDDot( ".." ); + + if ( chdir( path ) == -1 ) { printf("chdir error in %s \n",path); return; } // error + + while( ( dirp = readdir( dir ) ) != NULL ) + { + rtl::OString sEntryName( dirp->d_name ); + + if( sEntryName.equals( sDot ) || sEntryName.equals( sDDot ) ) + continue; + + // add dir entry + rtl::OString sEntity = sFullpathext; + sEntity += sEntryName; + + // stat new entry + if( lstat( sEntity.getStr() , &statbuf2 ) < 0 ) + { + printf("error on entry %s\n" , sEntity.getStr() ) ; // error + continue; + } + + // add file / dir to vector + switch( statbuf2.st_mode & S_IFMT ) + { + case S_IFREG: + { + rtl::OString sFile = sFullpathext; + sFile += sEntryName ; + transex::File aFile( rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) , + rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() ) + ); + + aFileVec.push_back( aFile ) ; + break; + } + case S_IFLNK: + { + if( bSkipLinks ) break; + } + case S_IFDIR: + { + rtl::OString sDir = sFullpathext; + sDir += sEntryName ; + + transex::Directory aDir( + rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) , + rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() ) + ) ; + aDirVec.push_back( aDir ) ; + break; + } + } + } + if ( chdir( ".." ) == -1 ) { printf("chdir error in .. \n"); return; } // error + if( aHolder.close() < 0 ) return ; // error + + std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile ); + std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir ); + +} + +#endif +} diff --git a/l10ntools/source/export.cxx b/l10ntools/source/export.cxx new file mode 100644 index 000000000000..72826d7bf1f2 --- /dev/null +++ b/l10ntools/source/export.cxx @@ -0,0 +1,2660 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: export.cxx,v $ + * $Revision: 1.57 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +#include +#include "export.hxx" +#include "tokens.h" +#include "utf8conv.hxx" +#include + +extern "C" { int yyerror( char * ); } +extern "C" { int YYWarning( char * ); } + +Export *pExport = 0L; + +// defines to parse command line +#define STATE_NON 0x0001 +#define STATE_INPUT 0x0002 +#define STATE_OUTPUT 0x0003 +#define STATE_PRJ 0x0004 +#define STATE_ROOT 0x0005 +#define STATE_MERGESRC 0x0006 +#define STATE_ERRORLOG 0x0007 +#define STATE_BREAKHELP 0x0008 +#define STATE_UNMERGE 0x0009 +#define STATE_UTF8 0x000A +#define STATE_LANGUAGES 0X000B + +// set of global variables +DECLARE_LIST( FileList, ByteString * ) +FileList aInputFileList; +BOOL bEnableExport; +BOOL bMergeMode; +BOOL bErrorLog; +BOOL bBreakWhenHelpText; +BOOL bUnmerge; +BOOL bUTF8; +bool bQuiet; +ByteString sPrj; +ByteString sPrjRoot; +ByteString sActFileName; +ByteString sOutputFile; +ByteString sMergeSrc; +ByteString sTempFile; +ByteString sFile; +MergeDataFile *pMergeDataFile; +FILE *pTempFile; + + +ByteString sStrBuffer; +bool bMarcro = false; + +extern "C" { +// the whole interface to lexer is in this extern "C" section + + +/*****************************************************************************/ +extern char *GetOutputFile( int argc, char* argv[]) +/*****************************************************************************/ +{ + bEnableExport = FALSE; + bMergeMode = FALSE; + bErrorLog = TRUE; + bBreakWhenHelpText = FALSE; + bUnmerge = FALSE; + bUTF8 = TRUE; + sPrj = ""; + sPrjRoot = ""; + sActFileName = ""; + Export::sLanguages = ""; + Export::sForcedLanguages = ""; + sTempFile = ""; + pTempFile = NULL; + bQuiet = false; + USHORT nState = STATE_NON; + BOOL bInput = FALSE; + + // parse command line + for( int i = 1; i < argc; i++ ) { + ByteString sSwitch( argv[ i ] ); + + if (sSwitch == "-i" || sSwitch == "-I" ) { + nState = STATE_INPUT; // next tokens specifies source files + } + else if (sSwitch == "-o" || sSwitch == "-O" ) { + nState = STATE_OUTPUT; // next token specifies the dest file + } + else if (sSwitch == "-p" || sSwitch == "-P" ) { + nState = STATE_PRJ; // next token specifies the cur. project + } + else if (sSwitch == "-qq" || sSwitch == "-QQ" ) { + bQuiet = true; + } + + else if (sSwitch == "-r" || sSwitch == "-R" ) { + nState = STATE_ROOT; // next token specifies path to project root + } + else if (sSwitch == "-m" || sSwitch == "-M" ) { + nState = STATE_MERGESRC; // next token specifies the merge database + } + else if (sSwitch == "-e" || sSwitch == "-E" ) { + nState = STATE_ERRORLOG; + bErrorLog = FALSE; + } + else if (sSwitch == "-b" || sSwitch == "-B" ) { + nState = STATE_BREAKHELP; + bBreakWhenHelpText = TRUE; + } + else if (sSwitch == "-u" || sSwitch == "-U" ) { + nState = STATE_UNMERGE; + bUnmerge = TRUE; + bMergeMode = TRUE; + } + else if ( sSwitch.ToUpperAscii() == "-UTF8" ) { + nState = STATE_UTF8; + bUTF8 = TRUE; + } + else if ( sSwitch.ToUpperAscii() == "-NOUTF8" ) { + nState = STATE_UTF8; + bUTF8 = FALSE; + } + else if ( sSwitch == "-l" || sSwitch == "-L" ) { + nState = STATE_LANGUAGES; + } + else { + switch ( nState ) { + case STATE_NON: { + return NULL; // no valid command line + } + case STATE_INPUT: { + aInputFileList.Insert( new ByteString( argv[ i ]), LIST_APPEND ); + bInput = TRUE; // min. one source file found + } + break; + case STATE_OUTPUT: { + sOutputFile = ByteString( argv[ i ]); // the dest. file + } + break; + case STATE_PRJ: { + sPrj = ByteString( argv[ i ]); + } + break; + case STATE_ROOT: { + sPrjRoot = ByteString( argv[ i ]); // path to project root + } + break; + case STATE_MERGESRC: { + sMergeSrc = ByteString( argv[ i ]); + bMergeMode = TRUE; // activate merge mode, cause merge database found + } + break; + case STATE_LANGUAGES: { + Export::sLanguages = ByteString( argv[ i ]); + } + break; + } + } + } + if( bUnmerge ) sMergeSrc = ByteString(); + if ( bInput ) { + // command line is valid + bEnableExport = TRUE; + char *pReturn = new char[ sOutputFile.Len() + 1 ]; + strcpy( pReturn, sOutputFile.GetBuffer()); // #100211# - checked + return pReturn; + } + + // command line is not valid + return NULL; +} +/*****************************************************************************/ +int isQuiet(){ +/*****************************************************************************/ + if( bQuiet ) return 1; + else return 0; +} +/*****************************************************************************/ +int InitExport( char *pOutput , char* pFilename ) +/*****************************************************************************/ +{ + // instanciate Export + ByteString sOutput( pOutput ); + ByteString sFilename( pFilename ); + + if ( bMergeMode && !bUnmerge ) { + // merge mode enabled, so read database + pExport = new Export(sOutput, bEnableExport, sPrj, sPrjRoot, sMergeSrc , sFilename ); + } + else + // no merge mode, only export + pExport = new Export( sOutput, bEnableExport, sPrj, sPrjRoot , sFilename ); + return 1; +} + +/*****************************************************************************/ +int EndExport() +/*****************************************************************************/ +{ + delete pExport; + return 1; +} + +extern const char* getFilename() +{ + return (*(aInputFileList.GetObject( 0 ))).GetBuffer(); +} +/*****************************************************************************/ +extern FILE *GetNextFile() +/*****************************************************************************/ +{ + // look for next valid filename in input file list + if ( sTempFile.Len()) { + fclose( pTempFile ); + String sTemp( sTempFile, RTL_TEXTENCODING_ASCII_US ); + DirEntry aTemp( sTemp ); + aTemp.Kill(); + } + + while ( aInputFileList.Count()) { + ByteString sFileName( *(aInputFileList.GetObject( 0 ))); + + ByteString sOrigFile( sFileName ); + + sFileName = Export::GetNativeFile( sFileName ); + delete aInputFileList.GetObject(( ULONG ) 0 ); + aInputFileList.Remove(( ULONG ) 0 ); + + if ( sFileName == "" ) { + fprintf( stderr, "ERROR: Could not precompile File %s\n", + sOrigFile.GetBuffer()); + return GetNextFile(); + } + + sTempFile = sFileName; + Export::RemoveUTF8ByteOrderMarkerFromFile( sFileName ); + + // able to open file? + FILE *pFile = fopen( sFileName.GetBuffer(), "r" ); + if ( !pFile ) + fprintf( stderr, "Error: Could not open File %s\n", + sFileName.GetBuffer()); + else { + pTempFile = pFile; + + // this is a valid file which can be opened, so + // create path to project root + DirEntry aEntry( String( sOrigFile, RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + ByteString sFullEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( sPrjRoot ); + ByteString sPrjEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + // create file name, beginnig with project root + // (e.g.: source\ui\src\menue.src) + sActFileName = sFullEntry.Copy( sPrjEntry.Len() + 1 ); + + if( !bQuiet ) fprintf( stdout, "\nProcessing File %s ...\n", sOrigFile.GetBuffer()); + + sActFileName.SearchAndReplaceAll( "/", "\\" ); + sFile = sActFileName; + + if ( pExport ) { + // create instance of class export + pExport->Init(); + } + // return the valid file handle + return pFile; + } + } + // this means the file could not be opened + return NULL; +} + +int Parse( int nTyp, const char *pTokenText ){ + pExport->Execute( nTyp , pTokenText ); + return 1; +} +void Close(){ + pExport->pParseQueue->Close(); +} +/*****************************************************************************/ +int WorkOnTokenSet( int nTyp, char *pTokenText ) +/*****************************************************************************/ +{ + + pExport->pParseQueue->Push( QueueEntry( nTyp , ByteString( pTokenText ) ) ); + return 1; +} + +} // extern + +extern "C" { +/*****************************************************************************/ +int SetError() +/*****************************************************************************/ +{ + // set error at global instance of class Export + pExport->SetError(); + return 1; +} +} + +extern "C" { +/*****************************************************************************/ +int GetError() +/*****************************************************************************/ +{ + // get error at global instance of class Export + if ( pExport->GetError()) + return 1; + return FALSE; +} +} + +// +// class ResData +// + +void ResData::Dump(){ + printf("**************\nResData\n"); + printf("sPForm = %s , sResTyp = %s , sId = %s , sGId = %s , sHelpId = %s\n",sPForm.GetBuffer() + ,sResTyp.GetBuffer(),sId.GetBuffer(),sGId.GetBuffer(),sHelpId.GetBuffer()); + + ByteString a("*pStringList"); + ByteString b("*pUIEntries"); + ByteString c("*pFilterList"); + ByteString d("*pItemList"); + ByteString e("*pPairedList"); + ByteString f("sText"); + + Export::DumpMap( f , sText ); + + if( pStringList ) Export::DumpExportList( a , *pStringList ); + if( pUIEntries ) Export::DumpExportList( b , *pUIEntries ); + if( pFilterList ) Export::DumpExportList( c , *pFilterList ); + if( pItemList ) Export::DumpExportList( d , *pItemList ); + if( pPairedList ) Export::DumpExportList( e , *pPairedList ); + printf("\n"); +} + +void ResData::addFallbackData( ByteString& sId_in , const ByteString& sText_in ){ + //printf(" ResData::addFallbackData ( sId = %s , sText = %s )\n", sId_in.GetBuffer() , sText_in.GetBuffer() ); + aFallbackData[ sId_in ] = sText_in; +} +bool ResData::getFallbackData( ByteString& sId_in , ByteString& sText_inout ){ + sText_inout = aFallbackData[ sId_in ]; + //printf("ResData::getFallbackData( sId = %s , return sText = %s \n" , sId_in.GetBuffer(), sText_inout.GetBuffer()); + return sText_inout.Len() > 0; +} + +void ResData::addMergedLanguage( ByteString& sLang ){ + aMergedLanguages[ sLang ]=ByteString("1"); +} +bool ResData::isMerged( ByteString& sLang ){ + return aMergedLanguages[ sLang ].Equals("1"); +} + +/*****************************************************************************/ +BOOL ResData::SetId( const ByteString &rId, USHORT nLevel ) +/*****************************************************************************/ +{ + if ( nLevel > nIdLevel ) + { + nIdLevel = nLevel; + sId = rId; + + if ( bChild && bChildWithText ) { + ByteString sError( "ResId after child definition" ); + yyerror( sError.GetBufferAccess()); + sError.ReleaseBufferAccess(); + SetError(); + } + + if ( sId.Len() > 255 ) { + ByteString sWarning( "LocalId > 255 chars, truncating..." ); + YYWarning( sWarning.GetBufferAccess()); + sWarning.ReleaseBufferAccess(); + sId.Erase( 255 ); + sId.EraseTrailingChars( ' ' ); + sId.EraseTrailingChars( '\t' ); + } + + return TRUE; + } + + return FALSE; +} + +// +// class Export +// + +/*****************************************************************************/ +Export::Export( const ByteString &rOutput, BOOL bWrite, + const ByteString &rPrj, const ByteString &rPrjRoot , const ByteString& rFile ) +/*****************************************************************************/ + : + pWordTransformer( NULL ), + aCharSet( RTL_TEXTENCODING_MS_1252 ), + bDefine( FALSE ), + bNextMustBeDefineEOL( FALSE ), + nLevel( 0 ), + nList( LIST_NON ), + nListIndex( 0 ), + nListLevel( 0 ), + bSkipFile( false ), + sProject( sPrj ), + sRoot( sPrjRoot ), + bEnableExport( bWrite ), + bMergeMode( bUnmerge ), + bError( FALSE ), + bReadOver( FALSE ), + bDontWriteOutput( FALSE ), + sFilename( rFile ) +{ + pParseQueue = new ParserQueue( *this ); + (void) rPrj; + (void) rPrjRoot; + (void) rFile; + + if( !isInitialized ) InitLanguages(); + // used when export is enabled + + // open output stream + if ( bEnableExport ) { + aOutput.Open( String( rOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); + if( !aOutput.IsOpen() ) { + printf("ERROR : Can't open file %s\n",rOutput.GetBuffer()); + exit ( -1 ); + } + aOutput.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); + + aOutput.SetLineDelimiter( LINEEND_CRLF ); + } +} + +/*****************************************************************************/ +Export::Export( const ByteString &rOutput, BOOL bWrite, + const ByteString &rPrj, const ByteString &rPrjRoot, + const ByteString &rMergeSource , const ByteString& rFile ) +/*****************************************************************************/ + : + pWordTransformer( NULL ), + aCharSet( RTL_TEXTENCODING_MS_1252 ), + bDefine( FALSE ), + bNextMustBeDefineEOL( FALSE ), + nLevel( 0 ), + nList( LIST_NON ), + nListIndex( 0 ), + nListLevel( 0 ), + bSkipFile( false ), + sProject( sPrj ), + sRoot( sPrjRoot ), + bEnableExport( bWrite ), + bMergeMode( TRUE ), + sMergeSrc( rMergeSource ), + bError( FALSE ), + bReadOver( FALSE ), + bDontWriteOutput( FALSE ), + sFilename( rFile ) +{ + (void) rPrj; + (void) rPrjRoot; + (void) rFile; + pParseQueue = new ParserQueue( *this ); + if( !isInitialized ) InitLanguages( bMergeMode ); + // used when merge is enabled + + // open output stream + if ( bEnableExport ) { + aOutput.Open( String( rOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); + aOutput.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); + aOutput.SetLineDelimiter( LINEEND_CRLF ); + } + +} + +/*****************************************************************************/ +void Export::Init() +/*****************************************************************************/ +{ + // resets the internal status, used before parseing another file + sActPForm = ""; + bDefine = FALSE; + bNextMustBeDefineEOL = FALSE; + nLevel = 0; + nList = LIST_NON; + nListLang = ByteString( String::CreateFromAscii(""),RTL_TEXTENCODING_ASCII_US ); + nListIndex = 0; + while ( aResStack.Count()) { + delete aResStack.GetObject(( ULONG ) 0 ); + aResStack.Remove(( ULONG ) 0 ); + } +} + +/*****************************************************************************/ +Export::~Export() +/*****************************************************************************/ +{ + if( pParseQueue ) + delete pParseQueue; + // close output stream + if ( bEnableExport ) + aOutput.Close(); + while ( aResStack.Count()) { + delete aResStack.GetObject(( ULONG ) 0 ); + aResStack.Remove(( ULONG ) 0 ); + } + + if ( bMergeMode && !bUnmerge ) { + if ( !pMergeDataFile ) + pMergeDataFile = new MergeDataFile( sMergeSrc,sFile , bErrorLog, aCharSet);//, bUTF8 ); + + //pMergeDataFile->WriteErrorLog( sActFileName ); + delete pMergeDataFile; + } +} + +/*****************************************************************************/ +int Export::Execute( int nToken, const char * pToken ) +/*****************************************************************************/ +{ + + ByteString sToken( pToken ); + ByteString sOrig( sToken ); +/* printf("+---------------\n"); + printf("sToken = %s\n",sToken.GetBuffer()); + printf("nToken = %d\n",nToken); + printf("+---------------\n"); */ + BOOL bWriteToMerged = bMergeMode; + + if ( nToken == CONDITION ) { + ByteString sTestToken( pToken ); + sTestToken.EraseAllChars( '\t' ); + sTestToken.EraseAllChars( ' ' ); + if (( !bReadOver ) && ( sTestToken.Search( "#ifndef__RSC_PARSER" ) == 0 )) + bReadOver = TRUE; + else if (( bReadOver ) && ( sTestToken.Search( "#endif" ) == 0 )) + bReadOver = FALSE; + } + if ((( nToken < FILTER_LEVEL ) || ( bReadOver )) && + (!(( bNextMustBeDefineEOL ) && ( sOrig == "\n" )))) { + // this tokens are not mandatory for parsing, so ignore them ... + if ( bMergeMode ) + WriteToMerged( sOrig , false ); // ... ore whrite them directly to dest. + return 0; + } + + ResData *pResData = NULL; + if ( nLevel ) { + // res. exists at cur. level + pResData = aResStack.GetObject( nLevel-1 ); + } + else if (( nToken != RESSOURCE ) && + ( nToken != RESSOURCEEXPR ) && + ( nToken != SMALRESSOURCE ) && + ( nToken != LEVELUP ) && + ( nToken != NORMDEFINE ) && + ( nToken != RSCDEFINE ) && + ( nToken != CONDITION ) && + ( nToken != PRAGMA )) + { + // no res. exists at cur. level so return + if ( bMergeMode ) + WriteToMerged( sOrig , false ); + return 0; + } + // #define NO_LOCALIZE_EXPORT + if( bSkipFile ){ + if ( bMergeMode ) { + WriteToMerged( sOrig , false ); + } + return 1; + } + + + if ( bDefine ) { + if (( nToken != EMPTYLINE ) && ( nToken != LEVELDOWN ) && ( nToken != LEVELUP )) { + // cur. res. defined in macro + if ( bNextMustBeDefineEOL ) { + if ( nToken != RSCDEFINELEND ) { + // end of macro found, so destroy res. + bDefine = FALSE; + if ( bMergeMode ) { + /*if ( bDontWriteOutput && bUnmerge ) { + bDontWriteOutput = FALSE; + bNextMustBeDefineEOL = FALSE; + bDefine = TRUE; + }*/ + MergeRest( pResData ); + } + bNextMustBeDefineEOL = FALSE; + Execute( LEVELDOWN, "" ); + } + else { + // next line also in macro definition + bNextMustBeDefineEOL = FALSE; + if ( bMergeMode ) + WriteToMerged( sOrig , false ); + return 1; + } + } + else if (( nToken != LISTASSIGNMENT ) && ( nToken != UIENTRIES )){ + // cur. line has macro line end + ByteString sTmpLine( sToken ); + sTmpLine.EraseAllChars( '\t' ); sTmpLine.EraseAllChars( ' ' ); + #if 0 + // impossible, unsigned is never negative + if( sTmpLine.Len() < 0 ){ + if ( sTmpLine.GetChar(( USHORT )( sTmpLine.Len() - 1 )) != '\\' ) + bNextMustBeDefineEOL = TRUE; + } + #endif + } + } + } + + BOOL bExecuteDown = FALSE; + if ( nToken != LEVELDOWN ) { + USHORT nOpen = 0; + USHORT nClose = 0; + BOOL bReadOver1 = FALSE; + USHORT i = 0; + for ( i = 0; i < sToken.Len(); i++ ) { + if ( sToken.GetChar( i ) == '\"' ) + bReadOver1 = !bReadOver1; + if ( !bReadOver1 && ( sToken.GetChar( i ) == '{' )) + nOpen++; + } + + bReadOver1 = FALSE; + for ( i = 0; i < sToken.Len(); i++ ) { + if ( sToken.GetChar( i ) == '\"' ) + bReadOver1 = !bReadOver1; + if ( !bReadOver1 && ( sToken.GetChar( i ) == '}' )) + nClose++; + } + + if ( nOpen < nClose ) + bExecuteDown = TRUE; + } + switch ( nToken ) { + + case NORMDEFINE: + //printf("sToken = '%s'",sToken.GetBuffer()); + while( sToken.SearchAndReplace( "\r", " " ) != STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; + if( sToken.EqualsIgnoreCaseAscii( "#define NO_LOCALIZE_EXPORT" ) ){ + bSkipFile = true; + return 0; + } + if ( bMergeMode ) + WriteToMerged( sOrig , false ); + + return 0; + + + case RSCDEFINE: + bDefine = TRUE; // res. defined in macro + + case RESSOURCE: + case RESSOURCEEXPR: { + bDontWriteOutput = FALSE; + if ( nToken != RSCDEFINE ) + bNextMustBeDefineEOL = FALSE; + // this is the beginning of a new res. + nLevel++; + if ( nLevel > 1 ) { + aResStack.GetObject( nLevel - 2 )->bChild = TRUE; + } + + // create new instance for this res. and fill mandatory fields + + pResData = new ResData( sActPForm, FullId() , sFilename ); + aResStack.Insert( pResData, LIST_APPEND ); + ByteString sBackup( sToken ); + sToken.EraseAllChars( '\n' ); + sToken.EraseAllChars( '\r' ); + sToken.EraseAllChars( '{' ); + while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + sToken.EraseTrailingChars( ' ' ); + ByteString sT = sToken.GetToken( 0, ' ' ); + pResData->sResTyp = sT.ToLowerAscii(); + ByteString sId( sToken.Copy( pResData->sResTyp.Len() + 1 )); + ByteString sCondition; + if ( sId.Search( "#" ) != STRING_NOTFOUND ) { + // between ResTyp, Id and paranthes is a precomp. condition + sCondition = "#"; + sCondition += sId.GetToken( 1, '#' ); + sId = sId.GetToken( 0, '#' ); + } + sId = sId.GetToken( 0, '/' ); + CleanValue( sId ); + sId = sId.EraseAllChars( '\t' ); + pResData->SetId( sId, ID_LEVEL_IDENTIFIER ); + if ( sCondition.Len()) { + ByteString sEmpty( "" ); + Execute( CONDITION, sEmpty.GetBufferAccess()); // execute the + // precomp. + // condition + sEmpty.ReleaseBufferAccess(); + } + } + break; + case SMALRESSOURCE: { + bDontWriteOutput = FALSE; + // this is the beginning of a new res. + bNextMustBeDefineEOL = FALSE; + nLevel++; + if ( nLevel > 1 ) { + aResStack.GetObject( nLevel - 2 )->bChild = TRUE; + } + + // create new instance for this res. and fill mandatory fields + + pResData = new ResData( sActPForm, FullId() , sFilename ); + aResStack.Insert( pResData, LIST_APPEND ); + sToken.EraseAllChars( '\n' ); + sToken.EraseAllChars( '\r' ); + sToken.EraseAllChars( '{' ); + sToken.EraseAllChars( '\t' ); + sToken.EraseAllChars( ' ' ); + sToken.EraseAllChars( '\\' ); + pResData->sResTyp = sToken.ToLowerAscii(); + } + break; + case LEVELUP: { + // push + if ( nList ) + nListLevel++; + if ( nList ) + break; + + bDontWriteOutput = FALSE; + ByteString sLowerTyp; + if ( pResData ) + sLowerTyp = "unknown"; + nLevel++; + if ( nLevel > 1 ) { + aResStack.GetObject( nLevel - 2 )->bChild = TRUE; + } + + ResData *pNewData = new ResData( sActPForm, FullId() , sFilename ); + pNewData->sResTyp = sLowerTyp; + aResStack.Insert( pNewData, LIST_APPEND ); + } + break; + case LEVELDOWN: { + // pop + if ( !nList ) { + bDontWriteOutput = FALSE; + if ( nLevel ) { + if ( bDefine && (nLevel == 1 )) { + bDefine = FALSE; + bNextMustBeDefineEOL = FALSE; + } + WriteData( pResData ); + delete aResStack.GetObject( nLevel - 1 ); + aResStack.Remove( nLevel - 1 ); + nLevel--; + } + } + else { + if ( bDefine ) + bNextMustBeDefineEOL = TRUE; + if ( !nListLevel ) { + if ( bMergeMode ) + MergeRest( pResData, MERGE_MODE_LIST ); + nList = LIST_NON; + } + else + nListLevel--; + } + } + break; + case ASSIGNMENT: { + bDontWriteOutput = FALSE; + // interpret different types of assignement + ByteString sKey = sToken.GetToken( 0, '=' ); + sKey.EraseAllChars( ' ' ); + sKey.EraseAllChars( '\t' ); + ByteString sValue = sToken.GetToken( 1, '=' ); + CleanValue( sValue ); + if ( sKey.ToUpperAscii() == "IDENTIFIER" ) { + ByteString sId( sValue.EraseAllChars( '\t' )); + pResData->SetId( sId.EraseAllChars( ' ' ), ID_LEVEL_IDENTIFIER ); + } + else if ( sKey == "HELPID" ) { + pResData->sHelpId = sValue; + } + else if ( sKey == "STRINGLIST" ) { + //if ( bUnmerge ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + //} + + pResData->bList = TRUE; + nList = LIST_STRING; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + else if ( sKey == "FILTERLIST" ) { + //if ( bUnmerge ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + //} + pResData->bList = TRUE; + nList = LIST_FILTER; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + else if ( sKey == "UIENTRIES" ) { + //if ( bUnmerge ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" ));} + pResData->bList = TRUE; + nList = LIST_UIENTRIES; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + if (( sToken.Search( "{" ) != STRING_NOTFOUND ) && + ( sToken.GetTokenCount( '{' ) > sToken.GetTokenCount( '}' ))) + { + //WorkOnTokenSet( LEVELUP, pTkn ); + Parse( LEVELUP, "" ); + } + //if ( bUnmerge && ( nListLang.EqualsIgnoreCaseAscii("de") || nListLang.EqualsIgnoreCaseAscii("en-US") ) && ListExists( pResData, nList )) + // bDontWriteOutput = TRUE; + } + break; + case UIENTRIES: + case LISTASSIGNMENT: { + bDontWriteOutput = FALSE; + ByteString sTmpToken( sToken); + sTmpToken.EraseAllChars(' '); + USHORT nPos = 0; + //nPos = sTmpToken.ToLowerAscii().Search("[de]="); + nPos = sTmpToken.ToLowerAscii().Search("[en-us]="); + if( nPos != STRING_NOTFOUND ) { + //if ( bUnmerge ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + //} + ByteString sKey = sTmpToken.Copy( 0 , nPos ); + sKey.EraseAllChars( ' ' ); + sKey.EraseAllChars( '\t' ); + ByteString sValue = sToken.GetToken( 1, '=' ); + CleanValue( sValue ); + if ( sKey.ToUpperAscii() == "STRINGLIST" ) { + pResData->bList = TRUE; + nList = LIST_STRING; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + else if ( sKey == "FILTERLIST" ) { + pResData->bList = TRUE; + nList = LIST_FILTER; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + // PairedList + else if ( sKey == "PAIREDLIST" ) { + pResData->bList = TRUE; + nList = LIST_PAIRED; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + + else if ( sKey == "ITEMLIST" ) { + pResData->bList = TRUE; + nList = LIST_ITEM; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + else if ( sKey == "UIENTRIES" ) { + pResData->bList = TRUE; + nList = LIST_UIENTRIES; + //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); + nListLang = SOURCE_LANGUAGE; + nListIndex = 0; + nListLevel = 0; + } + /*if ( bUnmerge && ( nListLang.EqualsIgnoreCaseAscii( "de" ) + || nListLang.EqualsIgnoreCaseAscii("en-US" ) ) + && ListExists( pResData, nList )) + bDontWriteOutput = TRUE;*/ + } + else { + // new res. is a String- or FilterList + ByteString sKey = sToken.GetToken( 0, '[' ); + sKey.EraseAllChars( ' ' ); + sKey.EraseAllChars( '\t' ); + if ( sKey.ToUpperAscii() == "STRINGLIST" ) + nList = LIST_STRING; + else if ( sKey == "FILTERLIST" ) + nList = LIST_FILTER; + else if ( sKey == "PAIREDLIST" ) + nList = LIST_PAIRED; // abcd + else if ( sKey == "ITEMLIST" ) + nList = LIST_ITEM; + else if ( sKey == "UIENTRIES" ) + nList = LIST_UIENTRIES; + if ( nList ) { + ByteString sLang=sToken.GetToken( 1, '[' ).GetToken( 0, ']' ); + CleanValue( sLang ); + nListLang = sLang; + /*if (( bUnmerge ) && ( !nListLang.EqualsIgnoreCaseAscii("de")) && ( !nListLang.EqualsIgnoreCaseAscii("en-US"))) + bDontWriteOutput = TRUE;*/ + nListIndex = 0; + nListLevel = 0; + /*if ( bUnmerge && nListLang.EqualsIgnoreCaseAscii("de") && ListExists( pResData, nList ) ) + bDontWriteOutput = TRUE;*/ + } + } + } + break; + case TEXT: + case _LISTTEXT: + case LISTTEXT: { + // this is an entry for a String- or FilterList + if ( nList ) { + SetChildWithText(); + ByteString sEntry( sToken.GetToken( 1, '\"' )); + if ( sToken.GetTokenCount( '\"' ) > 3 ) + sEntry += "\""; + if ( sEntry == "\\\"" ) + sEntry = "\""; + //sEntry = sEntry.Convert( aCharSet, RTL_TEXTENCODING_MS_1252 ); + //sEntry = sEntry.Convert( RTL_TEXTENCODING_MS_1252, RTL_TEXTENCODING_UTF8 ); + InsertListEntry( sEntry, sOrig ); + if ( bMergeMode && ( sEntry != "\"" )) { + PrepareTextToMerge( sOrig, nList, nListLang, pResData ); + } + } + } + break; + case LONGTEXTLINE: + case TEXTLINE: + bDontWriteOutput = FALSE; + if ( nLevel ) { + CutComment( sToken ); + + // this is a text line!!! + ByteString sKey = sToken.GetToken( 0, '=' ).GetToken( 0, '[' ); + sKey.EraseAllChars( ' ' ); + sKey.EraseAllChars( '\t' ); + ByteString sText( GetText( sToken, nToken )); + if ( !bMergeMode ) + sText = sText.Convert( aCharSet, RTL_TEXTENCODING_MS_1252 ); + ByteString sLang; + if ( sToken.GetToken( 0, '=' ).Search( "[" ) != STRING_NOTFOUND ) { + sLang = sToken.GetToken( 0, '=' ).GetToken( 1, '[' ).GetToken( 0, ']' ); + CleanValue( sLang ); + } + ByteString nLangIndex = sLang; + ByteString sOrigKey = sKey; + if ( sText.Len() && sLang.Len() ) { + if (( sKey.ToUpperAscii() == "TEXT" ) || + ( sKey == "MESSAGE" ) || + ( sKey == "CUSTOMUNITTEXT" ) || + ( sKey == "SLOTNAME" ) || + ( sKey == "UINAME" )) + { + //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ) + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + + SetChildWithText(); + //if ( nLangIndex.EqualsIgnoreCaseAscii("en-US") ) + if ( Export::isSourceLanguage( nLangIndex ) ) + pResData->SetId( sText, ID_LEVEL_TEXT ); + + pResData->bText = TRUE; + pResData->sTextTyp = sOrigKey; + if ( bMergeMode ) { + PrepareTextToMerge( sOrig, STRING_TYP_TEXT, nLangIndex, pResData ); + //if ( bUnmerge ) + // pResData->sText[ nLangIndex ] = sText; + } + else { + if ( pResData->sText[ nLangIndex ].Len()) { + ByteString sError( "Language " ); + sError += nLangIndex; + sError += " defined twice"; + } + pResData->sText[ nLangIndex ] = sText; + } + } + else if ( sKey == "HELPTEXT" ) { + //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + // } + SetChildWithText(); + pResData->bHelpText = TRUE; + if ( bBreakWhenHelpText ) { + ByteString sError( "\"HelpText\" found in source\n" ); + YYWarning( sError.GetBufferAccess()); + sError.ReleaseBufferAccess(); + SetError(); + } + if ( bMergeMode ) + PrepareTextToMerge( sOrig, STRING_TYP_HELPTEXT, nLangIndex, pResData ); + //if ( bUnmerge ) + // pResData->sHelpText[ nLangIndex ] = sText; + else { + if ( pResData->sHelpText[ nLangIndex ].Len()) { + ByteString sError( "Language " ); + sError += nLangIndex; + sError += " defined twice"; + } + pResData->sHelpText[ nLangIndex ] = sText; + } + } + else if ( sKey == "QUICKHELPTEXT" ) { + //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + // } + SetChildWithText(); + pResData->bQuickHelpText = TRUE; + if ( bMergeMode ) + PrepareTextToMerge( sOrig, STRING_TYP_QUICKHELPTEXT, nLangIndex, pResData ); + //if ( bUnmerge ) + // pResData->sQuickHelpText[ nLangIndex ] = sText; + else { + if ( pResData->sQuickHelpText[ nLangIndex ].Len()) { + ByteString sError( "Language " ); + sError += nLangIndex; + sError += " defined twice"; + } + pResData->sQuickHelpText[ nLangIndex ] = sText; + } + } + else if ( sKey == "TITLE" ) { + //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ + // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); + // } + SetChildWithText(); + pResData->bTitle = TRUE; + if ( bMergeMode ) + PrepareTextToMerge( sOrig, STRING_TYP_TITLE, nLangIndex, pResData ); + //if ( bUnmerge ) + // pResData->sTitle[ nLangIndex ] = sText; + else { + if ( pResData->sTitle[ nLangIndex ].Len()) { + ByteString sError( "Language " ); + sError += nLangIndex; + sError += " defined twice"; + } + pResData->sTitle[ nLangIndex ] = sText; + } + } + else if ( sKey == "ACCESSPATH" ) { + pResData->SetId( sText, ID_LEVEL_ACCESSPATH ); + } + else if ( sKey == "FIELDNAME" ) { + pResData->SetId( sText, ID_LEVEL_FIELDNAME ); + } + } + } + break; + case NEWTEXTINRES: { + bDontWriteOutput = TRUE; + // this means something like // ### Achtung : Neuer Text ... + /*ByteString sLang( "GERMAN" ); + ByteString sText = sToken.GetToken( 2, ':' ).GetToken( 0, '*' ); + CleanValue( sText ); + if ( sText.Len()) + pResData->sText[ sLang ] = sText;*/ + } + break; + case APPFONTMAPPING: { + bDontWriteOutput = FALSE; + // this is a AppfontMapping, so look if its a definition + // of field size + ByteString sKey = sToken.GetToken( 0, '=' ); + sKey.EraseAllChars( ' ' ); + sKey.EraseAllChars( '\t' ); + ByteString sMapping = sToken.GetToken( 1, '=' ); + sMapping = sMapping.GetToken( 1, '(' ); + sMapping = sMapping.GetToken( 0, ')' ); + sMapping.EraseAllChars( ' ' ); + sMapping.EraseAllChars( '\t' ); + if ( sKey.ToUpperAscii() == "SIZE" ) { + pResData->nWidth = ( USHORT ) sMapping.GetToken( 0, ',' ).ToInt64(); + } + else if ( sKey == "POSSIZE" ) { + pResData->nWidth = ( USHORT ) sMapping.GetToken( 2, ',' ).ToInt64(); + } + } + break; + case RSCDEFINELEND: + bDontWriteOutput = FALSE; + break; + case CONDITION: { + bDontWriteOutput = FALSE; + while( sToken.SearchAndReplace( "\r", " " ) != STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; + ByteString sCondition = sToken.GetToken( 0, ' ' ); + if ( sCondition == "#ifndef" ) { + sActPForm = "!defined "; + sActPForm += sToken.GetToken( 1, ' ' ); + } + else if ( sCondition == "#ifdef" ) { + sActPForm = "defined "; + sActPForm += sToken.GetToken( 1, ' ' ); + } + else if ( sCondition == "#if" ) { + sActPForm = sToken.Copy( 4 ); + while ( sActPForm.SearchAndReplace( "||", "\\or" ) != STRING_NOTFOUND ) {}; + } + else if ( sCondition == "#elif" ) { + sActPForm = sToken.Copy( 6 ); + while ( sActPForm.SearchAndReplace( "||", "\\or" ) != STRING_NOTFOUND ) {}; + } + else if ( sCondition == "#else" ) { + sActPForm = sCondition; + } + else if ( sCondition == "#endif" ) { + sActPForm = ""; + } + else break; + if ( nLevel ) { + WriteData( pResData, TRUE ); + pResData->sPForm = sActPForm; + } + } + break; + case EMPTYLINE : { + bDontWriteOutput = FALSE; + if ( bDefine ) { + bNextMustBeDefineEOL = FALSE; + bDefine = FALSE; + while ( nLevel ) + Parse( LEVELDOWN, "" ); + //WorkOnTokenSet( LEVELDOWN, pTkn ); + } + } + break; + case PRAGMA : { + bDontWriteOutput = FALSE; + while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; + sToken.EraseLeadingChars( ' ' ); + sToken.EraseTrailingChars( ' ' ); + + ByteString sCharset = sToken.GetToken( 1, ' ' ); + ByteString sSet = sToken.GetToken( 2, ' ' ); + if (( sCharset.ToUpperAscii() == "CHARSET_IBMPC" ) || + ( sCharset == "RTL_TEXTENCODING_IBM_850" ) || + (( sCharset == "CHARSET" ) && ( sSet.ToUpperAscii() == "IBMPC" ))) + { + aCharSet = RTL_TEXTENCODING_IBM_850; + } + else if (( sCharset == "CHARSET_ANSI" ) || + ( sCharset == "RTL_TEXTENCODING_MS_1252" ) || + (( sCharset == "CHARSET" ) && ( sSet.ToUpperAscii() == "ANSI" ))) + { + aCharSet = RTL_TEXTENCODING_MS_1252; + } + } + break; + case TEXTREFID : { + bDontWriteOutput = TRUE; + /*ByteString sK = sToken.GetToken( 0, '=' ); + ByteString sKey = sK.EraseAllChars( '\t' ).EraseAllChars( ' ' ); + ByteString sT = sToken.GetToken( 1, '=' ).GetToken( 0, ';' ); + USHORT nRefId = ( USHORT ) sT.EraseAllChars( '\t' ).EraseAllChars( ' ' ).ToInt32(); + if (( sKey.ToUpperAscii() == "TEXT" ) || + ( sKey == "MESSAGE" ) || + ( sKey == "CUSTOMUNITTEXT" ) || + ( sKey == "SLOTNAME" ) || + ( sKey == "UINAME" )) + pResData->nTextRefId = nRefId; + else if ( sKey == "HELPTEXT" ) + pResData->nHelpTextRefId = nRefId; + else if ( sKey == "QUICKHELPTEXT" ) + pResData->nQuickHelpTextRefId = nRefId; + else if ( sKey == "TITLE" ) + pResData->nTitleRefId = nRefId;*/ + } + } + if ( bWriteToMerged ) { + // the current token must be written to dest. without merging + + if( bDefine && sOrig.Len() > 2 ){ + for( USHORT n = 0 ; n < sOrig.Len() ; n++ ){ + if( sOrig.GetChar( n ) == '\n' && sOrig.GetChar( n-1 ) != '\\'){ + sOrig.Insert('\\' , n++ ); + } + } + } + WriteToMerged( sOrig , false); + } + + if ( bExecuteDown ) { + Parse( LEVELDOWN, "" ); + //WorkOnTokenSet( LEVELDOWN, pTkn ); + } + + return 1; +} + +/*****************************************************************************/ +void Export::CutComment( ByteString &rText ) +/*****************************************************************************/ +{ + if ( rText.Search( "//" ) != STRING_NOTFOUND ) { + ByteString sWork( rText ); + sWork.SearchAndReplaceAll( "\\\"", "XX" ); + USHORT i = 0; + BOOL bInner = FALSE; + + while ( i < sWork.Len() - 1 ) { + if ( sWork.GetChar( i ) == '\"' ) + bInner = !bInner; + else if + (( sWork.GetChar( i ) == '/' ) && + ( !bInner ) && + ( sWork.GetChar( i + 1 ) == '/' )) + { + rText.Erase( i ); + return; + } + i++; + } + } +} + +void Export::UnmergeUTF8( ByteString& sOrig ){ + USHORT nPos1 = sOrig.Search('\"'); + USHORT nPos2 = sOrig.SearchBackward('\"'); + if( nPos1 > 0 && nPos2 > 0 && nPos1 < nPos2){ + ByteString sPart = sOrig.Copy(nPos1+1 , nPos2-1); + ByteString sPartUTF8 = sPart; + sPartUTF8.Convert( RTL_TEXTENCODING_MS_1252 , RTL_TEXTENCODING_UTF8 ); + sOrig.SearchAndReplace( sPart , sPartUTF8 ); + } +} + +/*****************************************************************************/ +BOOL Export::ListExists( ResData *pResData, USHORT nLst ) +/*****************************************************************************/ +{ + switch ( nLst ) { + case LIST_STRING: return pResData->pStringList != NULL; + case LIST_FILTER: return pResData->pFilterList != NULL; + case LIST_ITEM: return pResData->pItemList != NULL; + case LIST_PAIRED: return pResData->pPairedList != NULL; + case LIST_UIENTRIES: return pResData->pUIEntries != NULL; + } + return FALSE; +} + +/*****************************************************************************/ +BOOL Export::WriteData( ResData *pResData, BOOL bCreateNew ) +/*****************************************************************************/ +{ + if ( bMergeMode ) { + MergeRest( pResData ); + return TRUE; + } + + if ( bUnmerge ) + return TRUE; + +/* ByteStringHashMap::iterator pos3 = pResData->sText.begin(); + ByteStringHashMap::iterator end3 = pResData->sText.end(); + for(;pos3!=end3;++pos3){ + + printf("[%s]=%s\n", pos3->first.GetBuffer(), pos3->second.GetBuffer() ); + }*/ + // mandatory to export: en-US + + if (( //pResData->sText[ ByteString("de") ].Len() && + ( pResData->sText[ SOURCE_LANGUAGE ].Len())) + || + ( //pResData->sHelpText[ ByteString("de") ].Len() && + ( pResData->sHelpText[ SOURCE_LANGUAGE ].Len())) + || + ( //pResData->sQuickHelpText[ ByteString("de") ].Len() && + ( pResData->sQuickHelpText[ SOURCE_LANGUAGE ].Len())) + || + ( //pResData->sTitle[ ByteString("de") ].Len() && + ( pResData->sTitle[ SOURCE_LANGUAGE ].Len()))) + + { + FillInFallbacks( pResData ); + + ByteString sGID = pResData->sGId; + ByteString sLID; + if ( !sGID.Len()) + sGID = pResData->sId; + else + sLID = pResData->sId; + + ByteString sXText; + ByteString sXHText; + ByteString sXQHText; + ByteString sXTitle; + + ByteString sTimeStamp( Export::GetTimeStamp()); + ByteString sCur; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + if ( !sCur.EqualsIgnoreCaseAscii("x-comment") ){ + if ( pResData->sText[ sCur ].Len()) + sXText = pResData->sText[ sCur ]; + else { + sXText = pResData->sText[ SOURCE_LANGUAGE ]; + /*if ( !sXText.Len()) + sXText = pResData->sText[ ByteString("en") ]; + if ( !sXText.Len()) + sXText = pResData->sText[ ByteString("de") ];*/ + } + + if ( pResData->sHelpText[ sCur ].Len()) + sXHText = pResData->sHelpText[ sCur ]; + else { + sXHText = pResData->sHelpText[ SOURCE_LANGUAGE ]; + /*if ( !sXHText.Len()) + sXHText = pResData->sHelpText[ ByteString("en") ]; + if ( !sXText.Len()) + sXHText = pResData->sHelpText[ ByteString("de") ];*/ + } + + if ( pResData->sQuickHelpText[ sCur ].Len()) + sXQHText = pResData->sQuickHelpText[ sCur ]; + else { + sXQHText = pResData->sQuickHelpText[ SOURCE_LANGUAGE ]; + /*if ( !sXQHText.Len()) + sXQHText = pResData->sQuickHelpText[ ByteString("en") ]; + if ( !sXQHText.Len()) + sXQHText = pResData->sQuickHelpText[ ByteString("de") ];*/ + } + + if ( pResData->sTitle[ sCur ].Len()) + sXTitle = pResData->sTitle[ sCur ]; + else { + sXTitle = pResData->sTitle[ SOURCE_LANGUAGE ]; + /*if ( !sXTitle.Len()) + sXTitle = pResData->sTitle[ ByteString("en") ]; + if ( !sXTitle.Len()) + sXTitle = pResData->sTitle[ ByteString("de") ];*/ + } + + if ( !sXText.Len()) + sXText = "-"; + + if ( !sXHText.Len()) { + /*if ( pResData->sHelpText[ ByteString("de") ].Len()) + sXHText = pResData->sHelpText[ ByteString("de") ];*/ + if ( pResData->sHelpText[ SOURCE_LANGUAGE ].Len()) + sXHText = pResData->sHelpText[ SOURCE_LANGUAGE ]; + /*else if ( pResData->sHelpText[ ByteString("en") ].Len()) + sXHText = pResData->sHelpText[ ByteString("en") ];*/ + } + } + else + sXText = pResData->sText[ sCur ]; + + if ( bEnableExport ) { + ByteString sOutput( sProject ); sOutput += "\t"; + if ( sRoot.Len()) + sOutput += sActFileName; + sOutput += "\t0\t"; + sOutput += pResData->sResTyp; sOutput += "\t"; + sOutput += sGID; sOutput += "\t"; + sOutput += sLID; sOutput += "\t"; + sOutput += pResData->sHelpId; sOutput += "\t"; + sOutput += pResData->sPForm; sOutput += "\t"; + sOutput += ByteString::CreateFromInt64( pResData->nWidth ); sOutput += "\t"; + sOutput += sCur; sOutput += "\t"; + + + sOutput += sXText; sOutput += "\t"; + sOutput += sXHText; sOutput += "\t"; + sOutput += sXQHText; sOutput+= "\t"; + sOutput += sXTitle; sOutput += "\t"; + sOutput += sTimeStamp; + + // if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sProject ) ) ) + aOutput.WriteLine( sOutput ); + } + + if ( bCreateNew ) { + pResData->sText[ sCur ] = ""; + pResData->sHelpText[ sCur ] = ""; + pResData->sQuickHelpText[ sCur ]= ""; + pResData->sTitle[ sCur ] = ""; + } + } + } + FillInFallbacks( pResData ); + if ( pResData->pStringList ) { + ByteString sList( "stringlist" ); + WriteExportList( pResData, pResData->pStringList, sList, bCreateNew ); + if ( bCreateNew ) + pResData->pStringList = 0; + } + if ( pResData->pFilterList ) { + ByteString sList( "filterlist" ); + WriteExportList( pResData, pResData->pFilterList, sList, bCreateNew ); + if ( bCreateNew ) + pResData->pFilterList = 0; + } + if ( pResData->pItemList ) { + ByteString sList( "itemlist" ); + WriteExportList( pResData, pResData->pItemList, sList, bCreateNew ); + if ( bCreateNew ) + pResData->pItemList = 0; + } + if ( pResData->pPairedList ) { + ByteString sList( "pairedlist" ); + WriteExportList( pResData, pResData->pPairedList, sList, bCreateNew ); + if ( bCreateNew ) + pResData->pItemList = 0; + } + if ( pResData->pUIEntries ) { + ByteString sList( "uientries" ); + WriteExportList( pResData, pResData->pUIEntries, sList, bCreateNew ); + if ( bCreateNew ) + pResData->pUIEntries = 0; + } + return TRUE; +} +ByteString Export::GetPairedListID( const ByteString& sText ){ +// < "STRING" ; IDENTIFIER ; > ; + ByteString sIdent = sText.GetToken( 1, ';' ); + sIdent.ToUpperAscii(); + while( sIdent.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + sIdent.EraseTrailingChars( ' ' ); + sIdent.EraseLeadingChars( ' ' ); + return sIdent; +} +ByteString Export::GetPairedListString( const ByteString& sText ){ +// < "STRING" ; IDENTIFIER ; > ; + ByteString sString = sText.GetToken( 0, ';' ); + while( sString.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; + sString.EraseTrailingChars( ' ' ); + ByteString s1 = sString.Copy( sString.Search( '\"' )+1 ); + sString = s1.Copy( 0 , s1.SearchBackward( '\"' ) ); + sString.EraseTrailingChars( ' ' ); + sString.EraseLeadingChars( ' ' ); + return sString; +} +ByteString Export::StripList( const ByteString& sText ){ + ByteString s1 = sText.Copy( sText.Search( '\"' ) + 1 ); + return s1.Copy( 0 , s1.SearchBackward( '\"' ) ); +} + +/*****************************************************************************/ +BOOL Export::WriteExportList( ResData *pResData, ExportList *pExportList, + const ByteString &rTyp, BOOL bCreateNew ) +/*****************************************************************************/ +{ + ByteString sGID = pResData->sGId; + if ( !sGID.Len()) + sGID = pResData->sId; + else { + sGID += "."; + sGID += pResData->sId; + sGID.EraseTrailingChars( '.' ); + } + + ByteString sTimeStamp( Export::GetTimeStamp()); + ByteString sCur; + for ( ULONG i = 0; pExportList != NULL && i < pExportList->Count(); i++ ) { + ExportListEntry *pEntry = pExportList->GetObject( i ); + // mandatory for export: german and eng. and/or enus + //ByteString a("Export::WriteExportList::pEntry"); + //Export::DumpMap( a, *pEntry ); + + ByteString sLID( ByteString::CreateFromInt64( i + 1 )); + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + if ( //1 ) + //(*pEntry)[ ByteString("de") ].Len() && + (*pEntry)[ SOURCE_LANGUAGE ].Len() ) + //|| + // (*pEntry)[ ByteString("en") ].Len())) + { + if ( bEnableExport ) + { + ByteString sText((*pEntry)[ SOURCE_LANGUAGE ] ); + + // Strip PairList Line String + if( rTyp.EqualsIgnoreCaseAscii("pairedlist") ){ + sLID = GetPairedListID( sText ); + if ((*pEntry)[ sCur ].Len()) + sText = (*pEntry)[ sCur ]; + sText = GetPairedListString( sText ); + } + else{ + //if ((*pEntry)[ sCur ].Len()){ + // if( sCur.EqualsIgnoreCaseAscii("de") ){ + // sText = StripList( (*pEntry)[ sCur ] ); + // } + // else + sText = StripList( (*pEntry)[ sCur ] ); + if( sText == "\\\"" ) + sText = "\""; + //} + } + + ByteString sOutput( sProject ); sOutput += "\t"; + if ( sRoot.Len()) + sOutput += sActFileName; + sOutput += "\t0\t"; + sOutput += rTyp; sOutput += "\t"; + sOutput += sGID; sOutput += "\t"; + sOutput += sLID; sOutput += "\t\t"; + sOutput += pResData->sPForm; sOutput += "\t0\t"; + sOutput += sCur; sOutput += "\t"; + + sOutput += sText; sOutput += "\t\t\t\t"; + sOutput += sTimeStamp; + + //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sProject ) ) ) + aOutput.WriteLine( sOutput ); + + } + } + } + if ( bCreateNew ) + delete [] pEntry; + } + if ( bCreateNew ) + delete pExportList; + + return TRUE; +} + +/*****************************************************************************/ +ByteString Export::FullId() +/*****************************************************************************/ +{ + ByteString sFull; + if ( nLevel > 1 ) { + sFull = aResStack.GetObject( 0 )->sId; + for ( USHORT i = 1; i < nLevel - 1; i++ ) { + ByteString sToAdd = aResStack.GetObject( i )->sId; + if ( sToAdd.Len()) { + sFull += "."; + sFull += sToAdd; + } + } + } + if ( sFull.Len() > 255 ) { + ByteString sError( "GroupId > 255 chars" ); + printf("GroupID = %s\n",sFull.GetBuffer()); + yyerror( sError.GetBufferAccess()); + sError.ReleaseBufferAccess(); + } + + return sFull; +} + +/*****************************************************************************/ +void Export::InsertListEntry( const ByteString &rText, const ByteString &rLine ) +/*****************************************************************************/ +{ + ResData *pResData = aResStack.GetObject( nLevel-1 ); + + ExportList *pList = NULL; + if ( nList == LIST_STRING ) { + pList = pResData->pStringList; + if ( !pList ) { + pResData->pStringList = new ExportList(); + pList = pResData->pStringList; + nListIndex = 0; + } + } + else if ( nList == LIST_FILTER ) { + pList = pResData->pFilterList; + if ( !pList ) { + pResData->pFilterList = new ExportList(); + pList = pResData->pFilterList; + nListIndex = 0; + } + } + else if ( nList == LIST_ITEM ) { + pList = pResData->pItemList; + if ( !pList ) { + pResData->pItemList = new ExportList(); + pList = pResData->pItemList; + nListIndex = 0; + } + } + else if ( nList == LIST_PAIRED ) { + pList = pResData->pPairedList; + if ( !pList ) { + pResData->pPairedList = new ExportList(); + pList = pResData->pPairedList; + nListIndex = 0; + } + } + else if ( nList == LIST_UIENTRIES ) { + pList = pResData->pUIEntries; + if ( !pList ) { + pResData->pUIEntries = new ExportList(); + pList = pResData->pUIEntries; + nListIndex = 0; + } + } + else + return; + + if ( nListIndex + 1 > pList->Count()) { + ExportListEntry *pNew = new ExportListEntry(); + (*pNew)[ LIST_REFID ] = ByteString::CreateFromInt32( REFID_NONE ); + pList->Insert( pNew, LIST_APPEND ); + } + ExportListEntry *pCurEntry = pList->GetObject( nListIndex ); + + // For paired list use the line to set proper lid + if( nList == LIST_PAIRED ){ + (*pCurEntry)[ nListLang ] = rLine; + }else + (*pCurEntry)[ nListLang ] = rText; + + // Remember en-US fallback string, so each list has the same amount of elements + //if ( nListLang.EqualsIgnoreCaseAscii("en-US") ) { + if ( Export::isSourceLanguage( nListLang ) ) { + if( nList == LIST_PAIRED ){ + const ByteString sPlist("pairedlist"); + ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sId , GetPairedListID( rLine ) , sFilename ); + pResData->addFallbackData( sKey , rText ); + } + // new fallback + else{ + const ByteString sPlist("list"); + ByteString a( pResData->sGId ); + a.Append( "." ); + a.Append( pResData->sId ); + sal_Int64 x = nListIndex+1; + ByteString b( ByteString::CreateFromInt64( x ) ); + ByteString sKey = MergeDataFile::CreateKey( sPlist , a , b , sFilename ); + pResData->addFallbackData( sKey , rText ); + } + // new fallback + } + + //if ( nListLang.EqualsIgnoreCaseAscii("en-US") ) { + if ( Export::isSourceLanguage( nListLang ) ) { + if( nList == LIST_PAIRED ){ + (*pCurEntry)[ SOURCE_LANGUAGE ] = rLine; + } + else + (*pCurEntry)[ SOURCE_LANGUAGE ] = rLine; + + pList->NewSourceLanguageListEntry(); + } + + //printf("Export::InsertListEntry ResData.id = %s ResData.ListData = %s\n",pResData->sId.GetBuffer() ,(*pCurEntry)[ nListLang ].GetBuffer()); + nListIndex++; +} + +/*****************************************************************************/ +void Export::CleanValue( ByteString &rValue ) +/*****************************************************************************/ +{ + while ( rValue.Len()) { + if (( rValue.GetChar( 0 ) == ' ' ) || ( rValue.GetChar( 0 ) == '\t' )) + rValue = rValue.Copy( 1 ); + else + break; + } + + if ( rValue.Len()) { + for ( USHORT i = rValue.Len() - 1; i > 0; i-- ) { + if (( rValue.GetChar( i ) == ' ' ) || ( rValue.GetChar( i ) == '\t' ) || + ( rValue.GetChar( i ) == '\n' ) || ( rValue.GetChar( i ) == ';' ) || + ( rValue.GetChar( i ) == '{' ) || ( rValue.GetChar( i ) == '\\' ) || + ( rValue.GetChar( i ) == '\r' )) + rValue.Erase( i ); + else + break; + } + } +} + + +/*****************************************************************************/ +ByteString Export::GetText( const ByteString &rSource, int nToken ) +/*****************************************************************************/ +#define TXT_STATE_NON 0x000 +#define TXT_STATE_TEXT 0x001 +#define TXT_STATE_MACRO 0x002 +{ + ByteString sReturn; + switch ( nToken ) { + case TEXTLINE: + case LONGTEXTLINE: { + ByteString sTmp( rSource.Copy( rSource.Search( "=" ))); + CleanValue( sTmp ); + sTmp.EraseAllChars( '\n' ); + sTmp.EraseAllChars( '\r' ); + + while ( sTmp.SearchAndReplace( "\\\\\"", "-=<[BSlashBSlashHKom]>=-\"" ) + != STRING_NOTFOUND ) {}; + while ( sTmp.SearchAndReplace( "\\\"", "-=<[Hochkomma]>=-" ) + != STRING_NOTFOUND ) {}; + while ( sTmp.SearchAndReplace( "\\", "-=<[0x7F]>=-" ) + != STRING_NOTFOUND ) {}; + while ( sTmp.SearchAndReplace( "\\0x7F", "-=<[0x7F]>=-" ) + != STRING_NOTFOUND ) {}; + + USHORT nStart = 0; + USHORT nState = TXT_STATE_MACRO; + + nState = TXT_STATE_TEXT; + nStart = 1; + + + for ( USHORT i = nStart; i < sTmp.GetTokenCount( '\"' ); i++ ) { + ByteString sToken = sTmp.GetToken( i, '\"' ); + if ( sToken.Len()) { + if ( nState == TXT_STATE_TEXT ) { + sReturn += sToken; + nState = TXT_STATE_MACRO; + } + else { + while( sToken.SearchAndReplace( "\t", " " ) != + STRING_NOTFOUND ) {}; + while( sToken.SearchAndReplace( " ", " " ) != + STRING_NOTFOUND ) {}; + sToken.EraseLeadingChars( ' ' ); + sToken.EraseTrailingChars( ' ' ); + if ( sToken.Len()) { + sReturn += "\\\" "; + sReturn += sToken; + sReturn += " \\\""; + } + nState = TXT_STATE_TEXT; + } + } + } + + while ( sReturn.SearchAndReplace( "-=<[0x7F]>=-", "" ) + != STRING_NOTFOUND ) {}; + while ( sReturn.SearchAndReplace( "-=<[Hochkomma]>=-", "\"" ) + != STRING_NOTFOUND ) {}; + while ( sReturn.SearchAndReplace( "-=<[BSlashBSlashHKom]>=-", "\\\\" ) + != STRING_NOTFOUND ) {}; + + + while ( sReturn.SearchAndReplace( "\\\\", "-=<[BSlashBSlash]>=-" ) + != STRING_NOTFOUND ) {}; + while ( sReturn.SearchAndReplace( "-=<[BSlashBSlash]>=-", "\\" ) + != STRING_NOTFOUND ) {}; + + } + break; + } + return sReturn; +} + +/*****************************************************************************/ +void Export::WriteToMerged( const ByteString &rText , bool bSDFContent ) +/*****************************************************************************/ +{ + static ByteString SLASH ('\\'); + static ByteString RETURN ('\n'); + //printf("%s\n",rText.GetBuffer() ); + + #if 0 + // statement has no effect + if( pParseQueue->bMflag && !bSDFContent ) pParseQueue->bMflag; + #endif + + if ( !bDontWriteOutput || !bUnmerge ) { + ByteString sText( rText ); + while ( sText.SearchAndReplace( " \n", "\n" ) != STRING_NOTFOUND ) {}; + if( pParseQueue->bNextIsM && bSDFContent && sText.Len() > 2 ){ + for( USHORT n = 0 ; n < sText.Len() ; n++ ){ + if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ + sText.Insert('\\' , n++ ); + + } + } + } + else if( pParseQueue->bLastWasM && sText.Len() > 2 ){ + for( USHORT n = 0 ; n < sText.Len() ; n++ ){ + if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ + sText.Insert('\\' , n++ ); + } + if( sText.GetChar( n ) == '\n' )pParseQueue->bMflag=true; + } + } + else if( pParseQueue->bCurrentIsM && bSDFContent && sText.Len() > 2 ){ + for( USHORT n = 0 ; n < sText.Len() ; n++ ){ + if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ + sText.Insert('\\' , n++ ); + pParseQueue->bMflag=true; + } + } + } + else if( pParseQueue->bMflag ){ + for( USHORT n = 1 ; n < sText.Len() ; n++ ){ + if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ + sText.Insert('\\' , n++ ); + } + } + } + for ( USHORT i = 0; i < sText.Len(); i++ ) { + if ( sText.GetChar( i ) != '\n' ){ + aOutput.Write( ByteString( sText.GetChar( i )).GetBuffer(), 1 ); + + } + else{ + aOutput.WriteLine( ByteString()); + } + + } + } +} + +/*****************************************************************************/ +void Export::ConvertMergeContent( ByteString &rText ) +/*****************************************************************************/ +{ + BOOL bNoOpen = ( rText.Search( "\\\"" ) != 0 ); + ByteString sClose( rText.Copy( rText.Len() - 2 )); + BOOL bNoClose = ( sClose != "\\\"" ); + ByteString sNew; + for ( USHORT i = 0; i < rText.Len(); i++ ) { + ByteString sChar( rText.GetChar( i )); + if ( sChar == "\\" ) { + if (( i + 1 ) < rText.Len()) { + ByteString sNext( rText.GetChar( i + 1 )); + if ( sNext == "\"" ) { + sChar = "\""; + i++; + } + else if ( sNext == "n" ) { + sChar = "\\n"; + i++; + } + else if ( sNext == "t" ) { + sChar = "\\t"; + i++; + } + else if ( sNext == "\'" ) { + sChar = "\\\'"; + i++; + } + else + sChar = "\\\\"; + } + else { + sChar = "\\\\"; + } + } + else if ( sChar == "\"" ) { + sChar = "\\\""; + } + else if ( sChar == "" ) { + sChar = "\\0x7F"; + } + sNew += sChar; + } + + rText = sNew; + + if ( bNoOpen ) { + ByteString sTmp( rText ); + rText = "\""; + rText += sTmp; + } + if ( bNoClose ) + rText += "\""; +} + +/*****************************************************************************/ +BOOL Export::PrepareTextToMerge( ByteString &rText, USHORT nTyp, + ByteString &nLangIndex, ResData *pResData ) +/*****************************************************************************/ +{ + // position to merge in: + USHORT nStart = 0; + USHORT nEnd = 0; + ByteString sOldId = pResData->sId; + ByteString sOldGId = pResData->sGId; + ByteString sOldTyp = pResData->sResTyp; + + ByteString sOrigText( rText ); + + switch ( nTyp ) { + case LIST_STRING : + case LIST_UIENTRIES : + case LIST_FILTER : + case LIST_PAIRED: + case LIST_ITEM : + { + if ( bUnmerge ) + return TRUE; + + ExportList *pList = NULL; + switch ( nTyp ) { + case LIST_STRING : { + pResData->sResTyp = "stringlist"; + pList = pResData->pStringList; + } + break; + case LIST_UIENTRIES : { + pResData->sResTyp = "uientries"; + pList = pResData->pUIEntries; + } + break; + case LIST_FILTER : { + pResData->sResTyp = "filterlist"; + pList = pResData->pFilterList; + } + break; + case LIST_ITEM : { + pResData->sResTyp = "itemlist"; + pList = pResData->pItemList; + } + break; + case LIST_PAIRED : { + pResData->sResTyp = "pairedlist"; + pList = pResData->pPairedList; + } + break; + + } + if ( pList ) { + ExportListEntry *pCurEntry = pList->GetObject( nListIndex - 1 ); + if ( pCurEntry ) { + //printf("%s\n",Export::DumpMap( "pCurEntry", *pCurEntry ).GetBuffer() ); + //ByteString a("pCurEntry"); + //Export::DumpMap( a , *pCurEntry ); + rText = (*pCurEntry)[ SOURCE_LANGUAGE ]; + if( nTyp == LIST_PAIRED ){ + pResData->addMergedLanguage( nLangIndex ); + } + } + } + + nStart = rText.Search( "\"" ); + if ( nStart == STRING_NOTFOUND ) { + rText = sOrigText; + return FALSE; + } + + BOOL bFound = FALSE; + for ( nEnd = nStart + 1; nEnd < rText.Len() && !bFound; nEnd++ ) { + if ( rText.GetChar( nEnd ) == '\"' ) + bFound = TRUE; + } + if ( !bFound ) { + rText = sOrigText; + return FALSE; + } + + nEnd --; + sLastListLine = rText; + if (( sLastListLine.Search( ">" ) != STRING_NOTFOUND ) && + ( sLastListLine.Search( "<" ) == STRING_NOTFOUND )) + { + ByteString sTmp = sLastListLine; + sLastListLine = "<"; + sLastListLine += sTmp; + } + if ( pResData->sResTyp.EqualsIgnoreCaseAscii( "pairedlist" ) ){ + pResData->sId = GetPairedListID( sLastListLine ); + } + else pResData->sId = ByteString::CreateFromInt32( nListIndex ); + + if ( pResData->sGId.Len()) + pResData->sGId += "."; + pResData->sGId += sOldId; + nTyp = STRING_TYP_TEXT; + } + break; + case STRING_TYP_TEXT : + case STRING_TYP_HELPTEXT : + case STRING_TYP_QUICKHELPTEXT : + case STRING_TYP_TITLE : + { + /*if ( bUnmerge ) { + if (( nLangIndex != ByteString("de") ) && + ( nLangIndex != ByteString("en-US") )) + { + bDontWriteOutput = TRUE; + } + return TRUE; + }*/ + + nStart = rText.Search( "=" ); + if ( nStart == STRING_NOTFOUND ) { + rText = sOrigText; + return FALSE; + } + + nStart++; + BOOL bFound = FALSE; + while(( nStart < rText.Len()) && !bFound ) { + if (( rText.GetChar( nStart ) != ' ' ) && ( rText.GetChar( nStart ) != '\t' )) + bFound = TRUE; + else + nStart ++; + } + + // no start position found + if ( !bFound ) { + rText = sOrigText; + return FALSE; + } + + // position to end mergeing in + nEnd = rText.Len() - 1; + bFound = FALSE; + + while (( nEnd > nStart ) && !bFound ) { + if (( rText.GetChar( nEnd ) != ' ' ) && ( rText.GetChar( nEnd ) != '\t' ) && + ( rText.GetChar( nEnd ) != '\n' ) && ( rText.GetChar( nEnd ) != ';' ) && + ( rText.GetChar( nEnd ) != '{' ) && ( rText.GetChar( nEnd ) != '\\' )) + { + bFound = TRUE; + } + else + nEnd --; + } + } + break; + } + + // search for merge data + if ( !pMergeDataFile ){ + pMergeDataFile = new MergeDataFile( sMergeSrc, sFile , bErrorLog, aCharSet);//, bUTF8 ); + + // Init Languages + ByteString sTmp = Export::sLanguages; + if( sTmp.ToUpperAscii().Equals("ALL") ) + SetLanguages( pMergeDataFile->GetLanguages() ); + else if( !isInitialized )InitLanguages(); + + } +// printf("*************DUMPING****************\n"); +// printf("%s\n",pMergeDataFile->Dump().GetBuffer()); +// printf("*************DUMPING****************\n"); + +// printf("Dumping ResData\n"); +// pResData->Dump(); + PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); + //printf("Dumping pEntrys\n"); + //if( pEntrys ) pEntrys->Dump(); + pResData->sId = sOldId; + pResData->sGId = sOldGId; + pResData->sResTyp = sOldTyp; + + if ( !pEntrys ) { + rText = sOrigText; + return FALSE; // no data found + } + + ByteString sContent; + pEntrys->GetText( sContent, nTyp, nLangIndex ); + //if ( !sContent.Len() && ( ! nLangIndex.EqualsIgnoreCaseAscii("en-US") )) { + if ( !sContent.Len() && ( ! Export::isSourceLanguage( nLangIndex ) )) { + rText = sOrigText; + return FALSE; // no data found + } + + //if ( nLangIndex.EqualsIgnoreCaseAscii("en-US") ) { + if ( Export::isSourceLanguage( nLangIndex ) ) { + return FALSE; + } + + ByteString sPostFix( rText.Copy( ++nEnd )); + rText.Erase( nStart ); + + //ConvertMergeContent( sContent, nTyp ); + ConvertMergeContent( sContent ); + + + + //printf("Merged %s\n",nLangIndex.GetBuffer()); + // merge new res. in text line + rText += sContent; + rText += sPostFix; + + return TRUE; +} + +/*****************************************************************************/ +void Export::MergeRest( ResData *pResData, USHORT nMode ) +/*****************************************************************************/ +{ + //if ( bUnmerge ) { return;} + + //pResData->Dump(); + + if ( !pMergeDataFile ){ + pMergeDataFile = new MergeDataFile( sMergeSrc, sFile ,bErrorLog, aCharSet);//, bUTF8 ); + + // Init Languages + ByteString sTmp = Export::sLanguages; + if( sTmp.ToUpperAscii().Equals("ALL") ) + SetLanguages( pMergeDataFile->GetLanguages() ); + else if( !isInitialized )InitLanguages(); + + } + switch ( nMode ) { + case MERGE_MODE_NORMAL : { + PFormEntrys *pEntry = pMergeDataFile->GetPFormEntrys( pResData ); + + bool bWriteNoSlash = false; + if ( pEntry && pResData->bText ) { + + BOOL bAddSemikolon = FALSE; + BOOL bFirst = TRUE; + ByteString sCur; + ByteString sTmp = Export::sLanguages; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sText; + BOOL bText = pEntry->GetText( sText, STRING_TYP_TEXT, sCur , TRUE ); + if ( bText && sText.Len() && sText != "-" ) { + ByteString sOutput; + if ( bNextMustBeDefineEOL) { + if ( bFirst ) + sOutput += "\t\\\n"; + else + sOutput += ";\t\\\n"; + } + bFirst=FALSE; + sOutput += "\t"; + sOutput += pResData->sTextTyp; + //if ( !sCur.EqualsIgnoreCaseAscii("en-US")) { + if ( ! Export::isSourceLanguage( sCur ) ) { + sOutput += "[ "; + sOutput += sCur; + sOutput += " ] "; + } + sOutput += "= "; + ConvertMergeContent( sText ); + sOutput += sText; + + if ( bDefine && bWriteNoSlash ) + sOutput += ";\n"; + + if ( bDefine ) + sOutput += ";\\\n"; + else if ( !bNextMustBeDefineEOL ) + sOutput += ";\n"; + else + bAddSemikolon = TRUE; + for ( USHORT j = 1; j < nLevel; j++ ) + sOutput += "\t"; + WriteToMerged( sOutput , true ); + } + } + + + if ( bAddSemikolon ) { + ByteString sOutput( ";" ); + WriteToMerged( sOutput , false ); + } + } + + if ( pEntry && pResData->bQuickHelpText ) { + BOOL bAddSemikolon = FALSE; + BOOL bFirst = TRUE; + ByteString sCur; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sText; + BOOL bText = pEntry->GetText( sText, STRING_TYP_QUICKHELPTEXT, sCur, TRUE ); + if ( bText && sText.Len() && sText != "-" ) { + ByteString sOutput; + if ( bNextMustBeDefineEOL) { + if ( bFirst ) + sOutput += "\t\\\n"; + else + sOutput += ";\t\\\n"; + } + bFirst=FALSE; + sOutput += "\t"; + sOutput += "QuickHelpText"; + //if ( !sCur.EqualsIgnoreCaseAscii("en-US") ) { + if ( ! Export::isSourceLanguage( sCur ) ) { + sOutput += "[ "; + sOutput += sCur; + sOutput += " ] "; + } + sOutput += "= "; + ConvertMergeContent( sText ); + sOutput += sText; + if ( bDefine ) + sOutput += ";\\\n"; + else if ( !bNextMustBeDefineEOL ) + sOutput += ";\n"; + else + bAddSemikolon = TRUE; + for ( USHORT j = 1; j < nLevel; j++ ) + sOutput += "\t"; + WriteToMerged( sOutput ,true ); + } + } + if ( bAddSemikolon ) { + ByteString sOutput( ";" ); + WriteToMerged( sOutput , false ); + } + } + + if ( pEntry && pResData->bTitle ) { + BOOL bAddSemikolon = FALSE; + BOOL bFirst = TRUE; + ByteString sCur; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sText; + BOOL bText = pEntry->GetText( sText, STRING_TYP_TITLE, sCur, TRUE ); + if ( bText && sText.Len() && sText != "-" ) { + ByteString sOutput; + if ( bNextMustBeDefineEOL) { + if ( bFirst ) + sOutput += "\t\\\n"; + else + sOutput += ";\t\\\n"; + } + bFirst=FALSE; + sOutput += "\t"; + sOutput += "Title"; + //if ( !sCur.EqualsIgnoreCaseAscii("en-US") ) { + if ( ! Export::isSourceLanguage( sCur ) ) { + sOutput += "[ "; + sOutput += sCur; + sOutput += " ] "; + } + sOutput += "= "; + ConvertMergeContent( sText ); + sOutput += sText; + if ( bDefine ) + sOutput += ";\\\n"; + else if ( !bNextMustBeDefineEOL ) + sOutput += ";\n"; + else + bAddSemikolon = TRUE; + for ( USHORT j = 1; j < nLevel; j++ ) + sOutput += "\t"; + WriteToMerged( sOutput ,true ); + } + } + if ( bAddSemikolon ) { + ByteString sOutput( ";" ); + WriteToMerged( sOutput ,false); + } + } + // Merge Lists + + if ( pResData->bList ) { + //printf("Dumping ResData\n"); + //pResData->Dump(); + + bool bPairedList = false; + ByteString sOldId = pResData->sId; + ByteString sOldGId = pResData->sGId; + ByteString sOldTyp = pResData->sResTyp; + if ( pResData->sGId.Len()) + pResData->sGId += "."; + pResData->sGId += sOldId; + ByteString sSpace; + for ( USHORT i = 1; i < nLevel-1; i++ ) + sSpace += "\t"; + for ( USHORT nT = LIST_STRING; nT <= LIST_UIENTRIES; nT++ ) { + ExportList *pList = NULL; + switch ( nT ) { + case LIST_STRING : pResData->sResTyp = "stringlist"; pList = pResData->pStringList; bPairedList = false; break; + case LIST_FILTER : pResData->sResTyp = "filterlist"; pList = pResData->pFilterList; bPairedList = false; break; + case LIST_UIENTRIES : pResData->sResTyp = "uientries"; pList = pResData->pUIEntries;bPairedList = false; break; + case LIST_ITEM : pResData->sResTyp = "itemlist"; pList = pResData->pItemList; bPairedList = false; break; + case LIST_PAIRED : pResData->sResTyp = "pairedlist"; pList = pResData->pPairedList; bPairedList = true; break; + } + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + USHORT nIdx = 1; + + // Set matching pairedlist identifier + if( bPairedList && pResData->pPairedList && ( nIdx == 1 ) ){ + ExportListEntry* pListE = ( ExportListEntry* ) pResData->pPairedList->GetObject( nIdx-1 ); + pResData->sId = GetPairedListID ( (*pListE)[ SOURCE_LANGUAGE ] ); + } + else + pResData->sId = ByteString("1"); + + PFormEntrys *pEntrys; + ULONG nLIndex = 0; + ULONG nMaxIndex = 0; + if ( pList ) + nMaxIndex = pList->GetSourceLanguageListEntryCount(); + pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); + while( pEntrys && ( nLIndex < nMaxIndex )) { + //printf("Lang %s, List Index %d\n",sCur.GetBuffer(),(int)nLIndex); + ByteString sText; + BOOL bText; + bText = pEntrys->GetText( sText, STRING_TYP_TEXT, sCur, TRUE ); + if( !bText ) + bText = pEntrys->GetText( sText , STRING_TYP_TEXT, SOURCE_LANGUAGE , FALSE ); + + // Use fallback, if data is missing in sdf file + //if( !bText && pResData->sResTyp.Equals( "pairedlist" ) ){ + if( !bText && bPairedList ){ + if( pResData->isMerged( sCur ) ) break; + const ByteString sPlist("pairedlist"); + ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sGId , pResData->sId , sFilename ); + bText = pResData->getFallbackData( sKey , sText ); + }else if ( !bText ){// new fallback + if( pResData->isMerged( sCur ) ) break; + const ByteString sPlist("list"); + ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sGId , pResData->sId , sFilename ); + bText = pResData->getFallbackData( sKey , sText ); + } // new fallback + + if ( bText && sText.Len()) { + //if( pEntrys ) pEntrys->Dump(); + if ( nIdx == 1 ) { + ByteString sHead; + if ( bNextMustBeDefineEOL ) + sHead = "\\\n\t"; + sHead += sSpace; + switch ( nT ) { + case LIST_STRING : sHead += "StringList "; break; + case LIST_FILTER : sHead += "FilterList "; break; + case LIST_ITEM : sHead += "ItemList "; break; + case LIST_PAIRED : sHead += "PairedList "; break; + case LIST_UIENTRIES : sHead += "UIEntries "; break; + } + sHead += "[ "; + sHead += sCur; + sHead += " ] "; + //} + if ( bDefine || bNextMustBeDefineEOL ) { + sHead += "= \\\n"; + sHead += sSpace; + sHead += "\t{\\\n\t"; + } + else { + sHead += "= \n"; + sHead += sSpace; + sHead += "\t{\n\t"; + } + WriteToMerged( sHead , true); + } + ByteString sLine; + if ( pList && pList->GetObject( nLIndex )) + sLine = ( *pList->GetObject( nLIndex ))[ SOURCE_LANGUAGE ]; + if ( !sLine.Len()) + sLine = sLastListLine; + + if ( sLastListLine.Search( "<" ) != STRING_NOTFOUND ) { + if (( nT != LIST_UIENTRIES ) && + (( sLine.Search( "{" ) == STRING_NOTFOUND ) || + ( sLine.Search( "{" ) >= sLine.Search( "\"" ))) && + (( sLine.Search( "<" ) == STRING_NOTFOUND ) || + ( sLine.Search( "<" ) >= sLine.Search( "\"" )))) + { + sLine.SearchAndReplace( "\"", "< \"" ); + } + } + + USHORT nStart, nEnd; + nStart = sLine.Search( "\"" ); + + ByteString sPostFix; + if( !bPairedList ){ + nEnd = sLine.SearchBackward( '\"' ); + sPostFix = ByteString( sLine.Copy( ++nEnd )); + sLine.Erase( nStart ); + } + + + ConvertMergeContent( sText ); + + // merge new res. in text line + if( bPairedList ){ + sLine = MergePairedList( sLine , sText ); + } + else{ + sLine += sText; + sLine += sPostFix; + } + + ByteString sText1( "\t" ); + sText1 += sLine; + if ( bDefine || bNextMustBeDefineEOL ) + sText1 += " ;\\\n"; + else + sText1 += " ;\n"; + sText1 += sSpace; + sText1 += "\t"; + //printf("Writing '%s'\n",sText1.GetBuffer()); + WriteToMerged( sText1 ,true ); + + // Set matching pairedlist identifier + if ( bPairedList ){ + nIdx++; + ExportListEntry* pListE = ( ExportListEntry* ) pResData->pPairedList->GetObject( ( nIdx ) -1 ); + if( pListE ){ + pResData->sId = GetPairedListID ( (*pListE)[ SOURCE_LANGUAGE ] ); + } + } + else + pResData->sId = ByteString::CreateFromInt32( ++nIdx ); + } + else + break; + nLIndex ++; + PFormEntrys *oldEntry = pEntrys; + pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); // <--- game over + if( !pEntrys ) + pEntrys = oldEntry; + } + if ( nIdx > 1 ) { + ByteString sFooter( sSpace.Copy( 1 )); + if ( bNextMustBeDefineEOL ) + sFooter += "};"; + else if ( !bDefine ) + sFooter += "};\n\t"; + else + sFooter += "\n\n"; + WriteToMerged( sFooter ,true ); + } + } + } + + pResData->sId = sOldId; + pResData->sGId = sOldGId; + pResData->sResTyp = sOldTyp; + } + } + break; + case MERGE_MODE_LIST : { + ExportList *pList = NULL; + switch ( nList ) { + // PairedList + case LIST_STRING : pList = pResData->pStringList; break; + case LIST_FILTER : pList = pResData->pFilterList; break; + case LIST_UIENTRIES : pList = pResData->pUIEntries; break; + case LIST_ITEM : pList = pResData->pItemList; break; + case LIST_PAIRED : pList = pResData->pPairedList; break; + + } + + nListIndex++; + ULONG nMaxIndex = 0; + if ( pList ) + nMaxIndex = pList->GetSourceLanguageListEntryCount(); + ByteString sLine; + if ( pList && pList->GetObject( nListIndex )) + sLine = ( *pList->GetObject( nListIndex ))[ SOURCE_LANGUAGE ]; + if ( !sLine.Len()) + sLine = sLastListLine; + + if ( sLastListLine.Search( "<" ) != STRING_NOTFOUND ) { + if (( nList != LIST_UIENTRIES ) && + (( sLine.Search( "{" ) == STRING_NOTFOUND ) || + ( sLine.Search( "{" ) >= sLine.Search( "\"" ))) && + (( sLine.Search( "<" ) == STRING_NOTFOUND ) || + ( sLine.Search( "<" ) >= sLine.Search( "\"" )))) + { + sLine.SearchAndReplace( "\"", "< \"" ); + } + } + + while( PrepareTextToMerge( sLine, nList, nListLang, pResData ) && ( nListIndex <= nMaxIndex )) { + ByteString sText( "\t" ); + sText += sLine; + sText += " ;"; + sText += "\n"; + for ( USHORT i = 0; i < nLevel; i++ ) + sText += "\t"; + WriteToMerged( sText ,false ); + nListIndex++; + if ( pList && pList->GetObject( nListIndex )) + sLine = ( *pList->GetObject( nListIndex ))[ SOURCE_LANGUAGE ]; + if ( !sLine.Len()) + sLine = sLastListLine; + sLine += " ;"; + } + } + break; + } + pParseQueue->bMflag = false; +} + +ByteString Export::MergePairedList( ByteString& sLine , ByteString& sText ){ +// < "xy" ; IDENTIFIER ; > + ByteString sPre = sLine.Copy( 0 , sLine.Search('\"') ); + ByteString sPost = sLine.Copy( sLine.SearchBackward('\"') + 1 , sLine.Len() ); + sPre.Append( sText ); + sPre.Append( sPost ); + return sPre; +} + +/*****************************************************************************/ +void Export::SetChildWithText() +/*****************************************************************************/ +{ + if ( aResStack.Count() > 1 ) { + for ( ULONG i = 0; i < aResStack.Count() - 1; i++ ) { + aResStack.GetObject( i )->bChildWithText = TRUE; + } + } +} + +void ParserQueue::Push( const QueueEntry& aEntry ){ +// printf("nTyp = %d ",aEntry.nTyp); + USHORT nLen = aEntry.sLine.Len(); + + if( !bStart ){ + aQueueCur->push( aEntry ); + if( nLen > 1 && aEntry.sLine.GetChar( nLen-1 ) == '\n' ) + bStart = true; + else if ( aEntry.nTyp != IGNOREDTOKENS ){ + if( nLen > 1 && ( aEntry.sLine.GetChar( nLen-1 ) == '\\') ){ + // Next is Macro + bCurrentIsM = true; + }else{ + // Next is no Macro + bCurrentIsM = false; + } + } + } + else{ + aQueueNext->push( aEntry ); + if( nLen > 1 && aEntry.sLine.GetChar( nLen-1 ) != '\n' ){ + if( nLen > 1 && ( aEntry.sLine.GetChar( nLen-1 ) == '\\') ){ + // Next is Macro + bNextIsM = true; + } + else{ + // Next is no Macro + bNextIsM = false; + } + }else if( nLen > 2 && aEntry.sLine.GetChar( nLen-1 ) == '\n' ){ + if( aEntry.nTyp != IGNOREDTOKENS ){ + if( nLen > 2 && ( aEntry.sLine.GetChar( nLen-2 ) == '\\') ){ + // Next is Macro + bNextIsM = true; + } + else{ + // Next is no Macro + bNextIsM = false; + } + } + // Pop current + Pop( *aQueueCur ); + bLastWasM = bCurrentIsM; + // next -> current + bCurrentIsM = bNextIsM; + aQref = aQueueCur; + aQueueCur = aQueueNext; + aQueueNext = aQref; + + } + + else{ + // Pop current + Pop( *aQueueCur ); + bLastWasM = bCurrentIsM; + // next -> current + bCurrentIsM = bNextIsM; + aQref = aQueueCur; + aQueueCur = aQueueNext; + aQueueNext = aQref; + } + } +} + +void ParserQueue::Close(){ + // Pop current + Pop( *aQueueCur ); + // next -> current + bLastWasM = bCurrentIsM; + bCurrentIsM = bNextIsM; + aQref = aQueueCur; + aQueueCur = aQueueNext; + aQueueNext = aQref; + bNextIsM = false; + Pop( *aQueueNext ); +}; +void ParserQueue::Pop( std::queue& aQueue ){ + while( !aQueue.empty() ){ + QueueEntry aEntry = aQueue.front(); + aQueue.pop(); + aExport.Execute( aEntry.nTyp , (char*) aEntry.sLine.GetBuffer() ); + } +} +ParserQueue::ParserQueue( Export& aExportObj ) + : + bCurrentIsM( false ), + bNextIsM( false ) , + bLastWasM( false ), + bMflag( false ) , + aExport( aExportObj ) , + bStart( false ) , + bStartNext( false ) +{ + aQueueNext = new std::queue; + aQueueCur = new std::queue; +} + + +ParserQueue::~ParserQueue(){ + if( aQueueNext ) delete aQueueNext; + if( aQueueCur ) delete aQueueCur; +} diff --git a/l10ntools/source/export2.cxx b/l10ntools/source/export2.cxx new file mode 100644 index 000000000000..d0a37c7c9f3d --- /dev/null +++ b/l10ntools/source/export2.cxx @@ -0,0 +1,741 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: export2.cxx,v $ + * $Revision: 1.43 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include "export.hxx" +#include "utf8conv.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +// +// class ResData(); +// + +/*****************************************************************************/ +ResData::~ResData() +/*****************************************************************************/ +{ + if ( pStringList ) { + // delete existing res. of type StringList + for ( ULONG i = 0; i < pStringList->Count(); i++ ) { + ExportListEntry* test = pStringList->GetObject( i ); + if( test != NULL ) delete test; + } + delete pStringList; + } + if ( pFilterList ) { + // delete existing res. of type FilterList + for ( ULONG i = 0; i < pFilterList->Count(); i++ ) { + ExportListEntry* test = pFilterList->GetObject( i ); + delete test; + } + delete pFilterList; + } + if ( pItemList ) { + // delete existing res. of type ItemList + for ( ULONG i = 0; i < pItemList->Count(); i++ ) { + ExportListEntry* test = pItemList->GetObject( i ); + delete test; + } + delete pItemList; + } + if ( pUIEntries ) { + // delete existing res. of type UIEntries + for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) { + ExportListEntry* test = pUIEntries->GetObject( i ); + delete test; + } + delete pUIEntries; + } +} + +// +// class Export +// + +/*****************************************************************************/ +ByteString Export::sLanguages; +ByteString Export::sForcedLanguages; +//ByteString Export::sIsoCode99; +/*****************************************************************************/ + +void Export::DumpExportList( ByteString& sListName , ExportList& aList ){ + printf( "%s\n", sListName.GetBuffer() ); + ByteString l(""); + ExportListEntry* aEntry; + for( unsigned int x = 0; x < aList.Count() ; x++ ){ + aEntry = (ExportListEntry*) aList.GetObject( x ); + Export::DumpMap( l , *aEntry ); + } + printf("\n"); +} +ByteString Export::DumpMap( ByteString& sMapName , ByteStringHashMap& aMap ){ + ByteStringHashMap::const_iterator idbg; + ByteString sReturn; + + if( sMapName.Len() ) + printf("MapName %s\n", sMapName.GetBuffer()); + if( aMap.size() < 1 ) return ByteString(); + for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ + ByteString a( idbg->first ); + ByteString b( idbg->second ); + printf("[%s]= %s",a.GetBuffer(),b.GetBuffer()); + printf("\n"); + } + printf("\n"); + return sReturn; +} +/*****************************************************************************/ +void Export::SetLanguages( std::vector val ){ +/*****************************************************************************/ + aLanguages = val; + isInitialized = true; +} +/*****************************************************************************/ +std::vector Export::GetLanguages(){ +/*****************************************************************************/ + return aLanguages; +} +/*****************************************************************************/ +std::vector Export::GetForcedLanguages(){ +/*****************************************************************************/ + return aForcedLanguages; +} +std::vector Export::aLanguages = std::vector(); +std::vector Export::aForcedLanguages = std::vector(); + + +/*****************************************************************************/ +void Export::QuotHTMLXRM( ByteString &rString ) +/*****************************************************************************/ +{ + ByteString sReturn; + //BOOL bBreak = FALSE; + for ( USHORT i = 0; i < rString.Len(); i++ ) { + ByteString sTemp = rString.Copy( i ); + if ( sTemp.Search( ""; + i++; + } + } + + if ( i < rString.Len()) { + switch ( rString.GetChar( i )) { + case '<': + if( i+2 < rString.Len() && + (rString.GetChar( i+1 ) == 'b' || rString.GetChar( i+1 ) == 'B') && + rString.GetChar( i+2 ) == '>' ) + { + sReturn +=""; + i += 2; + } + else if( i+3 < rString.Len() && + rString.GetChar( i+1 ) == '/' && + (rString.GetChar( i+2 ) == 'b' || rString.GetChar( i+2 ) == 'B') && + rString.GetChar( i+3 ) == '>' ) + { + sReturn +=""; + i += 3; + } + else + sReturn += "<"; + break; + + case '>': + sReturn += ">"; + break; + + case '\"': + sReturn += """; + break; + + case '\'': + sReturn += "'"; + break; + + case '&': + if ((( i + 4 ) < rString.Len()) && + ( rString.Copy( i, 5 ) == "&" )) + sReturn += rString.GetChar( i ); + else + sReturn += "&"; + break; + + default: + sReturn += rString.GetChar( i ); + break; + } + } + } + rString = sReturn; +} +/*****************************************************************************/ +void Export::QuotHTML( ByteString &rString ) +/*****************************************************************************/ +{ + ByteString sReturn; + for ( USHORT i = 0; i < rString.Len(); i++ ) { + ByteString sTemp = rString.Copy( i ); + if ( sTemp.Search( ""; + i++; + } + } + if ( i < rString.Len()) { + switch ( rString.GetChar( i )) { + case '<': + sReturn += "<"; + break; + + case '>': + sReturn += ">"; + break; + + case '\"': + sReturn += """; + break; + + case '\'': + sReturn += "'"; + break; + + case '&': + if ((( i + 4 ) < rString.Len()) && + ( rString.Copy( i, 5 ) == "&" )) + sReturn += rString.GetChar( i ); + else + sReturn += "&"; + break; + + default: + sReturn += rString.GetChar( i ); + break; + } + } + } + rString = sReturn; +} + +void Export::RemoveUTF8ByteOrderMarker( ByteString &rString ){ + if( hasUTF8ByteOrderMarker( rString ) ) + rString.Erase( 0 , 3 ); +} + +bool Export::hasUTF8ByteOrderMarker( const ByteString &rString ){ + // Byte order marker signature + + const unsigned char c1 = 0xEF; + const unsigned char c2 = 0xBB; + const unsigned char c3 = 0xBF; + + const char bom[ 3 ] = { c1 , c2 , c3 }; + + return rString.Len() >= 3 && + rString.GetChar( 0 ) == bom[ 0 ] && + rString.GetChar( 1 ) == bom[ 1 ] && + rString.GetChar( 2 ) == bom[ 2 ] ; +} +bool Export::fileHasUTF8ByteOrderMarker( const ByteString &rString ){ + SvFileStream aFileIn( String( rString , RTL_TEXTENCODING_ASCII_US ) , STREAM_READ ); + ByteString sLine; + if( !aFileIn.IsEof() ) { + aFileIn.ReadLine( sLine ); + if( aFileIn.IsOpen() ) aFileIn.Close(); + return hasUTF8ByteOrderMarker( sLine ); + } + if( aFileIn.IsOpen() ) aFileIn.Close(); + return false; +} +void Export::RemoveUTF8ByteOrderMarkerFromFile( const ByteString &rFilename ){ + SvFileStream aFileIn( String( rFilename , RTL_TEXTENCODING_ASCII_US ) , STREAM_READ ); + ByteString sLine; + if( !aFileIn.IsEof() ) { + aFileIn.ReadLine( sLine ); + // Test header + if( hasUTF8ByteOrderMarker( sLine ) ){ + //cout << "UTF8 Header found!\n"; + DirEntry aTempFile = Export::GetTempFile(); + ByteString sTempFile = ByteString( aTempFile.GetFull() , RTL_TEXTENCODING_ASCII_US ); + SvFileStream aNewFile( String( sTempFile , RTL_TEXTENCODING_ASCII_US ) , STREAM_WRITE ); + // Remove header + RemoveUTF8ByteOrderMarker( sLine ); + //cout << "Copy stripped stuff to " << sTempFile.GetBuffer() << endl; + aNewFile.WriteLine( sLine ); + // Copy the rest + while( !aFileIn.IsEof() ){ + aFileIn.ReadLine( sLine ); + aNewFile.WriteLine( sLine ); + } + if( aFileIn.IsOpen() ) aFileIn.Close(); + if( aNewFile.IsOpen() ) aNewFile.Close(); + DirEntry aEntry( rFilename.GetBuffer() ); + //cout << "Removing file " << rFilename.GetBuffer() << "\n"; + aEntry.Kill(); + //cout << "Renaming file " << sTempFile.GetBuffer() << " to " << rFilename.GetBuffer() << "\n"; + DirEntry( sTempFile ).MoveTo( DirEntry( rFilename.GetBuffer() ) ); + } + } + if( aFileIn.IsOpen() ) aFileIn.Close(); +} + +// Merge it into source code! +//bool Export::isMergingGermanAllowed( const ByteString& rPrj ){ +// (void) rPrj; +// return true; +/* static ByteStringBoolHashMap aHash; + + if( aHash.find( rPrj ) != aHash.end() ){ + return aHash[ rPrj ]; + } + + ByteString sFile = Export::GetEnv( "SRC_ROOT" ) ; + sFile.Append("/"); + sFile.Append( rPrj ); + sFile.Append("/prj/l10n"); +#if defined(WNT) || defined(OS2) + sFile.SearchAndReplaceAll('/','\\'); +#endif + DirEntry aFlagfile( sFile ); + + aHash[ rPrj ] = !aFlagfile.Exists(); + return aHash[ rPrj ];*/ +//} +bool Export::CopyFile( const ByteString& source , const ByteString& dest ) +{ +// cout << "CopyFile( " << source.GetBuffer() << " , " << dest.GetBuffer() << " )\n"; + const int BUFFERSIZE = 8192; + char buf[ BUFFERSIZE ]; + + FILE* IN_FILE = fopen( source.GetBuffer() , "r" ); + FILE* OUT_FILE = fopen( dest.GetBuffer() , "w" ); + + if( IN_FILE == NULL ) + { + cerr << "Export::CopyFile WARNING: Could not open " << source.GetBuffer() << "\n"; + return false; + } + if( OUT_FILE == NULL ) + { + cerr << "Export::CopyFile WARNING: Could not open/create " << dest.GetBuffer() << " for writing\n"; + return false; + } + + while( fgets( buf , BUFFERSIZE , IN_FILE ) != NULL ) + { + if( fputs( buf , OUT_FILE ) == EOF ) + { + cerr << "Export::CopyFile WARNING: Write problems " << source.GetBuffer() << "\n"; + fclose( IN_FILE ); + fclose( OUT_FILE ); + return false; + } + } + if( ferror( IN_FILE ) ) + { + cerr << "Export::CopyFile WARNING: Read problems " << dest.GetBuffer() << "\n"; + fclose( IN_FILE ); + fclose( OUT_FILE ); + return false; + } + fclose ( IN_FILE ); + fclose ( OUT_FILE ); + + return true; +} + +/*****************************************************************************/ +void Export::UnquotHTML( ByteString &rString ) +/*****************************************************************************/ +{ + ByteString sReturn; + while ( rString.Len()) { + if ( rString.Copy( 0, 5 ) == "&" ) { + sReturn += "&"; + rString.Erase( 0, 5 ); + } + else if ( rString.Copy( 0, 4 ) == "<" ) { + sReturn += "<"; + rString.Erase( 0, 4 ); + } + else if ( rString.Copy( 0, 4 ) == ">" ) { + sReturn += ">"; + rString.Erase( 0, 4 ); + } + else if ( rString.Copy( 0, 6 ) == """ ) { + sReturn += "\""; + rString.Erase( 0, 6 ); + } + else if ( rString.Copy( 0, 6 ) == "'" ) { + sReturn += "\'"; + rString.Erase( 0, 6 ); + } + else { + sReturn += rString.GetChar( 0 ); + rString.Erase( 0, 1 ); + } + } + rString = sReturn; +} +bool Export::isSourceLanguage( const ByteString &sLanguage ) +{ + return !isAllowed( sLanguage ); +} +bool Export::isAllowed( const ByteString &sLanguage ){ + return ! ( sLanguage.EqualsIgnoreCaseAscii("en-US") ); +} +/*****************************************************************************/ +bool Export::LanguageAllowed( const ByteString &nLanguage ) +/*****************************************************************************/ +{ + return std::find( aLanguages.begin() , aLanguages.end() , nLanguage ) != aLanguages.end(); +} + +bool Export::isInitialized = false; + +/*****************************************************************************/ +void Export::InitLanguages( bool bMergeMode ){ +/*****************************************************************************/ + if( !isInitialized ){ + ByteString sTmp; + ByteStringBoolHashMap aEnvLangs; + for ( USHORT x = 0; x < sLanguages.GetTokenCount( ',' ); x++ ){ + sTmp = sLanguages.GetToken( x, ',' ).GetToken( 0, '=' ); + sTmp.EraseLeadingAndTrailingChars(); + if( bMergeMode && !isAllowed( sTmp ) ){} + else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) ){ + aLanguages.push_back( sTmp ); + } + } + InitForcedLanguages( bMergeMode ); + isInitialized = true; + } +} +/*****************************************************************************/ +void Export::InitForcedLanguages( bool bMergeMode ){ +/*****************************************************************************/ + ByteString sTmp; + ByteStringBoolHashMap aEnvLangs; + for ( USHORT x = 0; x < sForcedLanguages.GetTokenCount( ',' ); x++ ){ + sTmp = sForcedLanguages.GetToken( x, ',' ).GetToken( 0, '=' ); + sTmp.EraseLeadingAndTrailingChars(); + if( bMergeMode && isAllowed( sTmp ) ){} + else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) ) + aForcedLanguages.push_back( sTmp ); + } +} + +/*****************************************************************************/ +ByteString Export::GetFallbackLanguage( const ByteString nLanguage ) +/*****************************************************************************/ +{ + ByteString sFallback=nLanguage; + GetIsoFallback( sFallback ); + return sFallback; +} + +void Export::replaceEncoding( ByteString& rString ) +{ +// ™ -> \u2122 + + for( xub_StrLen idx = 0; idx <= rString.Len()-8 ; idx++ ) + { + if( rString.GetChar( idx ) == '&' && + rString.GetChar( idx+1 ) == '#' && + rString.GetChar( idx+2 ) == 'x' && + rString.GetChar( idx+7 ) == ';' ) + { + ByteString sTmp = rString.Copy( 0 , idx ); + sTmp.Append( "\\u" ); + sTmp.Append( rString.GetChar( idx+3 ) ); + sTmp.Append( rString.GetChar( idx+4 ) ); + sTmp.Append( rString.GetChar( idx+5 ) ); + sTmp.Append( rString.GetChar( idx+6 ) ); + sTmp.Append( rString.Copy( idx+8 , rString.Len() ) ); + rString = sTmp; + } + } +} + +/*****************************************************************************/ +void Export::FillInFallbacks( ResData *pResData ) +/*****************************************************************************/ +{ + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + if( isAllowed( sCur ) ){ + ByteString nFallbackIndex = GetFallbackLanguage( sCur ); + if( nFallbackIndex.Len() ){ + if ( !pResData->sText[ sCur ].Len()) + pResData->sText[ sCur ] = + pResData->sText[ nFallbackIndex ]; + + if ( !pResData->sHelpText[ sCur ].Len()) + pResData->sHelpText[ sCur ] = + pResData->sHelpText[ nFallbackIndex ]; + + if ( !pResData->sQuickHelpText[ sCur ].Len()) + pResData->sQuickHelpText[ sCur ] = + pResData->sQuickHelpText[ nFallbackIndex ]; + + if ( !pResData->sTitle[ sCur ].Len()) + pResData->sTitle[ sCur ] = + pResData->sTitle[ nFallbackIndex ]; + + if ( pResData->pStringList ) + FillInListFallbacks( + pResData->pStringList, sCur, nFallbackIndex ); + + if ( pResData->pPairedList ) + FillInListFallbacks( + pResData->pPairedList, sCur, nFallbackIndex ); + + if ( pResData->pFilterList ) + FillInListFallbacks( + pResData->pFilterList, sCur, nFallbackIndex ); + + if ( pResData->pItemList ) + FillInListFallbacks( + pResData->pItemList, sCur, nFallbackIndex ); + + if ( pResData->pUIEntries ) + FillInListFallbacks( + pResData->pUIEntries, sCur, nFallbackIndex ); + } + } + } +} + +/*****************************************************************************/ +void Export::FillInListFallbacks( + ExportList *pList, const ByteString &nSource, const ByteString &nFallback ) +/*****************************************************************************/ +{ + + for ( ULONG i = 0; i < pList->Count(); i++ ) { + ExportListEntry *pEntry = pList->GetObject( i ); + if ( !( *pEntry )[ nSource ].Len()){ + ( *pEntry )[ nSource ] = ( *pEntry )[ nFallback ]; + ByteString x = ( *pEntry )[ nSource ]; + ByteString y = ( *pEntry )[ nFallback ]; + } + } +} + +/*****************************************************************************/ +ByteString Export::GetTimeStamp() +/*****************************************************************************/ +{ +// return "xx.xx.xx"; + char buf[20]; + Time aTime; + + snprintf(buf, sizeof(buf), "%8d %02d:%02d:%02d", int(Date().GetDate()), + int(aTime.GetHour()), int(aTime.GetMin()), int(aTime.GetSec())); + return ByteString(buf); +} + +/*****************************************************************************/ +BOOL Export::ConvertLineEnds( + ByteString sSource, ByteString sDestination ) +/*****************************************************************************/ +{ + String sSourceFile( sSource, RTL_TEXTENCODING_ASCII_US ); + String sDestinationFile( sDestination, RTL_TEXTENCODING_ASCII_US ); + + SvFileStream aSource( sSourceFile, STREAM_READ ); + if ( !aSource.IsOpen()) + return FALSE; + SvFileStream aDestination( sDestinationFile, STREAM_STD_WRITE | STREAM_TRUNC ); + if ( !aDestination.IsOpen()) { + aSource.Close(); + return FALSE; + } + + ByteString sLine; + + while ( !aSource.IsEof()) { + aSource.ReadLine( sLine ); + if ( !aSource.IsEof()) { + sLine.EraseAllChars( '\r' ); + aDestination.WriteLine( sLine ); + } + else + aDestination.WriteByteString( sLine ); + } + + aSource.Close(); + aDestination.Close(); + + return TRUE; +} + +/*****************************************************************************/ +ByteString Export::GetNativeFile( ByteString sSource ) +/*****************************************************************************/ +{ + DirEntry aTemp( GetTempFile()); + ByteString sReturn( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + for ( USHORT i = 0; i < 10; i++ ) + if ( ConvertLineEnds( sSource, sReturn )) + return sReturn; + + return ""; +} + +const char* Export::GetEnv( const char *pVar ) +{ + char *pRet = getenv( pVar ); + if ( !pRet ) + pRet = 0; + return pRet; +} + + +int Export::getCurrentDirectory( rtl::OUString& base_fqurl_out, rtl::OUString& base_out ) +{ + DirEntry aDir("."); + aDir.ToAbs(); + base_out = rtl::OUString( aDir.GetFull() ); + return osl::File::getFileURLFromSystemPath( base_out , base_fqurl_out ); +} + +void Export::getCurrentDir( string& dir ) +{ + char buffer[64000]; + if( getcwd( buffer , sizeof( buffer ) ) == 0 ){ + cerr << "Error: getcwd failed!\n"; + exit( -1 ); + } + dir = string( buffer ); +} + + +// Stolen from sal/osl/unx/tempfile.c + +#define RAND_NAME_LENGTH 6 + +void Export::getRandomName( const ByteString& sPrefix , ByteString& sRandStr , const ByteString& sPostfix ) +{ + static const char LETTERS[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + static const int COUNT_OF_LETTERS = sizeof(LETTERS)/sizeof(LETTERS[0]) - 1; + sRandStr.Append( sPrefix ); + + static sal_uInt64 value; + char buffer[RAND_NAME_LENGTH]; + + TimeValue tv; + sal_uInt64 v; + int i; + + osl_getSystemTime( &tv ); + oslProcessInfo proInfo; + osl_getProcessInfo( 0 , osl_Process_IDENTIFIER , &proInfo ); + + value += ((sal_uInt64) ( tv.Nanosec / 1000 ) << 16) ^ ( tv.Nanosec / 1000 ) ^ proInfo.Ident; + + v = value; + + for (i = 0; i < RAND_NAME_LENGTH; i++) + { + buffer[i] = LETTERS[v % COUNT_OF_LETTERS]; + v /= COUNT_OF_LETTERS; + } + + sRandStr.Append( buffer , RAND_NAME_LENGTH ); + sRandStr.Append( sPostfix ); +} + +void Export::getRandomName( ByteString& sRandStr ) +{ + const ByteString sEmpty; + getRandomName( sEmpty , sRandStr , sEmpty ); +} + +/*****************************************************************************/ +DirEntry Export::GetTempFile() +/*****************************************************************************/ +{ +#if defined(WNT) || defined(OS2) + String sTempDir( Export::GetEnv( "TEMP" ), RTL_TEXTENCODING_ASCII_US ); +#else + String sTempDir( String::CreateFromAscii( "/tmp" )); +#endif + rtl::OUString* sTempFilename = new rtl::OUString(); + + // Create a temp file + int nRC = osl::FileBase::createTempFile( 0 , 0 , sTempFilename ); + if( nRC ) printf(" osl::FileBase::createTempFile RC = %d",nRC); + + String strTmp( *sTempFilename ); + + INetURLObject::DecodeMechanism eMechanism = INetURLObject::DECODE_TO_IURI; + String sDecodedStr = INetURLObject::decode( strTmp , '%' , eMechanism ); + ByteString sTmp( sDecodedStr , RTL_TEXTENCODING_UTF8 ); + +#if defined(WNT) || defined(OS2) + sTmp.SearchAndReplace("file:///",""); + sTmp.SearchAndReplaceAll('/','\\'); +#else + // Set file permission to 644 + const sal_uInt64 nPerm = osl_File_Attribute_OwnRead | osl_File_Attribute_OwnWrite | + osl_File_Attribute_GrpRead | osl_File_Attribute_OthRead ; + + nRC = osl::File::setAttributes( *sTempFilename , nPerm ); + if( nRC ) printf(" osl::File::setAttributes RC = %d",nRC); + + sTmp.SearchAndReplace("file://",""); +#endif + DirEntry aDirEntry( sTmp ); + delete sTempFilename; + return aDirEntry; +} diff --git a/l10ntools/source/file.cxx b/l10ntools/source/file.cxx new file mode 100644 index 000000000000..43ce4c757d54 --- /dev/null +++ b/l10ntools/source/file.cxx @@ -0,0 +1,58 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: file.cxx,v $ + * $Revision: 1.6 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include + +namespace transex +{ + +File::File( const rtl::OUString sFile ) +{ + sFileName = sFile; +} + +File::File( const rtl::OUString sFullPath , const rtl::OUString sFile ) +{ + sFileName = sFile; + sFullName = sFullPath; +} + +bool File::lessFile ( const File& rKey1, const File& rKey2 ) +{ + rtl::OUString sName1( ( static_cast< File >( rKey1 ) ).getFileName() ); + rtl::OUString sName2( ( static_cast< File >( rKey2 ) ).getFileName() ); + + return sName1.compareTo( sName2 ) < 0 ; +} + +} diff --git a/l10ntools/source/filter/merge/FCFGMerge.cfg b/l10ntools/source/filter/merge/FCFGMerge.cfg new file mode 100644 index 000000000000..46fcccafe7e4 --- /dev/null +++ b/l10ntools/source/filter/merge/FCFGMerge.cfg @@ -0,0 +1,125 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: FCFGMerge.cfg,v $ +# +# $Revision: 1.5 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +#************************************************ +# Specify the verbose mode of this tool. +# 1 = show errors only +# 2 = show errors/warnings (default) +# 3 = show errors/warnings and some generic infos +# 4 = show anything (including detailed infos) +# +# [OPTIONAL] +#************************************************ + +loglevel = 2 + +#************************************************ +# This extension is used for all XML files. It doesnt +# matter if its used for reading fragments or writing +# XML packages. +# Must be given without any additional signes like "." +# or "*."! +# +# [REQUIRED] +#************************************************ + +extension_xcu=xcu + +#************************************************ +# This extension is used for all Package files. It doesnt +# matter if its used for reading such files or writing +# it. +# Must be given without any additional signes like "." +# or "*."! +# +# [REQUIRED] +#************************************************ + +extension_pkg=pkg + +#************************************************ +# These values are used to generate a correct XML +# header. +# Note: The property "xmlpackage" must be specified +# via command line. There exists more then one +# possible value. +# +# [REQUIRED] +#************************************************ + +xmlversion = 1.0 +xmlencoding = UTF-8 +xmlpath = org.openoffice.TypeDetection +#xmlpackage = + +#************************************************ +# These values are used to name the configuration +# sets inside the generated XCM file for different +# item groups like e.g. types, filters etcpp. +# +# [REQUIRED] +#************************************************ + +setname_types = Types +setname_filters = Filters +setname_frameloaders = FrameLoaders +setname_contenthandlers = ContentHandlers + +subdir_types = types +subdir_filters = filters +subdir_frameloaders = frameloaders +subdir_contenthandlers = contenthandlers + +#************************************************ +# This delimiter is used to split every +# item list of the package configuration files +# (which are temp. created by the make proccess) +# into its tokens. +# +# [REQUIRED] +#************************************************ +delimiter=, + +#************************************************ +# Enable/disable removing of leading/trailing withespaces +# during splitting stringlists. +# +# [REQUIRED] +#************************************************ +trim=true + +#************************************************ +# Enable/disable removing of leading/trailing "-signs +# during splitting stringlists. +# +# [REQUIRED] +#************************************************ +decode=false diff --git a/l10ntools/source/filter/merge/FCFGMerge.java b/l10ntools/source/filter/merge/FCFGMerge.java new file mode 100644 index 000000000000..7fbfa8a0c986 --- /dev/null +++ b/l10ntools/source/filter/merge/FCFGMerge.java @@ -0,0 +1,131 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: FCFGMerge.java,v $ + * $Revision: 1.5 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.filter.config.tools.merge; + +//_______________________________________________ + +import java.lang.*; +import java.util.*; +import java.io.*; +import com.sun.star.filter.config.tools.utils.*; + +//_______________________________________________ + +/** + * Its a simple command line tool, which can merge different XML fragments + * together. Such fragments must exist as files on disk, will be moved into + * one file together on disk. + * + * + */ +public class FCFGMerge +{ + //___________________________________________ + // const + + private static final java.lang.String CFGFILE = "com/sun/star/filter/config/tools/merge/FCFGMerge.cfg"; + private static final java.lang.String PROP_LOGLEVEL = "loglevel"; + + //___________________________________________ + // main + + public static void main(java.lang.String[] sCmdLine) + { + FCFGMerge.printCopyright(); + + // create log object in default mode "WARNINGS" + // If a command line parameter indicates another + // level - change it! + Logger aLog = new Logger(); + + try + { + // merge config file and overwrite properties + // via command line + ConfigHelper aCfg = null; + aCfg = new ConfigHelper(CFGFILE, sCmdLine); + + // update log level + int nLogLevel = aCfg.getInt(PROP_LOGLEVEL, Logger.LEVEL_WARNINGS); + aLog = new Logger(nLogLevel); + + // help requested? + if (aCfg.isHelp()) + { + FCFGMerge.printHelp(); + System.exit(-1); + } + + // create new merge object and start operation + Merger aMerger = new Merger(aCfg, aLog); + aMerger.merge(); + } + catch(java.lang.Throwable ex) + { + aLog.setException(ex); + System.exit(-1); + } + + System.exit(0); + } + + //___________________________________________ + + /** prints out a copyright message on stdout. + */ + private static void printCopyright() + { + java.lang.StringBuffer sOut = new java.lang.StringBuffer(256); + sOut.append("FCFGMerge\n"); + sOut.append("Copyright: 2003 by Sun Microsystems, Inc.\n"); + sOut.append("All Rights Reserved.\n"); + System.out.println(sOut.toString()); + } + + //___________________________________________ + + /** prints out a help message on stdout. + */ + private static void printHelp() + { + java.lang.StringBuffer sOut = new java.lang.StringBuffer(256); + sOut.append("____________________________________________________________\n"); + sOut.append("usage: FCFGMerge cfg=\n" ); + sOut.append("parameters:\n" ); + sOut.append("\tcfg=\n" ); + sOut.append("\t\tmust point to a system file, which contains\n" ); + sOut.append("\t\tall neccessary configuration data for the merge process.\n"); + sOut.append("\n\tFurther cou can specify every parameter allowed in the\n" ); + sOut.append("\n\tconfig file as command line parameter too, to overwrite\n" ); + sOut.append("\n\tthe value from the file.\n" ); + System.out.println(sOut.toString()); + } +} diff --git a/l10ntools/source/filter/merge/Manifest.mf b/l10ntools/source/filter/merge/Manifest.mf new file mode 100644 index 000000000000..1337eaf4d39a --- /dev/null +++ b/l10ntools/source/filter/merge/Manifest.mf @@ -0,0 +1 @@ +Main-Class: com.sun.star.filter.config.tools.merge.FCFGMerge diff --git a/l10ntools/source/filter/merge/Merger.java b/l10ntools/source/filter/merge/Merger.java new file mode 100644 index 000000000000..0bf11fc42fbf --- /dev/null +++ b/l10ntools/source/filter/merge/Merger.java @@ -0,0 +1,364 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Merger.java,v $ + * $Revision: 1.8 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.filter.config.tools.merge; + +//_______________________________________________ + +import java.lang.*; +import java.util.*; +import java.io.*; +import com.sun.star.filter.config.tools.utils.*; + +//_______________________________________________ + +/** can merge different xml fragments together. + * + * + */ +public class Merger +{ + //___________________________________________ + // const + + private static final java.lang.String PROP_XMLVERSION = "xmlversion" ; // <= global cfg file + private static final java.lang.String PROP_XMLENCODING = "xmlencoding" ; // <= global cfg file + private static final java.lang.String PROP_XMLPATH = "xmlpath" ; // <= global cfg file + private static final java.lang.String PROP_XMLPACKAGE = "xmlpackage" ; // <= global cfg file + + private static final java.lang.String PROP_SETNAME_TYPES = "setname_types" ; // <= global cfg file + private static final java.lang.String PROP_SETNAME_FILTERS = "setname_filters" ; // <= global cfg file + private static final java.lang.String PROP_SETNAME_LOADERS = "setname_frameloaders" ; // <= global cfg file + private static final java.lang.String PROP_SETNAME_HANDLERS = "setname_contenthandlers" ; // <= global cfg file + + private static final java.lang.String PROP_SUBDIR_TYPES = "subdir_types" ; // <= global cfg file + private static final java.lang.String PROP_SUBDIR_FILTERS = "subdir_filters" ; // <= global cfg file + private static final java.lang.String PROP_SUBDIR_LOADERS = "subdir_frameloaders" ; // <= global cfg file + private static final java.lang.String PROP_SUBDIR_HANDLERS = "subdir_contenthandlers" ; // <= global cfg file + + private static final java.lang.String PROP_EXTENSION_XCU = "extension_xcu" ; // <= global cfg file + private static final java.lang.String PROP_EXTENSION_PKG = "extension_pkg" ; // <= global cfg file + + private static final java.lang.String PROP_DELIMITER = "delimiter" ; // <= global cfg file + private static final java.lang.String PROP_TRIM = "trim" ; // <= global cfg file + private static final java.lang.String PROP_DECODE = "decode" ; // <= global cfg file + + private static final java.lang.String PROP_FRAGMENTSDIR = "fragmentsdir" ; // <= cmdline + private static final java.lang.String PROP_TEMPDIR = "tempdir" ; // <= cmdline + private static final java.lang.String PROP_OUTDIR = "outdir" ; // <= cmdline + private static final java.lang.String PROP_PKG = "pkg" ; // <= cmdline + private static final java.lang.String PROP_DEBUG = "debug" ; // <= cmdline + + private static final java.lang.String PROP_TCFG = "tcfg" ; // <= cmdline + private static final java.lang.String PROP_FCFG = "fcfg" ; // <= cmdline + private static final java.lang.String PROP_LCFG = "lcfg" ; // <= cmdline + private static final java.lang.String PROP_CCFG = "ccfg" ; // <= cmdline + private static final java.lang.String PROP_LANGUAGEPACK = "languagepack" ; // <= cmdline + + private static final java.lang.String PROP_ITEMS = "items" ; // <= pkg cfg files! + + //___________________________________________ + // member + + //------------------------------------------- + /** TODO */ + private ConfigHelper m_aCfg; + + //------------------------------------------- + /** TODO */ + private Logger m_aLog; + + //------------------------------------------- + /** TODO */ + private java.io.File m_aFragmentsDir; + + //------------------------------------------- + /** TODO */ + private java.io.File m_aTempDir; + + //------------------------------------------- + /** TODO */ + private java.io.File m_aOutDir; + + //------------------------------------------- + /** TODO */ + private java.util.Vector m_lTypes; + private java.util.Vector m_lFilters; + private java.util.Vector m_lLoaders; + private java.util.Vector m_lHandlers; + + //___________________________________________ + // interface + + //------------------------------------------- + /** initialize a new instance of this class and + * try to get all needed resources from the config module. + * + * @param aCfg + * provides access to all values of the global + * config file and to the command line. + * + * @param aLog + * can be used to print out log informations. + */ + public Merger(ConfigHelper aCfg, + Logger aLog) + throws java.lang.Exception + { + m_aCfg = aCfg; + m_aLog = aLog; + + m_aFragmentsDir = new java.io.File(m_aCfg.getString(PROP_FRAGMENTSDIR)); + m_aTempDir = new java.io.File(m_aCfg.getString(PROP_TEMPDIR )); +// m_aOutDir = new java.io.File(m_aCfg.getString(PROP_OUTDIR )); + + java.lang.String sDelimiter = m_aCfg.getString(PROP_DELIMITER); + boolean bTrim = m_aCfg.getBoolean(PROP_TRIM); + boolean bDecode = m_aCfg.getBoolean(PROP_DECODE); + + try + { + ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_TCFG), null); + m_lTypes = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); + } + catch(java.util.NoSuchElementException ex1) + { + m_lTypes = new java.util.Vector(); + //m_aLog.setWarning("Fragment list of types is missing. Parameter \"items\" seems to be invalid."); + } + + try + { + ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_FCFG), null); + m_lFilters = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); + } + catch(java.util.NoSuchElementException ex1) + { + m_lFilters = new java.util.Vector(); + //m_aLog.setWarning("Fragment list of filters is missing. Parameter \"items\" seems to be invalid."); + } + + try + { + ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_LCFG), null); + m_lLoaders = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); + } + catch(java.util.NoSuchElementException ex1) + { + m_lLoaders = new java.util.Vector(); + //m_aLog.setWarning("Fragment list of frame loader objects is missing. Parameter \"items\" seems to be invalid."); + } + + try + { + ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_CCFG), null); + m_lHandlers = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); + } + catch(java.util.NoSuchElementException ex1) + { + m_lHandlers = new java.util.Vector(); + //m_aLog.setWarning("Fragment list of content handler objects is missing. Parameter \"items\" seems to be invalid."); + } + } + + //------------------------------------------- + /** TODO */ + public synchronized void merge() + throws java.lang.Exception + { + java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(1000000); + java.lang.String sPackage = m_aCfg.getString(PROP_PKG); + + m_aLog.setGlobalInfo("create package \""+sPackage+"\" ..."); + m_aLog.setDetailedInfo("generate package header ... "); + + sBuffer.append( + XMLHelper.generateHeader( + m_aCfg.getString (PROP_XMLVERSION ), + m_aCfg.getString (PROP_XMLENCODING ), + m_aCfg.getString (PROP_XMLPATH ), + m_aCfg.getString (PROP_XMLPACKAGE ), + m_aCfg.getBoolean(PROP_LANGUAGEPACK, false))); + + // counts all transfered fragments + // Can be used later to decide, if a generated package file + // contains "nothing"! + int nItemCount = 0; + + for (int i=0; i<4; ++i) + { + java.lang.String sSetName = null; + java.lang.String sSubDir = null; + java.util.Vector lFragments = null; + + try + { + switch(i) + { + case 0: // types + { + m_aLog.setDetailedInfo("generate set for types ... "); + sSetName = m_aCfg.getString(PROP_SETNAME_TYPES); + sSubDir = m_aCfg.getString(PROP_SUBDIR_TYPES ); + lFragments = m_lTypes; + } + break; + + case 1: // filters + { + m_aLog.setDetailedInfo("generate set for filter ... "); + sSetName = m_aCfg.getString(PROP_SETNAME_FILTERS); + sSubDir = m_aCfg.getString(PROP_SUBDIR_FILTERS ); + lFragments = m_lFilters; + } + break; + + case 2: // loaders + { + m_aLog.setDetailedInfo("generate set for frame loader ... "); + sSetName = m_aCfg.getString(PROP_SETNAME_LOADERS); + sSubDir = m_aCfg.getString(PROP_SUBDIR_LOADERS ); + lFragments = m_lLoaders; + } + break; + + case 3: // handlers + { + m_aLog.setDetailedInfo("generate set for content handler ... "); + sSetName = m_aCfg.getString(PROP_SETNAME_HANDLERS); + sSubDir = m_aCfg.getString(PROP_SUBDIR_HANDLERS ); + lFragments = m_lHandlers; + } + break; + } + + nItemCount += lFragments.size(); + + getFragments( + new java.io.File(m_aFragmentsDir, sSubDir), + sSetName, + lFragments, + 1, + sBuffer); + } + catch(java.util.NoSuchElementException exIgnore) + { continue; } + } + + m_aLog.setDetailedInfo("generate package footer ... "); + sBuffer.append(XMLHelper.generateFooter()); + + // Attention! + // If the package seem to be empty, it make no sense to generate a corresponding + // xml file. We should suppress writing of this file on disk completly ... + if (nItemCount < 1) + { + m_aLog.setWarning("Package is empty and will not result into a xml file on disk!? Please check configuration file."); + return; + } + m_aLog.setGlobalInfo("package contains "+nItemCount+" items"); + + java.io.File aPackage = new File(sPackage); + m_aLog.setGlobalInfo("write temp package \""+aPackage.getPath()); // TODO encoding must be readed from the configuration + FileHelper.writeEncodedBufferToFile(aPackage, "UTF-8", false, sBuffer); // check for success is done inside this method! + } + + //------------------------------------------- + /** TODO */ + private void getFragments(java.io.File aDir , + java.lang.String sSetName , + java.util.Vector lFragments , + int nPrettyTabs, + java.lang.StringBuffer sBuffer ) + throws java.lang.Exception + { + if (lFragments.size()<1) + { + m_aLog.setWarning("List of fragments is empty!? Will be ignored ..."); + return; + } + + java.util.Enumeration pFragments = lFragments.elements(); + java.lang.String sExtXcu = m_aCfg.getString(PROP_EXTENSION_XCU); + + for (int tabs=0; tabs\n"); + ++nPrettyTabs; + + // special mode for generating language packs. + // In such case we must live with some missing fragment files. + // Reason behind; Not all filters are realy localized. + // But we dont use a different fragment list. We try to locate + // any fragment file in its language-pack version ... + boolean bHandleLanguagePacks = m_aCfg.getBoolean(PROP_LANGUAGEPACK, false); + boolean bDebug = m_aCfg.getBoolean(PROP_DEBUG , false); + java.lang.String sEncoding = "UTF-8"; + if (bDebug) + sEncoding = "UTF-8Special"; + + while(pFragments.hasMoreElements()) + { + java.lang.String sFragment = (java.lang.String)pFragments.nextElement(); + java.io.File aFragment = new java.io.File(aDir, sFragment+"."+sExtXcu); + + // handle simple files only and check for existence! + if (!aFragment.exists()) + { + if (bHandleLanguagePacks) + { + m_aLog.setWarning("language fragment \""+aFragment.getPath()+"\" does not exist. Will be ignored."); + continue; + } + else + throw new java.io.IOException("fragment \""+aFragment.getPath()+"\" does not exists."); + } + + if (!aFragment.isFile()) + { + m_aLog.setWarning("fragment \""+aFragment.getPath()+"\" seem to be not a valid file."); + continue; + } + + // copy file content of original fragment + // Note: A FileNotFoundException will be thrown automaticly by the + // used reader objects. Let it break this method too. Our calli is interested + // on such errors :-) + m_aLog.setDetailedInfo("merge fragment \""+aFragment.getPath()+"\" ..."); + FileHelper.readEncodedBufferFromFile(aFragment, sEncoding, sBuffer); + + sBuffer.append("\n"); + } + + --nPrettyTabs; + for (int tabs=0; tabs\n"); + } +} diff --git a/l10ntools/source/filter/merge/makefile.mk b/l10ntools/source/filter/merge/makefile.mk new file mode 100644 index 000000000000..510ec3202bb4 --- /dev/null +++ b/l10ntools/source/filter/merge/makefile.mk @@ -0,0 +1,96 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.9.102.1 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ = ..$/..$/.. +TARGET = FCFGMerge +PRJNAME = l10ntools +PACKAGE = com$/sun$/star$/filter$/config$/tools$/merge + +# --- Settings ----------------------------------------------------- + +.INCLUDE: settings.mk + +#----- compile .java files ----------------------------------------- +#.IF "$(L10N_framework)"=="" + +OWNCOPY = \ + $(MISC)$/$(TARGET)_copied.done + +#JARFILES = \ +# ridl.jar \ +# unoil.jar \ +# jurt.jar \ +# juh.jar \ +# java_uno.jar + +CFGFILES = \ + FCFGMerge.cfg + +JAVACLASSFILES = \ + $(CLASSDIR)$/$(PACKAGE)$/Merger.class \ + $(CLASSDIR)$/$(PACKAGE)$/FCFGMerge.class + +CUSTOMMANIFESTFILE = \ + Manifest.mf + +MAXLINELENGTH = 100000 + +#----- make a jar from compiled files ------------------------------ + +JARCLASSDIRS = \ + com$/sun$/star$/filter$/config$/tools$/utils \ + com$/sun$/star$/filter$/config$/tools$/merge + +JARTARGET = $(TARGET).jar + +JARCOMPRESS = TRUE + +# --- targets ----------------------------------------------------- + +.INCLUDE : target.mk + +.IF "$(SOLAR_JAVA)" != "" || "$(GUI)"=="OS2" +ALLTAR : $(OWNCOPY) + +.IF "$(JARTARGETN)" != "" +$(JARTARGETN) : $(OWNCOPY) +.ENDIF + +$(OWNCOPY) : $(CFGFILES) + -$(MKDIRHIER) $(CLASSDIR)$/$(PACKAGE) + $(COPY) $? $(CLASSDIR)$/$(PACKAGE) && $(TOUCH) $@ + +.ENDIF # "$(SOLAR_JAVA)" != "" + +#.ELSE +#pseudo: + +#.ENDIF diff --git a/l10ntools/source/filter/utils/AnalyzeStartupLog.java b/l10ntools/source/filter/utils/AnalyzeStartupLog.java new file mode 100644 index 000000000000..498528850697 --- /dev/null +++ b/l10ntools/source/filter/utils/AnalyzeStartupLog.java @@ -0,0 +1,328 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: AnalyzeStartupLog.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.filter.config.tools.utils; + +//_______________________________________________ +// imports +import java.util.*; +import java.lang.*; + +//_______________________________________________ +// implementation +public class AnalyzeStartupLog +{ + private class OperationTime + { + /** name the measured operation. */ + public java.lang.String sOperation; + + /** contains the time value, when this operation was started. */ + public long nStartTime; + + /** contains the time value, when this operation was finished. */ + public long nEndTime; + + /** text inside log file, which identifies the start time value. */ + public java.lang.String sStartMsg; + + /** text inside log file, which identifies the end time value. */ + public java.lang.String sEndMsg; + } + + //_________________________________ + // main + + public static void main(java.lang.String[] lCmdLine) + { + int nExit = 0; + try + { + // analyze command line + ConfigHelper aCmdLine = new ConfigHelper("", lCmdLine); + java.lang.String sLogDir = aCmdLine.getString("logdir" ); + java.lang.String sDataFile = aCmdLine.getString("datafile"); + + if (sLogDir == null || sDataFile == null) + { + System.err.println("AnalyzeStartupLog lodir= datafile="); + System.err.println("E.g.: AnalyzeStartupLog lodir=c:\\temp\\logs datafile=c:\\temp\\data.csv"); + System.exit(--nExit); + } + + // get list of all log files + boolean bRecursive = true; + java.util.Vector lLogs = FileHelper.getSystemFilesFromDir(new java.io.File(sLogDir), bRecursive); + if (lLogs == null || lLogs.isEmpty()) + { + System.err.println("log dir is empty"); + System.exit(--nExit); + } + + // analyze it + java.lang.StringBuffer sOut = new java.lang.StringBuffer(1000); + sOut.append("log;t_cfg_start;t_cfg_end;t_fwk_start;t_fwk_end;t_sfx_start;t_sfx_end;t_types_start;t_types_end;t_filters_start;t_filters_end;"); + sOut.append("t_filters_swriter_start;t_filters_swriter_end;t_filters_sweb_start;t_filters_sweb_end;t_filters_sglobal_start;t_filters_sglobal_end;t_filters_scalc_start;t_filters_scalc_end;t_filters_sdraw_start;t_filters_sdraw_end;t_filters_simpress_start;t_filters_simpress_end;t_filters_schart_start;t_filters_schart_end;t_filters_smath_start;t_filters_smath_end;"); + sOut.append("t_others_start;t_others_end;d_cfg;d_fwk;d_sfx;d_types;d_filters;d_others;d_complete\n"); + + java.util.Enumeration aIt = lLogs.elements(); + while (aIt.hasMoreElements()) + { + java.io.File aLog = (java.io.File)aIt.nextElement(); + java.io.FileReader aReader = new java.io.FileReader(aLog); + java.io.BufferedReader aBuffer = new java.io.BufferedReader(aReader); + + long t_cfg_start = 0; + long t_cfg_end = 0; + + long t_fwk_start = 0; + long t_fwk_end = 0; + + long t_sfx_start = 0; + long t_sfx_end = 0; + + long t_types_start = 0; + long t_types_end = 0; + + long t_filters_start = 0; + long t_filters_end = 0; + + long t_filters_swriter_start = 0; + long t_filters_swriter_end = 0; + + long t_filters_sweb_start = 0; + long t_filters_sweb_end = 0; + + long t_filters_sglobal_start = 0; + long t_filters_sglobal_end = 0; + + long t_filters_scalc_start = 0; + long t_filters_scalc_end = 0; + + long t_filters_sdraw_start = 0; + long t_filters_sdraw_end = 0; + + long t_filters_simpress_start = 0; + long t_filters_simpress_end = 0; + + long t_filters_schart_start = 0; + long t_filters_schart_end = 0; + + long t_filters_smath_start = 0; + long t_filters_smath_end = 0; + + long t_others_start = 0; + long t_others_end = 0; + + while (true) + { + java.lang.String sLine = aBuffer.readLine(); + if (sLine == null) + break; + + if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : { creation ConfigItem [file=standard, version=6, mode=3]")) + t_cfg_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : } creation ConfigItem")) + t_cfg_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : { reading TypeDetection.xml")) + t_fwk_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : } reading TypeDetection.xml")) + t_fwk_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadTypes")) + t_types_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadTypes")) + t_types_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadFilters")) + t_filters_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadFilters")) + t_filters_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [swriter]")) + t_filters_swriter_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [swriter]")) + t_filters_swriter_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [sweb]")) + t_filters_sweb_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [sweb]")) + t_filters_sweb_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [sglobal]")) + t_filters_sglobal_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [sglobal]")) + t_filters_sglobal_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [scalc]")) + t_filters_scalc_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [scalc]")) + t_filters_scalc_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [sdraw]")) + t_filters_sdraw_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [sdraw]")) + t_filters_sdraw_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [simpress]")) + t_filters_simpress_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [simpress]")) + t_filters_simpress_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [schart]")) + t_filters_schart_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [schart]")) + t_filters_schart_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ reading FilterGroup [smath]")) + t_filters_smath_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} reading FilterGroup [smath]")) + t_filters_smath_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadDetectors")) + t_others_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadContentHandlers")) + t_others_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} framework (as96863) ::FilterCache::FilterCache")) + t_sfx_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); + else + if (sLine.endsWith("} desktop (lo119109) OfficeWrapper::OfficeWrapper")) + t_sfx_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); + } + + sOut.append(aLog.getName() ); + sOut.append(";" ); + sOut.append(t_cfg_start ); + sOut.append(";" ); + sOut.append(t_cfg_end ); + sOut.append(";" ); + sOut.append(t_fwk_start ); + sOut.append(";" ); + sOut.append(t_fwk_end ); + sOut.append(";" ); + sOut.append(t_sfx_start ); + sOut.append(";" ); + sOut.append(t_sfx_end ); + sOut.append(";" ); + sOut.append(t_types_start ); + sOut.append(";" ); + sOut.append(t_types_end ); + sOut.append(";" ); + sOut.append(t_filters_start ); + sOut.append(";" ); + sOut.append(t_filters_end ); + sOut.append(";" ); + + sOut.append(t_filters_swriter_start ); + sOut.append(";" ); + sOut.append(t_filters_swriter_end ); + sOut.append(";" ); + sOut.append(t_filters_sweb_start ); + sOut.append(";" ); + sOut.append(t_filters_sweb_end ); + sOut.append(";" ); + sOut.append(t_filters_sglobal_start ); + sOut.append(";" ); + sOut.append(t_filters_sglobal_end ); + sOut.append(";" ); + sOut.append(t_filters_scalc_start ); + sOut.append(";" ); + sOut.append(t_filters_scalc_end ); + sOut.append(";" ); + sOut.append(t_filters_sdraw_start ); + sOut.append(";" ); + sOut.append(t_filters_sdraw_end ); + sOut.append(";" ); + sOut.append(t_filters_simpress_start ); + sOut.append(";" ); + sOut.append(t_filters_simpress_end ); + sOut.append(";" ); + sOut.append(t_filters_schart_start ); + sOut.append(";" ); + sOut.append(t_filters_schart_end ); + sOut.append(";" ); + sOut.append(t_filters_smath_start ); + sOut.append(";" ); + sOut.append(t_filters_smath_end ); + sOut.append(";" ); + + sOut.append(t_others_start ); + sOut.append(";" ); + sOut.append(t_others_end ); + sOut.append(";" ); + sOut.append(t_cfg_end -t_cfg_start ); + sOut.append(";" ); + sOut.append(t_fwk_end -t_fwk_start ); + sOut.append(";" ); + sOut.append(t_sfx_end -t_sfx_start ); + sOut.append(";" ); + sOut.append(t_types_end -t_types_start ); + sOut.append(";" ); + sOut.append(t_filters_end-t_filters_start); + sOut.append(";" ); + sOut.append(t_others_end -t_others_start ); + sOut.append(";" ); + sOut.append(t_others_end -t_cfg_start ); + sOut.append("\n" ); + + aBuffer.close(); + } + + java.io.FileWriter aCSV = new java.io.FileWriter(sDataFile); + java.lang.String sData = sOut.toString(); + aCSV.write(sData, 0, sData.length()); + aCSV.flush(); + aCSV.close(); + } + catch(java.lang.Throwable exAny) + { + System.err.println(exAny.getMessage()); + exAny.printStackTrace(); + System.exit(--nExit); + } + + System.exit(0); + } +} diff --git a/l10ntools/source/filter/utils/Cache.java b/l10ntools/source/filter/utils/Cache.java new file mode 100644 index 000000000000..94c26008ed13 --- /dev/null +++ b/l10ntools/source/filter/utils/Cache.java @@ -0,0 +1,2449 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Cache.java,v $ + * $Revision: 1.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package com.sun.star.filter.config.tools.utils; + +//_______________________________________________ + +import java.lang.*; +import java.util.*; +import java.io.*; + +//_______________________________________________ + +/** + * It implements a container for all possible entries which are part of the type + * and filter mechanism of an office - means all items of the configuration file + * "TypeDetection". How these entries will be readed or written can be switch + * in different modes. That would make it possible to edit an xml directly or + * to contact a running office instance. + * + * + */ +public class Cache +{ + //___________________________________________ + // public const + + /** identifies a file type item of this cache. */ + public static final int E_TYPE = 0; + + /** identifies a filter item of this cache. */ + public static final int E_FILTER = 1; + + /** identifies a detect service item of this cache. */ + public static final int E_DETECTSERVICE = 2; + + /** identifies a frame loader item of this cache. */ + public static final int E_FRAMELOADER = 3; + + /** identifies a content handler item of this cache. */ + public static final int E_CONTENTHANDLER = 4; + + /** indicates an unsupported xml format => error! */ + public static final int FORMAT_UNSUPPORTED = -1; + + /** identify the configuration format of an office 6.0. + * The own formated data string is used. */ + public static final int FORMAT_60 = 0; + + /** identify the configuration format of an office 6.y. + * Properties are realy xml tags again. */ + public static final int FORMAT_6Y = 1; + + /** identify the configuration format which is used inside + * this tooling project. */ + public static final int FORMAT_INTERNAL = 2; + + /** right value for a command line parameter to define a 6.0 version. */ + public static final java.lang.String CMDVAL_FORMAT_60 = "6.0"; + + /** right value for a command line parameter to define a 6.Y version. */ + public static final java.lang.String CMDVAL_FORMAT_6Y = "6.Y"; + + /** right value for a command line parameter to define an internal xml version! */ + public static final java.lang.String CMDVAL_FORMAT_INTERNAL = "internal"; + + // general + public static final java.lang.String PROPNAME_DATA = "Data"; + public static final java.lang.String PROPNAME_NAME = "Name"; + public static final java.lang.String PROPNAME_UINAME = "UIName"; + public static final java.lang.String PROPNAME_UINAMES = "UINames"; + + // type 6.0 ... + public static final java.lang.String PROPNAME_MEDIATYPE = "MediaType"; + public static final java.lang.String PROPNAME_PREFERRED = "Preferred"; + public static final java.lang.String PROPNAME_CLIPBOARDFORMAT = "ClipboardFormat"; + public static final java.lang.String PROPNAME_DOCUMENTICONID = "DocumentIconID"; + public static final java.lang.String PROPNAME_URLPATTERN = "URLPattern"; + public static final java.lang.String PROPNAME_EXTENSIONS = "Extensions"; + // ... +6.y + public static final java.lang.String PROPNAME_UIORDER = "UIOrder"; + public static final java.lang.String PROPNAME_PREFERREDFILTER = "PreferredFilter"; + public static final java.lang.String PROPNAME_DETECTSERVICE = "DetectService"; + public static final java.lang.String PROPNAME_FRAMELOADER = "FrameLoader"; + public static final java.lang.String PROPNAME_CONTENTHANDLER = "ContentHandler"; + + // filter + public static final java.lang.String PROPNAME_DOCUMENTSERVICE = "DocumentService"; + public static final java.lang.String PROPNAME_FILEFORMATVERSION = "FileFormatVersion"; + public static final java.lang.String PROPNAME_FILTERSERVICE = "FilterService"; + public static final java.lang.String PROPNAME_FLAGS = "Flags"; + public static final java.lang.String PROPNAME_ORDER = "Order"; // -6.y + public static final java.lang.String PROPNAME_TEMPLATENAME = "TemplateName"; + public static final java.lang.String PROPNAME_TYPE = "Type"; + public static final java.lang.String PROPNAME_UICOMPONENT = "UIComponent"; + public static final java.lang.String PROPNAME_USERDATA = "UserData"; + + // frame loader / detect services / content handler + public static final java.lang.String PROPNAME_TYPES = "Types"; + + //___________________________________________ + // private const + + private static final java.lang.String FILTERSERVICE_NATIVEWARPPER = "com.sun.star.filter.NativeFilterWrapper"; + private static final java.lang.String GENERIC_DETECTSERVICE = "com.sun.star.comp.office.FrameLoader"; + + /** its the name of the cfg set, which contains all types. */ + private static final java.lang.String CFGNODE_TYPES = "Types"; + + /** its the name of the cfg set, which contains all filters. */ + private static final java.lang.String CFGNODE_FILTERS = "Filters"; + + /** its the name of the cfg set, which contains all detect services. */ + private static final java.lang.String CFGNODE_DETECTSERVICES = "DetectServices"; + + /** its the name of the cfg set, which contains all frame loaders. */ + private static final java.lang.String CFGNODE_FRAMELOADERS = "FrameLoaders"; + + /** its the name of the cfg set, which contains all content handlers. */ + private static final java.lang.String CFGNODE_CONTENTHANDLERS = "ContentHandlers"; + + // names for filter flags + private static final java.lang.String FLAGNAME_3RDPARTYFILTER = "3RDPARTYFILTER"; + private static final java.lang.String FLAGNAME_ALIEN = "ALIEN"; + private static final java.lang.String FLAGNAME_ASYNCHRON = "ASYNCHRON"; + private static final java.lang.String FLAGNAME_BROWSERPREFERRED = "BROWSERPREFERRED"; + private static final java.lang.String FLAGNAME_CONSULTSERVICE = "CONSULTSERVICE"; + private static final java.lang.String FLAGNAME_DEFAULT = "DEFAULT"; + private static final java.lang.String FLAGNAME_EXPORT = "EXPORT"; + private static final java.lang.String FLAGNAME_IMPORT = "IMPORT"; + private static final java.lang.String FLAGNAME_INTERNAL = "INTERNAL"; + private static final java.lang.String FLAGNAME_NOTINCHOOSER = "NOTINCHOOSER"; + private static final java.lang.String FLAGNAME_NOTINFILEDIALOG = "NOTINFILEDIALOG"; + private static final java.lang.String FLAGNAME_NOTINSTALLED = "NOTINSTALLED"; + private static final java.lang.String FLAGNAME_OWN = "OWN"; + private static final java.lang.String FLAGNAME_PACKED = "PACKED"; + private static final java.lang.String FLAGNAME_PREFERRED = "PREFERRED"; + private static final java.lang.String FLAGNAME_READONLY = "READONLY"; + private static final java.lang.String FLAGNAME_SILENTEXPORT = "SILENTEXPORT"; + private static final java.lang.String FLAGNAME_TEMPLATE = "TEMPLATE"; + private static final java.lang.String FLAGNAME_TEMPLATEPATH = "TEMPLATEPATH"; + private static final java.lang.String FLAGNAME_USESOPTIONS = "USESOPTIONS"; + + private static final java.lang.String FLAGNAME_COMBINED = "COMBINED"; + private static final java.lang.String FLAGNAME_SUPPORTSSELECTION= "SUPPORTSSELECTION"; + + // values for filter flags + private static final int FLAGVAL_3RDPARTYFILTER = 0x00080000; // 524288 + private static final int FLAGVAL_ALIEN = 0x00000040; // 64 + private static final int FLAGVAL_ALL = 0xffffffff; // 4294967295 + private static final int FLAGVAL_ASYNCHRON = 0x00004000; // 16384 + private static final int FLAGVAL_BROWSERPREFERRED = 0x00400000; // 4194304 + private static final int FLAGVAL_CONSULTSERVICE = 0x00040000; // 262144 + private static final int FLAGVAL_DEFAULT = 0x00000100; // 256 + private static final int FLAGVAL_EXPORT = 0x00000002; // 2 + private static final int FLAGVAL_IMPORT = 0x00000001; // 1 + private static final int FLAGVAL_INTERNAL = 0x00000008; // 8 + private static final int FLAGVAL_NOTINCHOOSER = 0x00002000; // 8192 + private static final int FLAGVAL_NOTINFILEDIALOG = 0x00001000; // 4096 + private static final int FLAGVAL_NOTINSTALLED = 0x00020000; // 131072 + private static final int FLAGVAL_OWN = 0x00000020; // 32 + private static final int FLAGVAL_PACKED = 0x00100000; // 1048576 + private static final int FLAGVAL_PREFERRED = 0x10000000; // 268435456 + private static final int FLAGVAL_READONLY = 0x00010000; // 65536 + private static final int FLAGVAL_SILENTEXPORT = 0x00200000; // 2097152 + private static final int FLAGVAL_TEMPLATE = 0x00000004; // 4 + private static final int FLAGVAL_TEMPLATEPATH = 0x00000010; // 16 + private static final int FLAGVAL_USESOPTIONS = 0x00000080; // 128 + + private static final int FLAGVAL_COMBINED = 0x00800000; // ... + private static final int FLAGVAL_SUPPORTSSELECTION = 0x00000400; // 1024 + + //___________________________________________ + // member + + /** list of all located types. + * Format: [string,HashMap] + */ + private java.util.HashMap m_lTypes; + + /** list of all located filters. + * Format: [string,HashMap] + */ + private java.util.HashMap m_lFilters; + + /** list of all located detect services. + * Format: [string,HashMap] + */ + private java.util.HashMap m_lDetectServices; + + /** list of all located frame loader. + * Format: [string,HashMap] + */ + private java.util.HashMap m_lFrameLoaders; + + /** list of all located content handler. + * Format: [string,HashMap] + */ + private java.util.HashMap m_lContentHandlers; + + /** contains all analyzed relations between + * filters and types. The key is an internal + * type name (can be used as reference into the + * list m_lTypes) and the value is a Vector of all + * internal filter names, which are registered for + * this type. + * Format: [string, Vector] + */ + private java.util.HashMap m_lFilterToTypeRegistrations; + + private int m_nDoubleRegisteredFilters; + private int m_nTypesForFilters; + private int m_nTypesForDetectServices; + private int m_nTypesForFrameLoaders; + private int m_nTypesForContentHandlers; + + /** can be used to log different informations. */ + private Logger m_aDebug; + + //___________________________________________ + // interface + + /** standard ctor. + * + * Initialize an empty cache instance. You have to use + * on of the fromXXX() methods to fill it from different + * sources with content. + */ + public Cache(Logger aDebug) + { + reset(); + m_aDebug = aDebug; + } + + //___________________________________________ + + /** free memory and set default values on all members. + */ + public synchronized void reset() + { + m_lTypes = new java.util.HashMap(); + m_lFilters = new java.util.HashMap(); + m_lFrameLoaders = new java.util.HashMap(); + m_lDetectServices = new java.util.HashMap(); + m_lContentHandlers = new java.util.HashMap(); + m_lFilterToTypeRegistrations = new java.util.HashMap(); + m_aDebug = new Logger(); + m_nDoubleRegisteredFilters = 0; + m_nTypesForFilters = 0; + m_nTypesForDetectServices = 0; + m_nTypesForFrameLoaders = 0; + m_nTypesForContentHandlers = 0; + } + + //___________________________________________ + + /** converts a string representation of an xml format + * to its int value, which must be used at some interface + * methods of this cache. + * + * If the given string does not match to any well known format, + * the return value will be FORMAT_UNSUPPORTED. The calli have to + * check that. Otherwhise a called interface method at this cache + * instance will be rejected by an exception! + * + * @param sFormat + * the string representation + * Must be one of our public const values from type CMDVAL_FORMAT_xxx. + * + * @return [int] + * the int representation. + * Will be one of our public const values from type FORMAT_xxx. + */ + public static int mapFormatString2Format(java.lang.String sFormat) + { + int nFormat = FORMAT_UNSUPPORTED; + if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_60)) + nFormat = FORMAT_60; + else + if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_6Y)) + nFormat = FORMAT_6Y; + else + if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_INTERNAL)) + nFormat = FORMAT_INTERNAL; + return nFormat; + } + + //___________________________________________ + + /** return some statistic values. + * + * Such values can be: - count of container items, + * - ... + * + * @return [java.lang.String] + * a formated string, which contains al statistic data. + */ + public synchronized java.lang.String getStatistics() + { + java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(256); + + sBuffer.append("types = "+m_lTypes.size() +"\n"); + sBuffer.append("filters = "+m_lFilters.size() +"\n"); + sBuffer.append("detect services = "+m_lDetectServices.size() +"\n"); + sBuffer.append("frame loaders = "+m_lFrameLoaders.size() +"\n"); + sBuffer.append("content handler = "+m_lContentHandlers.size() +"\n"); + sBuffer.append("double registered filters = "+m_nDoubleRegisteredFilters+"\n"); + sBuffer.append("types used by filters = "+m_nTypesForFilters +"\n"); + sBuffer.append("types used by detect services = "+m_nTypesForDetectServices +"\n"); + sBuffer.append("types used by frame loaders = "+m_nTypesForFrameLoaders +"\n"); + sBuffer.append("types used by content handlers = "+m_nTypesForContentHandlers+"\n"); + + return sBuffer.toString(); + } + + //___________________________________________ + + /** reset this cache and fill it with new values using the given XML file. + * + * @param aXML + * must be a system file of a suitable XML file, which + * include all neccessary type/filter items. + * + * @param nFormat + * identifies the format of the specified xml file, + * which must be interpreted. + */ + public synchronized void fromXML(java.io.File aXML , + int nFormat) + throws java.lang.Exception + { + // clear this cache + reset(); + + // parse it + javax.xml.parsers.DocumentBuilderFactory aFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); + /* Attention: + * This call is important. It force right handling of entities during parsing and(!) + * writing. It let all possible signs for entities or it's quoted representations + * untouched. So this class don't change the original signs of the original file. + * Means: + *
    + *
  • (') => (')
  • + *
  • (") => (")
  • + *
  • (>) => (>)
  • + *
  • (<) => (<)
  • + *
  • (>) => (>)
  • + *
  • (&) => (&)
  • + *
  • ...
  • + *
+ */ + + System.out.println("TODO: must be adapted to java 1.3 :-("); + System.exit(-1); +//TODO_JAVA aFactory.setExpandEntityReferences(false); + + javax.xml.parsers.DocumentBuilder aBuilder = aFactory.newDocumentBuilder(); + org.w3c.dom.Document aDOM = aBuilder.parse(aXML); + org.w3c.dom.Element aRoot = aDOM.getDocumentElement(); + + // step over all sets + java.util.Vector lSetNodes = XMLHelper.extractChildNodesByTagName(aRoot, XMLHelper.XMLTAG_NODE); + java.util.Enumeration it1 = lSetNodes.elements(); + while (it1.hasMoreElements()) + { + // try to find out, which set should be read + org.w3c.dom.Node aSetNode = (org.w3c.dom.Node)it1.nextElement(); + java.lang.String sSetName = XMLHelper.extractNodeAttribByName(aSetNode, XMLHelper.XMLATTRIB_OOR_NAME); + if (sSetName == null) + throw new java.io.IOException("unsupported format: could not extract set name on node ...\n"+aSetNode); + + // map some generic interfaces to the right members! + int eType = -1 ; + java.util.HashMap rMap = null; + + if (sSetName.equals(CFGNODE_TYPES)) + { + eType = E_TYPE; + rMap = m_lTypes; + } + else + if (sSetName.equals(CFGNODE_FILTERS)) + { + eType = E_FILTER; + rMap = m_lFilters; + } + else + if (sSetName.equals(CFGNODE_FRAMELOADERS)) + { + eType = E_FRAMELOADER; + rMap = m_lFrameLoaders; + } + else + if (sSetName.equals(CFGNODE_DETECTSERVICES)) + { + eType = E_DETECTSERVICE; + rMap = m_lDetectServices; + } + else + if (sSetName.equals(CFGNODE_CONTENTHANDLERS)) + { + eType = E_CONTENTHANDLER; + rMap = m_lContentHandlers; + } + else + throw new java.io.IOException("unsupported format: unknown set name [\""+sSetName+"\"] detected on node ...\n"+aSetNode); + + // load all set entries + java.util.Vector lChildNodes = XMLHelper.extractChildNodesByTagName(aSetNode, XMLHelper.XMLTAG_NODE); + java.util.Enumeration it2 = lChildNodes.elements(); + while (it2.hasMoreElements()) + { + org.w3c.dom.Node aChildNode = (org.w3c.dom.Node)it2.nextElement(); + java.lang.String sChildName = XMLHelper.extractNodeAttribByName(aChildNode, XMLHelper.XMLATTRIB_OOR_NAME); + if (sChildName == null) + throw new java.io.IOException("unsupported format: could not extract child node name on node ...\n"+aChildNode); + java.util.HashMap aPropSet = null; + + // Note: Our internal format is different from the source format! + java.util.HashMap aTempSet = XMLHelper.convertNodeToPropSet(aChildNode); + switch(eType) + { + case E_TYPE : + { + aPropSet = Cache.convertTypePropsToInternal(aTempSet, nFormat); + m_aDebug.setDetailedInfo("type [\""+sChildName+"\"] converted to internal format"); + } + break; + + case E_FILTER : + { + aPropSet = Cache.convertFilterPropsToInternal(aTempSet, nFormat); + m_aDebug.setDetailedInfo("filter [\""+sChildName+"\"] converted to internal format"); + } + break; + + case E_DETECTSERVICE : + { + aPropSet = Cache.convertDetectServicePropsToInternal(aTempSet, nFormat); + m_aDebug.setDetailedInfo("detect service [\""+sChildName+"\"] converted to internal format"); + } + break; + + case E_FRAMELOADER : + { + aPropSet = Cache.convertFrameLoaderPropsToInternal(aTempSet, nFormat); + m_aDebug.setDetailedInfo("frame loader [\""+sChildName+"\"] converted to internal format"); + } + break; + + case E_CONTENTHANDLER : + { + aPropSet = Cache.convertContentHandlerPropsToInternal(aTempSet, nFormat); + m_aDebug.setDetailedInfo("content handler [\""+sChildName+"\"] converted to internal format"); + } + break; + } + m_aDebug.setDetailedInfo("props = "+aTempSet); + rMap.put(sChildName, aPropSet); + } + } + } + + //___________________________________________ + + /** create some hml views of the current content of this cache. + * + * The given directory is used to create different html files + * there. Every of them show another aspect of this cache. + * E.g.: - all type/filter properties + * - relation ships between types/filters/loaders etc. + * + * @param aDirectory + * points to a system directory, which + * can be used completely(!) to generate + * the results there. + * + * @param nFormat + * specify in which context the cache items should be + * interpreted. + */ + public synchronized void toHTML(java.io.File aDirectory, + int nFormat , + java.lang.String sEncoding ) + throws java.lang.Exception + { + if (nFormat != FORMAT_6Y) + throw new java.lang.Exception("HTML views are supported for the new 6.y format only yet."); + + java.lang.StringBuffer sRelationView = new java.lang.StringBuffer(1000); + sRelationView.append("
Relation View
"); + sRelationView.append(""); + sRelationView.append(""); + + java.util.Iterator aIt = m_lTypes.keySet().iterator(); + while (aIt.hasNext()) + { + java.lang.String sType = (java.lang.String)aIt.next(); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sType); + + sRelationView.append(""); + sRelationView.append(""); + + java.lang.String sVal = (java.lang.String)aType.get(PROPNAME_DETECTSERVICE); + if (sVal == null || sVal.length()<1) + sRelationView.append(""); + else + sRelationView.append(""); + + sVal = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); + if (sVal == null || sVal.length()<1) + sRelationView.append(""); + else + sRelationView.append(""); + + sVal = (java.lang.String)aType.get(PROPNAME_FRAMELOADER); + if (sVal == null || sVal.length()<1) + sRelationView.append(""); + else + sRelationView.append(""); + + sVal = (java.lang.String)aType.get(PROPNAME_CONTENTHANDLER); + if (sVal == null || sVal.length()<1) + sRelationView.append(""); + else + sRelationView.append(""); + + sRelationView.append(""); + } + + sRelationView.append("
typedetect servicepreferred filterframe loadercontent handler
"+sType+" - "+sVal+" - "+sVal+" - "+sVal+" - "+sVal+"
"); + sRelationView.append(""); + + FileHelper.writeEncodedBufferToFile(new java.io.File(aDirectory, "relation_view.html"), sEncoding, false, sRelationView); + + java.util.HashMap lFilters2TypeRegistration = new java.util.HashMap(); + aIt = m_lFilters.keySet().iterator(); + while (aIt.hasNext()) + { + java.lang.String sFilter = (java.lang.String)aIt.next(); + java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); + java.lang.String sType = (java.lang.String)aFilter.get(PROPNAME_TYPE); + + java.util.Vector lFilters = (java.util.Vector)lFilters2TypeRegistration.get(sType); + if (lFilters == null) + lFilters = new java.util.Vector(); + lFilters.add(sFilter); + lFilters2TypeRegistration.put(sType, lFilters); + } + + java.lang.StringBuffer sType2FiltersView = new java.lang.StringBuffer(1000); + sType2FiltersView.append("
Type2Filters View
"); + sType2FiltersView.append(""); + sType2FiltersView.append(""); + + aIt = lFilters2TypeRegistration.keySet().iterator(); + while (aIt.hasNext()) + { + java.lang.String sType = (java.lang.String)aIt.next(); + java.util.Vector lFilters = (java.util.Vector)lFilters2TypeRegistration.get(sType); + + sType2FiltersView.append(""); + } + + sType2FiltersView.append("
typefilters
"+sType+""); + java.util.Enumeration aEn = lFilters.elements(); + while(aEn.hasMoreElements()) + sType2FiltersView.append(aEn.nextElement()+"
"); + sType2FiltersView.append("
"); + sType2FiltersView.append(""); + + FileHelper.writeEncodedBufferToFile(new java.io.File(aDirectory, "type2filters_view.html"), sEncoding, false, sType2FiltersView); + } + + //___________________________________________ + + /** converts all items of this cache to its xml representation + * and write it to the given file. + * + * @param aXML + * the target file for output. + * + * @param nFormat + * the requested xml format. + * see const values FORMAT_xxx too. + * + * @param sEncoding + * specify the file encoding for the generated xml file. + * + * @throws [java.lang.Exception] + * if something fail during convertion. + */ + public synchronized void toXML(java.io.File aXML , + int nFormat , + java.lang.String sEncoding) + throws java.lang.Exception + { + java.lang.StringBuffer sXML = new java.lang.StringBuffer(500000); + + for (int i=0; i<5; ++i) + { + // define right sub container + java.lang.String sSetName = null; + java.util.HashMap rMap = null; + int eType = -1; + + switch(i) + { + case 0 : + { + sSetName = CFGNODE_TYPES; + rMap = m_lTypes; + eType = E_TYPE; + } + break; + + case 1 : + { + sSetName = CFGNODE_FILTERS; + rMap = m_lFilters; + eType = E_FILTER; + } + break; + + case 2 : + { + sSetName = CFGNODE_DETECTSERVICES; + rMap = m_lDetectServices; + eType = E_DETECTSERVICE; + } + break; + + case 3 : + { + sSetName = CFGNODE_FRAMELOADERS; + rMap = m_lFrameLoaders; + eType = E_FRAMELOADER; + } + break; + + case 4 : + { + sSetName = CFGNODE_CONTENTHANDLERS; + rMap = m_lContentHandlers; + eType = E_CONTENTHANDLER; + } + break; + } + + // generate set + sXML.append("\n"); + java.util.Iterator it = rMap.keySet().iterator(); + while(it.hasNext()) + { + java.lang.String sItem = (java.lang.String)it.next(); + sXML.append("\n"); + sXML.append(getItemAsXML(eType, sItem, nFormat)); + sXML.append("\n"); + } + sXML.append("\n"); + } + + java.io.FileOutputStream aStream = new java.io.FileOutputStream(aXML.getAbsolutePath(), false); + java.io.OutputStreamWriter aWriter = new java.io.OutputStreamWriter(aStream, sEncoding); + java.lang.String sOut = sXML.toString(); + aWriter.write(sOut, 0, sOut.length()); + aWriter.flush(); + aWriter.close(); + } + + //___________________________________________ + + /** converts a type property set from internal format + * to an external one. + * + * @param aMap + * points to the item, which should be converted. + * + * @param nFormat + * specify the requested output format. + * + * @return [java.util.HashMap] + * contains the properties in the requested format. + * + * @throws [java.lang.Exception + * if something fail during convertion. + */ + private static java.util.HashMap convertTypePropsToExternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + java.util.HashMap aResultMap = new java.util.HashMap(); + // copy Name property ... if it exists! + if (aMap.containsKey(PROPNAME_NAME)) + aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); + switch(nFormat) + { + //----------------------------------- + case FORMAT_60 : + { + // copy UIName property unchanged + aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); + + // ignore properties "UIOrder", "PreferredFilter", "DetectService" + // They are not supported for 6.0 types. + + // pack all other properties to one "Data" string value + java.lang.StringBuffer sData = new java.lang.StringBuffer(256); + + sData.append(aMap.get(PROPNAME_PREFERRED)); + sData.append(","); + sData.append(aMap.get(PROPNAME_MEDIATYPE)); + sData.append(","); + sData.append(aMap.get(PROPNAME_CLIPBOARDFORMAT)); + sData.append(","); + + java.util.Vector lList = (java.util.Vector)aMap.get(PROPNAME_URLPATTERN); + int c = lList.size(); + int i = 0; + for (i=0; i aExpandedMap["UIName"] + * aMap["Data" ] => aExpandedMap["Preferred" ], aExpandedMap["MediaType"] etc. ... + * + * @param aMap + * points to the item, which should be converted. + + * @param nFormat + * specify the external format. + * + * @return [java.util.HashMap] + * The new map in internal format. + */ + private static java.util.HashMap convertTypePropsToInternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + java.util.HashMap aResultMap = new java.util.HashMap(); + // copy Name property ... if it exists! + if (aMap.containsKey(PROPNAME_NAME)) + aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); + switch(nFormat) + { + //----------------------------------- + case FORMAT_60 : + { + // copy UIName property unchanged! + aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); + + // generate new property "UIOrder" + // Its the moved property "Order" of filters for versions >= 6.y! + aResultMap.put(PROPNAME_UIORDER, new java.lang.Integer(0)); + + // generate new property "PreferredFilter" + // Its a the moved filter flag "Preferred" for versions >= 6.y! + aResultMap.put(PROPNAME_PREFERREDFILTER, new java.lang.String()); + + // generate new property "DetectService" + // Every type know its detector diretcly from now. No search + // will be neccessary any longer. + aResultMap.put(PROPNAME_DETECTSERVICE, new java.lang.String()); + + // analyze the Data property of the original map + // and copy its results (means all expanded properties) + // to the result map. + java.lang.String sDataVal = (java.lang.String)aMap.get(PROPNAME_DATA); + java.util.Vector lTokens = Cache.splitTokenString(sDataVal, ","); + + int t = 0; + java.util.Enumeration it = lTokens.elements(); + while (it.hasMoreElements()) + { + java.lang.String sToken = (java.lang.String)it.nextElement(); + switch(t) + { + case 0 : + aResultMap.put(PROPNAME_PREFERRED, new java.lang.Boolean(sToken)); + break; + case 1 : + aResultMap.put(PROPNAME_MEDIATYPE, sToken); + break; + case 2 : + { + /*HACK ersetze %20 mit " " ...*/ + int ni = sToken.indexOf("%20"); + if (ni!=-1) + { + java.lang.String sPatch = sToken.substring(0,ni) + " " + sToken.substring(ni+3); + sToken = sPatch; + } + aResultMap.put(PROPNAME_CLIPBOARDFORMAT, sToken); + } + break; + case 3 : + aResultMap.put(PROPNAME_URLPATTERN, Cache.splitTokenString(sToken, ";")); + break; + case 4 : + aResultMap.put(PROPNAME_EXTENSIONS, Cache.splitTokenString(sToken, ";")); + break; + case 5 : + aResultMap.put(PROPNAME_DOCUMENTICONID, new java.lang.Integer(sToken)); + break; + default : + throw new java.lang.Exception("unsupported format for data value of a type \""+aMap.get(PROPNAME_NAME)+"\" detected."); + } + ++t; + } + } + break; + + //----------------------------------- + case FORMAT_6Y : + { + // copy all supported properties directly + aResultMap.put(PROPNAME_PREFERRED , aMap.get(PROPNAME_PREFERRED )); + aResultMap.put(PROPNAME_MEDIATYPE , aMap.get(PROPNAME_MEDIATYPE )); + aResultMap.put(PROPNAME_CLIPBOARDFORMAT, aMap.get(PROPNAME_CLIPBOARDFORMAT)); + aResultMap.put(PROPNAME_URLPATTERN , aMap.get(PROPNAME_URLPATTERN )); + aResultMap.put(PROPNAME_EXTENSIONS , aMap.get(PROPNAME_EXTENSIONS )); + aResultMap.put(PROPNAME_DOCUMENTICONID , aMap.get(PROPNAME_DOCUMENTICONID )); + aResultMap.put(PROPNAME_UINAME , aMap.get(PROPNAME_UINAME )); + aResultMap.put(PROPNAME_UIORDER , aMap.get(PROPNAME_UIORDER )); + aResultMap.put(PROPNAME_PREFERREDFILTER, aMap.get(PROPNAME_PREFERREDFILTER)); + aResultMap.put(PROPNAME_DETECTSERVICE , aMap.get(PROPNAME_DETECTSERVICE )); + } + break; + + //----------------------------------- + default : + throw new java.lang.Exception("unknown format"); + } + + return aResultMap; + } + + //___________________________________________ + + /** converts a filter property set (using an external format) to + * our internal cache format. + * + * Especialy the data format string will be expanded + * to its real properties. + * + * Schema: + * aMap["UIName"] => aExpandedMap["UIName"] + * aMap["Data" ] => aExpandedMap["Order" ], aExpandedMap["Flags"] etc. ... + * + * @param aMap + * points to the item, which should be converted. + * + * @param nFormat + * specify the external format. + * + * @return [java.util.HashMap] + * The new map in internal format. + */ + private static java.util.HashMap convertFilterPropsToInternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + java.util.HashMap aResultMap = new java.util.HashMap(); + // copy Name property ... if it exists! + if (aMap.containsKey(PROPNAME_NAME)) + aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); + switch(nFormat) + { + //----------------------------------- + case FORMAT_60 : + { + // copy UIName property + aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); + + // analyze the Data property of the original map + // and copy its results (means all expanded properties) + // to the result map. + java.lang.String sDataVal = (java.lang.String)aMap.get(PROPNAME_DATA); + java.util.Vector lTokens = Cache.splitTokenString(sDataVal, ","); + + int t = 0; + java.util.Enumeration it = lTokens.elements(); + while (it.hasMoreElements()) + { + java.lang.String sToken = (java.lang.String)it.nextElement(); + switch(t) + { + case 0 : + aResultMap.put(PROPNAME_ORDER, new java.lang.Integer(sToken)); + break; + case 1 : + aResultMap.put(PROPNAME_TYPE, sToken); + break; + case 2 : + aResultMap.put(PROPNAME_DOCUMENTSERVICE, sToken); + break; + case 3 : + aResultMap.put(PROPNAME_FILTERSERVICE, sToken); + break; + case 4 : + aResultMap.put(PROPNAME_FLAGS, new java.lang.Integer(sToken)); + break; + case 5 : + aResultMap.put(PROPNAME_USERDATA, Cache.splitTokenString(sToken, ";")); + break; + case 6 : + aResultMap.put(PROPNAME_FILEFORMATVERSION, new java.lang.Integer(sToken)); + break; + case 7 : + aResultMap.put(PROPNAME_TEMPLATENAME, sToken); + break; + case 8 : + aResultMap.put(PROPNAME_UICOMPONENT, sToken); + break; + default : + throw new java.lang.Exception("unsupported format for data value of a filter detected."); + } + ++t; + } + + // its an optional property :-) + if (!aResultMap.containsKey(PROPNAME_TEMPLATENAME)) + aResultMap.put(PROPNAME_TEMPLATENAME, new java.lang.String("")); + + // its an optional property :-) + if (!aResultMap.containsKey(PROPNAME_UICOMPONENT)) + aResultMap.put(PROPNAME_UICOMPONENT, new java.lang.String("")); + } + break; + + //----------------------------------- + case FORMAT_6Y : + { + // "Order" does not exist for 6.y versions! Use default. + aResultMap.put(PROPNAME_ORDER, new java.lang.Integer(0)); + + // "UIName" property does not exist for 6.y versions! use default. + /* TODO make it configurable :-) */ + aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); + //aResultMap.put(PROPNAME_UINAME, new java.util.HashMap()); + + // "Flags" must be converted from names to its values + java.util.Vector lFlags = (java.util.Vector)aMap.get(PROPNAME_FLAGS); + java.lang.Integer nFlags = Cache.convertFilterFlagNames2Values(lFlags); + aResultMap.put(PROPNAME_FLAGS, nFlags); + + // copy all direct supported properties + aResultMap.put(PROPNAME_TYPE , aMap.get(PROPNAME_TYPE )); + aResultMap.put(PROPNAME_DOCUMENTSERVICE , aMap.get(PROPNAME_DOCUMENTSERVICE )); + aResultMap.put(PROPNAME_FILTERSERVICE , aMap.get(PROPNAME_ORDER )); + aResultMap.put(PROPNAME_USERDATA , aMap.get(PROPNAME_USERDATA )); + aResultMap.put(PROPNAME_FILEFORMATVERSION, aMap.get(PROPNAME_FILEFORMATVERSION)); + aResultMap.put(PROPNAME_TEMPLATENAME , aMap.get(PROPNAME_TEMPLATENAME )); + aResultMap.put(PROPNAME_UICOMPONENT , aMap.get(PROPNAME_UICOMPONENT )); + } + break; + + //----------------------------------- + default : + throw new java.lang.Exception("unknown format"); + } + + return aResultMap; + } + + private static java.util.HashMap convertDetectServicePropsToInternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + /*FIXME*/ + java.util.HashMap aResultMap = aMap; + return aResultMap; + } + + private static java.util.HashMap convertFrameLoaderPropsToInternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + /*FIXME*/ + java.util.HashMap aResultMap = aMap; + return aResultMap; + } + + private static java.util.HashMap convertContentHandlerPropsToInternal(java.util.HashMap aMap , + int nFormat) + throws java.lang.Exception + { + /*FIXME*/ + java.util.HashMap aResultMap = aMap; + return aResultMap; + } + + //___________________________________________ + + /** converts filter flag names to its int representation. + * + * @param lFlags + * a list of flag names. + * + * @return [java.lang.Integer] + * an integer field of all set flags. + * + * @throws [java.lang.Exception] + * for unsupported flags or empty flag fields! + */ + private static java.lang.Integer convertFilterFlagNames2Values(java.util.Vector lFlags) + throws java.lang.Exception + { + int nFlags = 0; + java.util.Enumeration it = lFlags.elements(); + while(it.hasMoreElements()) + { + java.lang.String sFlagName = (java.lang.String)it.nextElement(); + + if (sFlagName.equals(FLAGNAME_3RDPARTYFILTER)) + nFlags |= FLAGVAL_3RDPARTYFILTER; + else + if (sFlagName.equals(FLAGNAME_ALIEN)) + nFlags |= FLAGVAL_ALIEN; + else + if (sFlagName.equals(FLAGNAME_ASYNCHRON)) + nFlags |= FLAGVAL_ASYNCHRON; + else + if (sFlagName.equals(FLAGNAME_BROWSERPREFERRED)) + nFlags |= FLAGVAL_BROWSERPREFERRED; + else + if (sFlagName.equals(FLAGNAME_CONSULTSERVICE)) + nFlags |= FLAGVAL_CONSULTSERVICE; + else + if (sFlagName.equals(FLAGNAME_DEFAULT)) + nFlags |= FLAGVAL_DEFAULT; + else + if (sFlagName.equals(FLAGNAME_EXPORT)) + nFlags |= FLAGVAL_EXPORT; + else + if (sFlagName.equals(FLAGNAME_IMPORT)) + nFlags |= FLAGVAL_IMPORT; + else + if (sFlagName.equals(FLAGNAME_INTERNAL)) + nFlags |= FLAGVAL_INTERNAL; + else + if (sFlagName.equals(FLAGNAME_NOTINCHOOSER)) + nFlags |= FLAGVAL_NOTINCHOOSER; + else + if (sFlagName.equals(FLAGNAME_NOTINFILEDIALOG)) + nFlags |= FLAGVAL_NOTINFILEDIALOG; + else + if (sFlagName.equals(FLAGNAME_NOTINSTALLED)) + nFlags |= FLAGVAL_NOTINSTALLED; + else + if (sFlagName.equals(FLAGNAME_OWN)) + nFlags |= FLAGVAL_OWN; + else + if (sFlagName.equals(FLAGNAME_PACKED)) + nFlags |= FLAGVAL_PACKED; + else + if (sFlagName.equals(FLAGNAME_PREFERRED)) + nFlags |= FLAGVAL_PREFERRED; + else + if (sFlagName.equals(FLAGNAME_READONLY)) + nFlags |= FLAGVAL_READONLY; + else + if (sFlagName.equals(FLAGNAME_SILENTEXPORT)) + nFlags |= FLAGVAL_SILENTEXPORT; + else + if (sFlagName.equals(FLAGNAME_TEMPLATE)) + nFlags |= FLAGVAL_TEMPLATE; + else + if (sFlagName.equals(FLAGNAME_TEMPLATEPATH)) + nFlags |= FLAGVAL_TEMPLATEPATH; + else + if (sFlagName.equals(FLAGNAME_USESOPTIONS)) + nFlags |= FLAGVAL_USESOPTIONS; + else + if (sFlagName.equals(FLAGNAME_COMBINED)) + nFlags |= FLAGVAL_COMBINED; + else + throw new java.lang.Exception("unsupported filter flag detected: \""+sFlagName+"\""); + } + + if (nFlags == 0) + throw new java.lang.Exception("no filter flags?"); + + return new java.lang.Integer(nFlags); + } + + //___________________________________________ + + /** converts filter flag values to its string representation. + * + * @param nFlags + * the flag field as int value. + * + * @return [java.util.Vector] + * a list of flag names. + * + * @throws [java.lang.Exception] + * for unsupported flags or empty flag fields! + */ + private static java.util.Vector convertFilterFlagValues2Names(java.lang.Integer nFlags) + throws java.lang.Exception + { + java.util.Vector lFlags = new java.util.Vector(); + int field = nFlags.intValue(); + + if (field == 0) + throw new java.lang.Exception("no filter flags?"); + + if((field & FLAGVAL_IMPORT) == FLAGVAL_IMPORT) + lFlags.add(FLAGNAME_IMPORT); + + if((field & FLAGVAL_EXPORT) == FLAGVAL_EXPORT) + lFlags.add(FLAGNAME_EXPORT); + + if((field & FLAGVAL_TEMPLATE) == FLAGVAL_TEMPLATE) + lFlags.add(FLAGNAME_TEMPLATE); + + if((field & FLAGVAL_INTERNAL) == FLAGVAL_INTERNAL) + lFlags.add(FLAGNAME_INTERNAL); + + if((field & FLAGVAL_TEMPLATEPATH) == FLAGVAL_TEMPLATEPATH) + lFlags.add(FLAGNAME_TEMPLATEPATH); + + if((field & FLAGVAL_OWN) == FLAGVAL_OWN) + lFlags.add(FLAGNAME_OWN); + + if((field & FLAGVAL_ALIEN) == FLAGVAL_ALIEN) + lFlags.add(FLAGNAME_ALIEN); + + if((field & FLAGVAL_USESOPTIONS) == FLAGVAL_USESOPTIONS) + lFlags.add(FLAGNAME_USESOPTIONS); + + if((field & FLAGVAL_DEFAULT) == FLAGVAL_DEFAULT) + lFlags.add(FLAGNAME_DEFAULT); + + if((field & FLAGVAL_NOTINFILEDIALOG) == FLAGVAL_NOTINFILEDIALOG) + lFlags.add(FLAGNAME_NOTINFILEDIALOG); + + if((field & FLAGVAL_NOTINCHOOSER) == FLAGVAL_NOTINCHOOSER) + lFlags.add(FLAGNAME_NOTINCHOOSER); + + if((field & FLAGVAL_ASYNCHRON) == FLAGVAL_ASYNCHRON) + lFlags.add(FLAGNAME_ASYNCHRON); + + if((field & FLAGVAL_READONLY) == FLAGVAL_READONLY) + lFlags.add(FLAGNAME_READONLY); + + if((field & FLAGVAL_NOTINSTALLED) == FLAGVAL_NOTINSTALLED) + lFlags.add(FLAGNAME_NOTINSTALLED); + + if((field & FLAGVAL_CONSULTSERVICE) == FLAGVAL_CONSULTSERVICE) + lFlags.add(FLAGNAME_CONSULTSERVICE); + + if((field & FLAGVAL_3RDPARTYFILTER) == FLAGVAL_3RDPARTYFILTER) + lFlags.add(FLAGNAME_3RDPARTYFILTER); + + if((field & FLAGVAL_PACKED) == FLAGVAL_PACKED) + lFlags.add(FLAGNAME_PACKED); + + if((field & FLAGVAL_SILENTEXPORT) == FLAGVAL_SILENTEXPORT) + lFlags.add(FLAGNAME_SILENTEXPORT); + + if((field & FLAGVAL_BROWSERPREFERRED) == FLAGVAL_BROWSERPREFERRED) + lFlags.add(FLAGNAME_BROWSERPREFERRED); + + if((field & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED) + lFlags.add(FLAGNAME_PREFERRED); + + if((field & FLAGVAL_COMBINED) == FLAGVAL_COMBINED) + lFlags.add(FLAGNAME_COMBINED); + + if((field & FLAGVAL_COMBINED) == FLAGVAL_SUPPORTSSELECTION) + lFlags.add(FLAGNAME_SUPPORTSSELECTION); + + return lFlags; + } + + //___________________________________________ + + /** return a reference to one of our member + * lists for types/filters etc ... + * + * @param eItemType + * specify, which item map is required. + * + * @return [java.util.HashMap] + * a reference(!) to the right member. + * + * @throws [java.lang.Exception] + * if the specified map does not exist. + */ + private java.util.HashMap getItemMap(int eItemType) + throws java.lang.Exception + { + java.util.HashMap rMap = null; + switch(eItemType) + { + case E_TYPE : + rMap = m_lTypes; + break; + + case E_FILTER : + rMap = m_lFilters; + break; + + case E_DETECTSERVICE : + rMap = m_lDetectServices; + break; + + case E_FRAMELOADER : + rMap = m_lFrameLoaders; + break; + + case E_CONTENTHANDLER : + rMap = m_lContentHandlers; + break; + + default: + throw new java.lang.Exception("Invalid item map specified."); + } + return rMap; + } + + //___________________________________________ + + /** return the count of items inside a sub container + * of this cache. + * + * @param eItemType + * specify, which item map is required. + * + * @throws [java.lang.Exception] + * if the specified map does not exist. + */ + public synchronized int getItemCount(int eItemType) + throws java.lang.Exception + { + java.util.HashMap rMap = getItemMap(eItemType); + return rMap.size(); + } + + //___________________________________________ + + /** get a list of all item names of the specified + * sub container. + * + * @param eItemType + * specify, which item map is required. + * + * @throws [java.lang.Exception] + * if the specified map does not exist. + */ + public synchronized java.util.Vector getItemNames(int eItemType) + throws java.lang.Exception + { + java.util.Vector lNames = new java.util.Vector(); + java.util.HashMap rMap = getItemMap(eItemType); + java.util.Iterator it = rMap.keySet().iterator(); + while(it.hasNext()) + lNames.add(it.next()); + return lNames; + } + + //___________________________________________ + + /** get a list of all item names of the specified + * sub coontainer, where items match to given property set. + * + * Note: The given property set must exist at all + * returned items as minimum and every checked property + * value must be equals! Using of reg expressions or + * similar mechanism will not be supported here. + * + * @param eItemType + * specify, which item map is required. + * + * @param aPropSet + * the set of properties, which must + * exist at the returned item as minimum. + * + * @throws [java.lang.Exception] + * if the specified map does not exist. + */ + public synchronized java.util.Vector getMatchedItemNames(int eItemType, + java.util.HashMap aPropSet ) + throws java.lang.Exception + { + java.util.Vector lNames = new java.util.Vector(); + java.util.HashMap rMap = getItemMap(eItemType); + java.util.Iterator it = rMap.keySet().iterator(); + while(it.hasNext()) + { + java.lang.String sItemName = (java.lang.String)it.next(); + java.util.HashMap rItemProps = (java.util.HashMap)rMap.get(sItemName); + + boolean bMatch = Cache.matchPropSet(rItemProps, aPropSet); + if (bMatch) + lNames.add(sItemName); + else + { + java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(1000); + sBuffer.append("entry ["+eItemType+"] \""+sItemName+"\" does not match.\n"); + sBuffer.append("\torg items = {"+rItemProps+"}\n"); + sBuffer.append("\treq items = {"+aPropSet+"}\n"); + + m_aDebug.setDetailedInfo(sBuffer.toString()); + } + } + return lNames; + } + + //___________________________________________ + + /** check if two property sets are equals in its + * shared properties. + * + * Note: Only set properties of the match set will be searched + * inside the original set. And its values must be equals. + * Using of reg expressions or similar mechanism will not + * be supported here. + * + * @param rOrgProps + * the original property set, which should be checked. + * + * @param rMatchProps + * contains the properties, which must be searched + * inside rOrgProps. + * + * @return TRUE if all properties of rMatchProps could be located + * inside rOrgProps. + */ + private static boolean matchPropSet(java.util.HashMap rOrgProps , + java.util.HashMap rMatchProps) + { + java.util.Iterator it = rMatchProps.keySet().iterator(); + while(it.hasNext()) + { + java.lang.String sMatchName = (java.lang.String)it.next(); + java.lang.Object aMatchValue = rMatchProps.get(sMatchName); + + if ( + (!rOrgProps.containsKey(sMatchName) ) || + (!rOrgProps.get(sMatchName).equals(aMatchValue)) + ) + { + return false; + } + } + return true; + } + + //___________________________________________ + + /** return a property set for the queried container item. + * + * @param eItemType + * specify, which item map is required. + * + * @param sItemName + * must be a valid item name of the specified item map. + * + * @return [java.util.HashMap] + * the property set of the queried item. + * Always different from null! + * + * @throws [java.lang.Exception] + * if the specified item does not exists or + * seems to be invalid in general (means null!). + */ + public synchronized java.util.HashMap getItem(int eItemType, + java.lang.String sItemName) + throws java.lang.Exception + { + java.util.HashMap rMap = getItemMap(eItemType); + java.util.HashMap rItem = (java.util.HashMap)rMap.get(sItemName); + if (rItem == null) + throw new java.lang.Exception("Queried item \""+sItemName+"\" does not exist inside this cache."); + return rItem; + } + + //___________________________________________ + + /** return a requested item in XML format. + * + * @param eItemType + * identify the right sub set of this cache + * inside which the requested item should exist. + * e.g. E_TYPE, E_FILTER, ... + * + * @param sItemName + * the name of the request item + * + * @param nXMLFormat + * means the format of the generated xml source. + * + * @return [java.lang.String] + * a xml formated string, which contains all properties + * for this container item. + */ + public synchronized java.lang.String getItemAsXML(int eItemType , + java.lang.String sItemName , + int nXMLFormat) + throws java.lang.Exception + { + // Note: Our internal format must be converted to the target format! + java.util.HashMap rItem = getItem(eItemType, sItemName); + java.util.HashMap rFormatedItem = null; + switch(eItemType) + { + case E_TYPE : + { + rFormatedItem = Cache.convertTypePropsToExternal(rItem, nXMLFormat); + m_aDebug.setGlobalInfo("type to external \""+sItemName+"\""); + } + break; + + case E_FILTER : + { + rFormatedItem = Cache.convertFilterPropsToExternal(rItem, nXMLFormat); + m_aDebug.setGlobalInfo("filter to external \""+sItemName+"\""); + } + break; + + case E_DETECTSERVICE : + { + rFormatedItem = Cache.convertDetectServicePropsToExternal(rItem, nXMLFormat); + m_aDebug.setGlobalInfo("detect service to external \""+sItemName+"\""); + } + break; + + case E_FRAMELOADER : + { + rFormatedItem = Cache.convertFrameLoaderPropsToExternal(rItem, nXMLFormat); + m_aDebug.setGlobalInfo("frame loader to external \""+sItemName+"\""); + } + break; + + case E_CONTENTHANDLER : + { + rFormatedItem = Cache.convertContentHandlerPropsToExternal(rItem, nXMLFormat); + m_aDebug.setGlobalInfo("content handler to external \""+sItemName+"\""); + } + break; + } + + java.lang.StringBuffer sXML = new java.lang.StringBuffer(1000); + int nPrettyTabs = 1; + for (int t=0; t\n"); + sXML.append(XMLHelper.convertPropSetToXML(rFormatedItem, nPrettyTabs+1)); + for (int t=0; t\n"); + + return sXML.toString(); + } + + //___________________________________________ + + /** split the given string (using the specified delimiter) + * and return alist of found string tokens. + * + * Note: Against the normal behaviour of the StringTokenizer class + * this method returns empty tokens too. + * E.g: "0,,1" will return "0" - "" - "1" + * + * @param sTokenString + * the string value, which should be analyzed. + * + * @param sDelim + * the delimiter, which will be used to differe between tokens. + * + * @return [java.util.Vector] + * a list of string tokens. Can be empty - but not null! + */ + private static java.util.Vector splitTokenString(java.lang.String sTokenString, + java.lang.String sDelim ) + { + java.util.Vector lTokens = new java.util.Vector(); + java.util.StringTokenizer aTokenizer = new java.util.StringTokenizer(sTokenString, sDelim, true); + boolean bLastWasDelim = false; + + while (aTokenizer.hasMoreTokens()) + { + java.lang.String sToken = aTokenizer.nextToken(); + if (sToken.equals(sDelim)) + { + if (bLastWasDelim) + { + // last token was a delimiter - new one too + // => an empty token must be placed between these + // two delimiters! Add this empty value to the return list. + lTokens.add(""); + } + else + { + // last token was not a delimiter - new one is such delim + // => ignore this delimiter - but save the information, that + // it occured + bLastWasDelim = true; + } + } + else + { + // new token is no delim + // => Add it to the return list. + lTokens.add(sToken); + // Dont forget to reset this information - so next loop + // will do the right things! + bLastWasDelim = false; + } + } + + return lTokens; + } + + //___________________________________________ + + /** + */ + public synchronized void analyze() + { + m_nDoubleRegisteredFilters = 0; + m_nTypesForFilters = 0; + m_nTypesForDetectServices = 0; + m_nTypesForFrameLoaders = 0; + m_nTypesForContentHandlers = 0; + + // create table of types and all registered filters for such types + // By the way: count all double registrations, where a filter + // uses the same type then another filter. + m_lFilterToTypeRegistrations = new java.util.HashMap(); + java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); + while (aIt1.hasNext()) + { + java.lang.String sFilter = (java.lang.String)aIt1.next(); + java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); + java.lang.String sType = (java.lang.String)aFilter.get(PROPNAME_TYPE); + + java.util.Vector lFilters = (java.util.Vector)m_lFilterToTypeRegistrations.get(sType); + if (lFilters == null) + lFilters = new java.util.Vector(); + else + ++m_nDoubleRegisteredFilters; + lFilters.add(sFilter); + m_lFilterToTypeRegistrations.put(sType, lFilters); + } + + // count, how many types are used by filters, frame loaders or content handlers + aIt1 = m_lTypes.keySet().iterator(); + while (aIt1.hasNext()) + { + java.lang.String sType = (java.lang.String)aIt1.next(); + + java.util.Iterator aIt2 = m_lFilters.keySet().iterator(); + while (aIt2.hasNext()) + { + java.lang.String sItem = (java.lang.String)aIt2.next(); + java.util.HashMap aItem = (java.util.HashMap)m_lFilters.get(sItem); + java.lang.String sTypeReg = (java.lang.String)aItem.get(PROPNAME_TYPE); + + if (sTypeReg.equals(sType)) + { + ++m_nTypesForFilters; + break; + } + } + + aIt2 = m_lDetectServices.keySet().iterator(); + while (aIt2.hasNext()) + { + java.lang.String sItem = (java.lang.String)aIt2.next(); + java.util.HashMap aItem = (java.util.HashMap)m_lDetectServices.get(sItem); + java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); + + if (lTypeReg.contains(sType)) + { + ++m_nTypesForDetectServices; + break; + } + } + + aIt2 = m_lFrameLoaders.keySet().iterator(); + while (aIt2.hasNext()) + { + java.lang.String sItem = (java.lang.String)aIt2.next(); + java.util.HashMap aItem = (java.util.HashMap)m_lFrameLoaders.get(sItem); + java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); + + if (lTypeReg.contains(sType)) + { + ++m_nTypesForFrameLoaders; + break; + } + } + + aIt2 = m_lContentHandlers.keySet().iterator(); + while (aIt2.hasNext()) + { + java.lang.String sItem = (java.lang.String)aIt2.next(); + java.util.HashMap aItem = (java.util.HashMap)m_lContentHandlers.get(sItem); + java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); + + if (lTypeReg.contains(sType)) + { + ++m_nTypesForContentHandlers; + break; + } + } + } + } + + //___________________________________________ + + /** validate all cache entries. + * + * It checks if all made registrations are valid; + * try to repair some simple problems; + * create missing informations on demand ... + * + * @param nFormat + * specify, which configuration format + * must be checked. + * + * @throws [java.lang.Exception] + * if an unrecoverable problem occure. + */ + public synchronized void validate(int nFormat) + throws java.lang.Exception + { + validateTypes(nFormat); + validateFilters(nFormat); + } + + //___________________________________________ + + /** validate all type entries of this cache. + * + * @param nFormat + * specify, which configuration format + * must be checked. + * + * @throws [java.lang.Exception] + * if an unrecoverable problem occure. + */ + private void validateTypes(int nFormat) + throws java.lang.Exception + { + java.util.Iterator aIt1 = m_lTypes.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sType = (java.lang.String)aIt1.next(); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sType); + if (aType == null) + throw new java.lang.Exception("type ["+sType+"] dos not exist realy?!"); + + if ( + (!aType.containsKey(PROPNAME_MEDIATYPE )) || + (!aType.containsKey(PROPNAME_PREFERRED )) || + (!aType.containsKey(PROPNAME_CLIPBOARDFORMAT)) || + (!aType.containsKey(PROPNAME_DOCUMENTICONID )) || + (!aType.containsKey(PROPNAME_URLPATTERN )) || + (!aType.containsKey(PROPNAME_EXTENSIONS )) || + (!aType.containsKey(PROPNAME_UINAME )) + ) + { + throw new java.lang.Exception("Type \""+sType+"\" does not contain all neccessary properties for a 6.0/6.Y format."); + } + + if ( + (((java.util.Vector)aType.get(PROPNAME_EXTENSIONS)).isEmpty()) && + (((java.util.Vector)aType.get(PROPNAME_URLPATTERN)).isEmpty()) + ) + { + throw new java.lang.Exception("Type \""+sType+"\" does not contain any extension nor an url pattern."); + } + + if (((java.util.HashMap)aType.get(PROPNAME_UINAME)).isEmpty()) + throw new java.lang.Exception("Type \""+sType+"\" is not localized."); + + if (nFormat == FORMAT_6Y) + { + if ( + (!aType.containsKey(PROPNAME_UIORDER )) || + (!aType.containsKey(PROPNAME_PREFERREDFILTER)) || + (!aType.containsKey(PROPNAME_DETECTSERVICE )) + ) + { + throw new java.lang.Exception("Type \""+sType+"\" does not contain all neccessary properties for a 6.Y format."); + } + + if (((java.lang.Integer)aType.get(PROPNAME_UIORDER)).intValue() < 0) + throw new java.lang.Exception("Type \""+sType+"\" has invalid value for prop UIOrder."); + + if (((java.lang.String)aType.get(PROPNAME_DETECTSERVICE)).length() < 1) + m_aDebug.setWarning("Type \""+sType+"\" has no detect service registered."); + + java.lang.String sPreferredReg = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); + if ( + (sPreferredReg == null) || + (sPreferredReg.length() < 1 ) + ) + { + m_aDebug.setWarning("Type \""+sType+"\" has no preferred filter ..."); + /*FIXME + * OK - not every type has a filter registered .. but the + * a frame loader MUST(!) exist! Check it. + */ + } + else + { + if (!m_lFilters.containsKey(sPreferredReg)) + throw new java.lang.Exception("Type \""+sType+"\" has no valid preferred filter registration [\""+sPreferredReg+"\"]."); + } + } + } + } + + //___________________________________________ + + /** validate all filter entries of this cache. + * + * @param nFormat + * specify, which configuration format + * must be checked. + * + * @throws [java.lang.Exception] + * if an unrecoverable problem occure. + */ + public synchronized void validateFilters(int nFormat) + throws java.lang.Exception + { + java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sFilter = (java.lang.String)aIt1.next(); + java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); + if (aFilter == null) + throw new java.lang.Exception("filter ["+sFilter+"] dos not exist realy?!"); + + if ( + (!aFilter.containsKey(PROPNAME_DOCUMENTSERVICE )) || + (!aFilter.containsKey(PROPNAME_FILEFORMATVERSION)) || + (!aFilter.containsKey(PROPNAME_FILTERSERVICE )) || + (!aFilter.containsKey(PROPNAME_FLAGS )) || + (!aFilter.containsKey(PROPNAME_TEMPLATENAME )) || + (!aFilter.containsKey(PROPNAME_TYPE )) || + (!aFilter.containsKey(PROPNAME_UICOMPONENT )) || + (!aFilter.containsKey(PROPNAME_USERDATA )) + ) + { + throw new java.lang.Exception("Filter \""+sFilter+"\" does not contain all neccessary properties for a 6.0/6.Y format."); + } + + if (((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue() < 1) + throw new java.lang.Exception("Filter \""+sFilter+"\" does not have a valid flag field."); + + if (!m_lTypes.containsKey(aFilter.get(PROPNAME_TYPE))) + throw new java.lang.Exception("Filter \""+sFilter+"\" is not registered for a well known type."); + + if (nFormat == FORMAT_60) + { + if ( + (!aFilter.containsKey(PROPNAME_ORDER )) || + (!aFilter.containsKey(PROPNAME_UINAME)) + ) + { + throw new java.lang.Exception("Filter \""+sFilter+"\" does not contain all neccessary properties for a 6.0 format."); + } + + if (((java.lang.Integer)aFilter.get(PROPNAME_ORDER)).intValue() < 0) + throw new java.lang.Exception("Filter \""+sFilter+"\" does not have a valid Order value."); + + if (((java.util.HashMap)aFilter.get(PROPNAME_UINAME)).isEmpty()) + throw new java.lang.Exception("Filter \""+sFilter+"\" is not localized."); + } +/*TODO + depends from the configuration item "remove_filter_flag_preferred" ... + + if (nFormat == FORMAT_6Y) + { + int flags = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); + if ((flags & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED) + throw new java.lang.Exception("Filter \""+sFilter+"\" has superflous Preferred flag set. Please remove this flag. ["+flags+"]"); + } +*/ + } + } + + /*TODO + * - remove graphic filters! + * - move detect services to types + */ + + public synchronized void transform60to6Y(boolean bCreateCombineFilterFlag , + boolean bRemoveFilterFlagBrowserPreferred, + boolean bRemoveFilterFlagPreferred , + boolean bRemoveFilterFlag3rdparty , + boolean bRemoveFilterUINames , + boolean bRemoveGraphicFilters , + boolean bSetDefaultDetector ) + throws java.lang.Exception + { + // remove some superflous cache entries ... + // everything related to "load macros" + // Macros should be dispatched instead of loaded! + if (m_lTypes.containsKey("macro")) + { + m_lTypes.remove("macro"); + m_aDebug.setDetailedInfo("superflous type \"macro\" was removed"); + } + if (m_lFrameLoaders.containsKey("com.sun.star.comp.sfx2.SfxMacroLoader")) + { + m_lFrameLoaders.remove("com.sun.star.comp.sfx2.SfxMacroLoader"); + m_aDebug.setDetailedInfo("superflous frame loader \"com.sun.star.comp.sfx2.SfxMacroLoader\" was removed"); + } + + // step over all filters and check her properties and references + java.util.Vector lPreferredFilters = new java.util.Vector(); + java.util.Vector lNoRealFilters = new java.util.Vector(); + java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sFilter = (java.lang.String)aIt1.next(); + java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); + + // remove the "graphic helper filters" used by draw and impress + // They dont have any valid document service name set and cant be handled + // by our generic FrameLoader! + // They must be moved to her own configuration ... + + if ( + (bRemoveGraphicFilters ) && + (((java.lang.String)aFilter.get(PROPNAME_DOCUMENTSERVICE)).length() < 1) + ) + { + lNoRealFilters.add(sFilter); + continue; + } + + java.lang.String sTypeReg = (java.lang.String)aFilter.get(PROPNAME_TYPE); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); + + // move UINames of filters to types + java.util.HashMap lFilterUINames = (java.util.HashMap)aFilter.get(PROPNAME_UINAME); + java.util.HashMap lTypeUINames = (java.util.HashMap)aType.get(PROPNAME_UINAME); + java.util.HashMap lPatchUINames = new java.util.HashMap(); + + java.util.Iterator pUINames = lTypeUINames.keySet().iterator(); + while(pUINames.hasNext()) + { + java.lang.String sLocale = (java.lang.String)pUINames.next(); + java.lang.String sValue = (java.lang.String)lTypeUINames.get(sLocale); + lPatchUINames.put(sLocale, sValue); + } + + pUINames = lFilterUINames.keySet().iterator(); + while(pUINames.hasNext()) + { + java.lang.String sLocale = (java.lang.String)pUINames.next(); + java.lang.String sValue = (java.lang.String)lFilterUINames.get(sLocale); + lPatchUINames.put(sFilter+":"+sLocale, sValue); + } + aType.put(PROPNAME_UINAME, lPatchUINames); + + // set generic filter service wrapper for our own native filters! + // By the way: The format types of such filters can be detected by our + // generic detector too. + if ( + (bSetDefaultDetector ) && + (((java.lang.String)aFilter.get(PROPNAME_FILTERSERVICE)).length() < 1) + ) + { + /*ME_THINKING aFilter.put(PROPNAME_FILTERSERVICE, FILTERSERVICE_NATIVEWARPPER);*/ + aType.put(PROPNAME_DETECTSERVICE, GENERIC_DETECTSERVICE); + } + + // move the preferred filter information to any type + // Set the filter name to the type for which the filter is registered. + // If this type already have a set PreferredFilter value, check if the current filter + // has the preferred flag set. If not ignore it - otherwhise overwrite the + // current information at the type. But look for multiple preferred filter relations ... + // means: look if more the one filter has set the preferred flag for the same type! + + /* Attention! + * + * Dont remove the preferred flag from any filter! ... not here. + * Otherwhise next loop can't detect ambigous preferred registrations! + * Add filter to a temp. list, which can be used later to remove the preferred + * flag ... + */ + + int flags1 = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); + java.lang.String sDocSrv = (java.lang.String)aFilter.get(PROPNAME_DOCUMENTSERVICE); + if (sDocSrv.length()>0)// without a doc service its not a real filter - its a graphic filter! + { + boolean preferred1 = ((flags1 & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED); + if (preferred1) + lPreferredFilters.add(aFilter); + + java.lang.String sAlreadyRegisteredFilter = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); + // no registration => set this filter as "any possible one"! + if (sAlreadyRegisteredFilter.length() < 1) + aType.put(PROPNAME_PREFERREDFILTER, sFilter); + else + { + java.util.HashMap aAlreadyRegisteredFilter = (java.util.HashMap)m_lFilters.get(sAlreadyRegisteredFilter); + int flags2 = ((java.lang.Integer)aAlreadyRegisteredFilter.get(PROPNAME_FLAGS)).intValue(); + boolean preferred2 = ((flags2 & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED); + + // two preferred filters for the same type! => error + if (preferred1 && preferred2) + { + java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); + sMsg.append("More the one preferred filter detected for the same type.\n"); + sMsg.append("\ttype = \""+sTypeReg+"\"\n"); + sMsg.append("\tfilter[1] = \""+sAlreadyRegisteredFilter+"\"\n"); + sMsg.append("\tfilter[2] = \""+sFilter+"\"\n"); + throw new java.lang.Exception(sMsg.toString()); + } + else + // overwrite the "any possible" filter with a real preferred one + if (preferred1 && !preferred2) + aType.put(PROPNAME_PREFERREDFILTER, sFilter); + } + } + + // create the new combined filter flag if required + if (bCreateCombineFilterFlag) + { + if ( + ((flags1 & FLAGVAL_IMPORT) == FLAGVAL_IMPORT) && + ((flags1 & FLAGVAL_EXPORT) == FLAGVAL_EXPORT) + ) + { + flags1 |= FLAGVAL_COMBINED; + flags1 &= ~FLAGVAL_IMPORT ; + flags1 &= ~FLAGVAL_EXPORT ; + aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); + } + } + + // remove some obsolete filter flags + if (bRemoveFilterFlagBrowserPreferred) + { + flags1 &= ~FLAGVAL_BROWSERPREFERRED; + aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); + } + + if (bRemoveFilterFlag3rdparty) + { + flags1 &= ~FLAGVAL_3RDPARTYFILTER; + aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); + } + + // if its a filter with an UI order ... + // move this information to the registered type. + // Note: Because more then one filter can be registered for the same type. + // Handle it as an error ... till we find a better transformation! + java.lang.Integer nOrder = (java.lang.Integer)aFilter.get(PROPNAME_ORDER); + java.lang.Integer nUIOrder = (java.lang.Integer)aType.get(PROPNAME_UIORDER); + int order = nOrder.intValue(); + int uiorder = nUIOrder.intValue(); + + if (order > 0) + { + if ( + (uiorder < 1 ) || + (uiorder > order) + ) + { + aType.put(PROPNAME_UIORDER, nOrder); + m_aDebug.setDetailedInfo("moved order value "+nOrder+" from filter \""+sFilter+"\" to type \""+sTypeReg+"\""); + } + else + m_aDebug.setDetailedInfo("ignore order value [order="+nOrder+",uiorder="+nUIOrder+"] for filter \""+sFilter+"\" and type \""+sTypeReg+"\""); + } + } + + // NOW ... remove the preferred flags from every filter, which it has set. + java.util.Enumeration aIt2 = null; + if (bRemoveFilterFlagPreferred) + { + aIt2 = lPreferredFilters.elements(); + while (aIt2.hasMoreElements()) + { + java.util.HashMap aFilter = (java.util.HashMap)aIt2.nextElement(); + int flags = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); + flags &= ~FLAGVAL_PREFERRED; + aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags)); + } + } + + // NOW ... remove all "no real filters" like the graphich helper filters of + // draw and impress! + aIt2 = lNoRealFilters.elements(); + while (aIt2.hasMoreElements()) + m_lFilters.remove(aIt2.nextElement()); + + // step over all detect services and move this information directly to + // the corresponding types + // Overwrite possibel default registrations with a real existing one! + aIt1 = m_lDetectServices.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sDetector = (java.lang.String)aIt1.next(); + java.util.HashMap aDetector = (java.util.HashMap)m_lDetectServices.get(sDetector); + java.util.Vector lTypeReg = (java.util.Vector)aDetector.get(PROPNAME_TYPES); + aIt2 = lTypeReg.elements(); + while(aIt2.hasMoreElements()) + { + java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); + + if (aType == null) + { + m_aDebug.setWarning("Detector \""+sDetector+"\" seem to be registered for unknown type \""+sTypeReg+"\""); + continue; + } + + java.lang.Object aAlreadyRegisteredDetector = aType.get(PROPNAME_DETECTSERVICE); + if (aAlreadyRegisteredDetector != null && ((java.lang.String)aAlreadyRegisteredDetector).length() > 0) + { + java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); + sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a detect service\n"); + sMsg.append("\tdetect service[1] = \""+(java.lang.String)aAlreadyRegisteredDetector+"\"\n"); + sMsg.append("\tdetect service[2] = \""+sDetector+"\"\n"); + m_aDebug.setWarning(sMsg.toString()); + } + aType.put(PROPNAME_DETECTSERVICE, sDetector); + m_aDebug.setGlobalInfo("move detector \""+sDetector+"\" to type \""+sTypeReg+"\""); + } + } + + // because all detect service was registered as type properties directly ... + // remove all detect service objects of this cache! + m_lDetectServices.clear(); + + // step over all frame loader and move this information directly to + // the corresponding types + // Overwrite possibel default registrations with a real existing one! + aIt1 = m_lFrameLoaders.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sLoader = (java.lang.String)aIt1.next(); + java.util.HashMap aLoader = (java.util.HashMap)m_lFrameLoaders.get(sLoader); + java.util.Vector lTypeReg = (java.util.Vector)aLoader.get(PROPNAME_TYPES); + aIt2 = lTypeReg.elements(); + while(aIt2.hasMoreElements()) + { + java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); + java.lang.String sAlreadyRegisteredLoader = (java.lang.String)aType.get(PROPNAME_FRAMELOADER); + if (sAlreadyRegisteredLoader != null && sAlreadyRegisteredLoader.length() > 0) + { + java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); + sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a frame loader\n"); + sMsg.append("\tframe loader[1] = \""+sAlreadyRegisteredLoader+"\"\n"); + sMsg.append("\tframe loader[2] = \""+sLoader+"\"\n"); + m_aDebug.setWarning(sMsg.toString()); + } + aType.put(PROPNAME_FRAMELOADER, sLoader); + System.out.println("move loader \""+sLoader+"\" to type \""+sTypeReg+"\""); + } + } + + m_lFrameLoaders.clear(); + + // step over all content handler and move this information directly to + // the corresponding types + // Overwrite possibel default registrations with a real existing one! + aIt1 = m_lContentHandlers.keySet().iterator(); + while(aIt1.hasNext()) + { + java.lang.String sHandler = (java.lang.String)aIt1.next(); + java.util.HashMap aHandler = (java.util.HashMap)m_lContentHandlers.get(sHandler); + java.util.Vector lTypeReg = (java.util.Vector)aHandler.get(PROPNAME_TYPES); + aIt2 = lTypeReg.elements(); + while(aIt2.hasMoreElements()) + { + java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); + java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); + java.lang.String sAlreadyRegisteredHandler = (java.lang.String)aType.get(PROPNAME_CONTENTHANDLER); + if (sAlreadyRegisteredHandler != null && sAlreadyRegisteredHandler.length() > 0) + { + java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); + sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a content handler\n"); + sMsg.append("\tcontent handler[1] = \""+sAlreadyRegisteredHandler+"\"\n"); + sMsg.append("\tcontent handler[2] = \""+sHandler+"\"\n"); + m_aDebug.setWarning(sMsg.toString()); + } + aType.put(PROPNAME_CONTENTHANDLER, sHandler); + System.out.println("move handler \""+sHandler+"\" to type \""+sTypeReg+"\""); + } + } + + m_lContentHandlers.clear(); + +/* + int c = m_lTypes.size(); + java.lang.String[] lT1 = new java.lang.String[c]; + java.lang.String[] lT2 = new java.lang.String[c]; + long nUPS = 0; + + int i = 0; + aIt1 = m_lTypes.keySet().iterator(); + while(aIt1.hasNext()) + { + lT1[i] = (java.lang.String)aIt1.next(); + lT2[i] = lT1[i]; + ++i; + } + + for (int i1=0; i1 search from left to right + int len = lCommandLineArgs[arg].length(); + int pos = lCommandLineArgs[arg].indexOf('='); + if (pos != -1) + { + java.lang.String sArg = lCommandLineArgs[arg].substring(0,pos); + java.lang.String sValue = lCommandLineArgs[arg].substring(pos+1); + setProperty(sArg, sValue); + continue; + } + + // is it a boolean argument? + // Note: Because "--" and "-" will be interpreted as the same + // we search from right to left! + pos = lCommandLineArgs[arg].lastIndexOf('-'); + if (pos == -1) + pos = lCommandLineArgs[arg].lastIndexOf('/'); + if (pos != -1) + { + java.lang.String sArg = lCommandLineArgs[arg].substring(pos+1); + setProperty(sArg, java.lang.String.valueOf(true)); + continue; + } + + // There is an unknown format used by this argument ... + throw new MalformedCommandLineException("Invalid command line detected. The argument \""+lCommandLineArgs[arg]+"\" use an unsupported format."); + } + } + + //------------------------------------------- + /** indicates if the given command line includes + * a help request. + * + * @return True if there was an explicit help request. + */ + public synchronized boolean isHelp() + { + return ( + (containsKey("help")) || + (containsKey("?") ) || + (containsKey("h") ) + ); + } + + //------------------------------------------- + /** indicates if the gioven command line was empty. + * + * @return True if there was an empty command line. + */ + public synchronized boolean isEmpty() + { + return m_bEmpty; + } + + //------------------------------------------- + /** returns the value of sProp as boolean value. + * + * @param sProp + * the name of the parameter. + * + * @return The boolean value of the requested property. + * + * @throw [NoSuchElementException] + * if the requested property does not exists. + */ + public synchronized boolean getBoolean(java.lang.String sProp) + throws java.util.NoSuchElementException + { + java.lang.String sValue = getProperty(sProp); + if (sValue == null) + throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); + return new java.lang.Boolean(sValue).booleanValue(); + } + + public synchronized boolean getBoolean(java.lang.String sProp , + boolean bDefault) + { + java.lang.String sDefault = java.lang.String.valueOf(bDefault); + java.lang.String sValue = getProperty(sProp, sDefault); + return new java.lang.Boolean(sValue).booleanValue(); + } + + //------------------------------------------- + /** returns the value of sProp as int value. + * + * @param sProp + * the name of the parameter. + * + * @return The int value of the requested property. + * + * @throw [NoSuchElementException] + * if the requested property does not exists. + */ + public synchronized int getInt(java.lang.String sProp) + throws java.util.NoSuchElementException + { + java.lang.String sValue = getProperty(sProp); + if (sValue == null) + throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); + return new java.lang.Integer(sValue).intValue(); + } + + public synchronized int getInt(java.lang.String sProp , + int nDefault) + { + java.lang.String sDefault = java.lang.String.valueOf(nDefault); + java.lang.String sValue = getProperty(sProp, sDefault); + return new java.lang.Integer(sValue).intValue(); + } + + //------------------------------------------- + /** returns the value of sProp as string value. + * + * @param sProp + * the name of the parameter. + * + * @return The string value of the requested property. + * + * @throw [NoSuchElementException] + * if the requested property does not exists. + */ + public synchronized java.lang.String getString(java.lang.String sProp) + throws java.util.NoSuchElementException + { + java.lang.String sValue = getProperty(sProp); + if (sValue == null) + throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); + return sValue; + } + + //------------------------------------------- + /** returns the value of sProp as string list value! + * + * @descr The delimiter must be well known and + * it must be clear if trailing/leading + * whitespaces must be ignored or not. + * + * @param sProp + * the name of the parameter. + * + * @param sDelim + * the delimiter, which must be used to split + * the config string value into an array. + * + * @param bTrim + * if its set to true, trailing and leading whitespace + * characters will be ommited. + * + * @param bDecode + * if its set to TRUE all liste items will be + * interpreted as "" and converted to ! + * + * @return The string list value of the requested property. + * + * @throw [NoSuchElementException] + * if the requested property does not exists. + */ + public synchronized java.util.Vector getStringList(java.lang.String sProp , + java.lang.String sDelimiter, + boolean bTrim , + boolean bDecode ) + throws java.util.NoSuchElementException + { + java.lang.String sValue = getProperty(sProp); + if (sValue == null) + throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); + + java.util.Vector lValue = new java.util.Vector(); + try + { + java.util.StringTokenizer lTokens = new java.util.StringTokenizer(sValue, sDelimiter); + while(lTokens.hasMoreTokens()) + { + java.lang.String sToken = lTokens.nextToken(); + // remove trailing/leading whitespaces + if (bTrim) + sToken = sToken.trim(); + // remove "" + if ( + (bDecode ) && + (sToken.indexOf("\"") == 0 ) && + (sToken.lastIndexOf("\"") == sToken.length()-1) + ) + { + sToken = sToken.substring(1, sToken.length()-1); + } + lValue.add(sToken); + } + } + catch(java.lang.Throwable ex) + { lValue.clear(); } + + return lValue; + } +} diff --git a/l10ntools/source/filter/utils/FileHelper.java b/l10ntools/source/filter/utils/FileHelper.java new file mode 100644 index 000000000000..71f51cf36bf6 --- /dev/null +++ b/l10ntools/source/filter/utils/FileHelper.java @@ -0,0 +1,766 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: FileHelper.java,v $ + * $Revision: 1.13 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.filter.config.tools.utils; + +// __________ Imports __________ + +import java.io.*; +import java.lang.*; +import java.net.*; +import java.util.*; + +// __________ Implementation __________ + +/** + * It collects some static helper functons to handle file system specific problems. + * Sometimes it's neccessary to convert URL from/to system pathes; + * or from string notation to structural versions (e.g. com.sun.star.util.URL). + * And sometimes java had another notation then the office it has. + * Further it provides functionality to work easiear with the java.io.File class of java. + * + * + */ +public class FileHelper +{ + // ____________________ + + /** + * Because the office need URLs for loading/saving documents + * we must convert used system pathes. + * And java use another notation for file URLs ... correct it. + * + * @param aSystemPath + * represent the file in system notation + * + * @return [String] + * a file url which represent the given system path + */ + public static java.lang.String getFileURLFromSystemPath(java.io.File aSystemPath) + { + System.out.println("TODO: must be adapted to java 1.3 :-("); + System.exit(-1); +/*TODO_JAVA + try + { + sFileURL = aSystemPath.toURI().toURL().toString(); + } + catch( MalformedURLException exWrong ) + { + sFileURL = null; + } +*/ + java.lang.String sFileURL = null; + + // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones! + // => correct this problem first, otherwise office can't use these URL's + if( + (sFileURL != null ) && + (sFileURL.startsWith("file:/") == true ) && + (sFileURL.startsWith("file://") == false) + ) + { + java.lang.StringBuffer sWorkBuffer = new java.lang.StringBuffer(sFileURL); + sWorkBuffer.insert(6,"//"); + sFileURL = sWorkBuffer.toString(); + } + + return sFileURL; + } + + // ____________________ + + /** + * The same as getFileURLFromSystemPath() before but uses string parameter instead + * of a java.io.File type. It exist to supress converting of neccessary parameters in the + * outside code. But of course getFileURLFromSystemPath(File) will be a little bit faster + * then this method ... + * + * @param sSystemPath + * represent the file in system notation + * + * @return [String] + * a file url which represent the given system path + */ + public static java.lang.String getFileURLFromSystemPath(java.lang.String sSystemPath) + { + return getFileURLFromSystemPath(new java.io.File(sSystemPath)); + } + + // ____________________ + + /** + * Does the same as getFileURLFromSystemPath() before ... but uses + * the given protocol string (e.g."http://") insted of "file:///". + * + * @param aSystemPath + * represent the file in system notation + * + * @param aBasePath + * define the base path of the aSystemPath value, + * which must be replaced with the value of "sServerPath". + * + * @param sServerURL + * Will be used to replace sBasePath. + * + * @example + * System Path = "d:\test\file.txt" + * Base Path = "d:\test" + * Server Path = "http://alaska:8000" + * => "http://alaska:8000/file.txt" + * + * @return [String] + * an url which represent the given system path + * and uses the given protocol + */ + public static java.lang.String getURLWithProtocolFromSystemPath(java.io.File aSystemPath, + java.io.File aBasePath , + java.lang.String sServerURL ) + { + System.out.println("TODO: must be adapted to java 1.3 :-("); + System.exit(-1); + + java.lang.String sFileURL = FileHelper.getFileURLFromSystemPath(aSystemPath); + java.lang.String sBaseURL = FileHelper.getFileURLFromSystemPath(aBasePath ); + + // cut last '/'! + if (sBaseURL.lastIndexOf('/')==(sBaseURL.length()-1)) + sBaseURL = sBaseURL.substring(0,sBaseURL.length()-1); + + // cut last '/'! + if (sServerURL.lastIndexOf('/')==(sServerURL.length()-1)) + sServerURL = sServerURL.substring(0,sServerURL.length()-1); + +//TODO_JAVA java.lang.String sURL = sFileURL.replaceFirst(sBaseURL,sServerURL); + java.lang.String sURL = null; + return sURL; + } + + // ____________________ + + /** + * The same as getURLWithProtocolFromSystemPath() before but uses string parameter instead + * of a java.io.File types. It exist to supress converting of neccessary parameters in the + * outside code. But of course getURLWithProtocolFromSystemPath(File,File,String) will be + * a little bit faster then this method ... + * + * @param sSystemPath + * represent the file in system notation + * + * @param sBasePath + * define the base path of the aSystemPath value, + * which must be replaced with the value of "sServerPath". + * + * @param sServerPath + * Will be used to replace sBasePath. + * + * @example + * System Path = "d:\test\file.txt" + * Base Path = "d:\test" + * Server Path = "http://alaska:8000" + * => "http://alaska:8000/file.txt" + * + * @return [String] + * an url which represent the given system path + * and uses the given protocol + */ + public static java.lang.String getURLWithProtocolFromSystemPath(java.lang.String sSystemPath, + java.lang.String sBasePath , + java.lang.String sServerPath) + { + return getURLWithProtocolFromSystemPath(new java.io.File(sSystemPath), new java.io.File(sBasePath), sServerPath); + } + + //_________________________________ + + /** + * Return a list of all available files of a directory. + * We filter sub directories. All other files + * are returned. So they can be used for further purposes. + * One parameter define the start directory, + * another one enable/disable recursive search into sub directories. + * + * @param aRoot + * the start directory, which should be analyzed. + * + * @param bRecursive + * enable/disable search in sub directories. + * + * @return [Vector] + * a filtered list of java java.io.File objects of all available files + * of the start dir (and may of its sub directories). + */ + public static java.util.Vector getSystemFilesFromDir(java.io.File aRoot , + boolean bRecursive) + { + java.io.File[] lAllFiles = aRoot.listFiles(); + if (lAllFiles == null) + return null; + + int c = lAllFiles.length; + java.util.Vector lFilteredFiles = new java.util.Vector(c); + for (int i=0; i=48 && c<=57 // 0-9 + && + c>=97 && c<=122 // a-z + && + c>=65 && c<=90 // A-Z + ) + { + sNewName.append(c); + } + else + { + sNewName.append("_"); + } + } + + return sNewName.toString(); + } + + //___________________________________________ + + /** it removes all child nodes of a file system directory. + * + * @param aDirectory + * points to the directory, which should be made empty. + * + * @param bFilesOnly + * force deletion of files only. If its set to TRUE, + * no subdirectory will be removed. + * + * @throw [java.io.IOException] + * if some of the child nodes couldn't be removed. + */ + public static void makeDirectoryEmpty(java.io.File aDirectory, + boolean bFilesOnly) + throws java.io.IOException + { + if (!aDirectory.isDirectory()) + throw new java.io.FileNotFoundException("\""+aDirectory.toString()+"\" is not a directory."); + + java.io.File[] lChilds = aDirectory.listFiles(); + for (int f=0; f0) + sBuffer.append(aEncodedBuffer, 0, nReadCount); + + aEncodedReader.close(); + } + + //___________________________________________ + private static void logEncodingData(java.lang.StringBuffer sLog , + int nUTF8 , + int nByteOrg1 , + int nByteOrg2 , + int nByteOrg3 , + int nByteOrg4 , + int nByte1 , + int nByte2 , + int nByte3 , + int nByte4 , + int nEncodingType) + { + sLog.append("["+nEncodingType+"]\t"); + sLog.append((int)nUTF8+"\t="); + sLog.append("\t"+nByteOrg1+"/"+nByte1); + sLog.append("\t"+nByteOrg2+"/"+nByte2); + sLog.append("\t"+nByteOrg3+"/"+nByte3); + sLog.append("\t"+nByteOrg4+"/"+nByte4); + sLog.append("\n"); + } + + //___________________________________________ + private static char impl_convertBytesToChar(int nByte1, int nByte2, int nByte3, int nByte4) + { + return (char)((nByte1*0x40000)+(nByte2*0x1000)+(nByte3*0x40)+nByte4); + } + + //___________________________________________ + private static int impl_readAndCheckNextByte(byte[] aBuffer , + int nBufPos , + int nBufLength , + int nMinRange , + int nMaxRange ) + throws java.lang.Exception + { + if (nBufPos>=nBufLength) + throw new java.lang.Exception("impl_readAndCheckNextByte()\nEnd of buffer reached."); + + int nByte = aBuffer[nBufPos] & 0xFF; + if ( + (nByte < nMinRange) || + (nByte > nMaxRange) + ) + { + throw new java.lang.Exception("impl_readAndCheckNextByte()\nByte does not fit the specified range."); + } + + return nByte; + } + + //___________________________________________ + public static void readAndCheckUTF8File(java.io.File aFile , + java.lang.StringBuffer sBuffer) + throws java.io.IOException + { + java.io.FileInputStream aByteStream = new java.io.FileInputStream(aFile.getAbsolutePath()); + byte[] aBuffer = new byte[4096]; + int nReadCount = 0; + int nByteOrg_1 = 0; + int nByteOrg_2 = 0; + int nByteOrg_3 = 0; + int nByteOrg_4 = 0; + int nByte_1 = 0; + int nByte_2 = 0; + int nByte_3 = 0; + int nByte_4 = 0; + char nUTF8 = 0; + int i = 0; + int nEncodingType = 0; + java.lang.StringBuffer sLog = new java.lang.StringBuffer(); + + try + { + + while((nReadCount=aByteStream.read(aBuffer))>0) + { + i=0; + while (i= 0x00) && + (nByteOrg_1 <= 0x7F) + ) + { + nEncodingType = 1; + nUTF8 = (char)nByte_1; + } + // ------------------------------------------------------------ + // 02 + // 1 byte: 110xxxxx + // 2 byte: 101xxxxx + // ------------------------------------------------------------ + else + if ( + (nByteOrg_1 >= 0xC2) && + (nByteOrg_1 <= 0xDF) + ) + { + nEncodingType = 2; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_1 = nByteOrg_1-0xC2; + nByte_2 = nByteOrg_2-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0,0,nByte_1, nByte_2); + } + // ------------------------------------------------------------ + // 03 + // 1 byte: 11100000 + // 2 byte: 101xxxxx + // 3 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if (nByteOrg_1 == 0xE0) + { + nEncodingType = 3; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0xA0, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_2 = nByteOrg_2-0xA0; + nByte_3 = nByteOrg_3-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0,0,nByte_2, nByte_3); + } + // ------------------------------------------------------------ + // 04 + // 1 byte: 111xxxxx + // 2 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if ( + (nByteOrg_1 >= 0xE1) && + (nByteOrg_1 <= 0xEC) + ) + { + nEncodingType = 4; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_1 = nByteOrg_1-0xE1; + nByte_2 = nByteOrg_2-0x80; + nByte_3 = nByteOrg_3-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0,nByte_1, nByte_2, nByte_3); + } + // ------------------------------------------------------------ + // 05 + // 1 byte: 11101101 + // 2 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if (nByteOrg_1 == 0xED) + { + nEncodingType = 5; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0x9F); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_2 = nByteOrg_2-0x80; + nByte_3 = nByteOrg_3-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0,0, nByte_2, nByte_3); + } + // ------------------------------------------------------------ + // 06 + // 1 byte: 1110111x + // 2 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if ( + (nByteOrg_1 >= 0xEE) && + (nByteOrg_1 <= 0xEF) + ) + { + nEncodingType = 6; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_1 = nByteOrg_1-0xEE; + nByte_2 = nByteOrg_2-0x80; + nByte_3 = nByteOrg_3-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0,nByte_1, nByte_2, nByte_3); + } + // ------------------------------------------------------------ + // 07 + // 1 byte: 11110000 + // 2 byte: 1001xxxx + // 3 byte: 10xxxxxx + // 4 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if (nByteOrg_1 == 0xF0) + { + nEncodingType = 7; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x90, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_2 = nByteOrg_2-0x90; + nByte_3 = nByteOrg_3-0x80; + nByte_4 = nByteOrg_4-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0, nByte_2, nByte_3, nByte_4); + } + // ------------------------------------------------------------ + // 08 + // 1 byte: 111100xx + // 2 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if ( + (nByteOrg_1 >= 0xF1) && + (nByteOrg_1 <= 0xF3) + ) + { + nEncodingType = 8; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_1 = nByteOrg_1-0xF1; + nByte_2 = nByteOrg_2-0x80; + nByte_3 = nByteOrg_3-0x80; + nByte_4 = nByteOrg_4-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(nByte_1, nByte_2, nByte_3, nByte_4); + } + // ------------------------------------------------------------ + // 09 + // 1 byte: 11110100 + // 2 byte: 10xxxxxx + // 3 byte: 10xxxxxx + // 4 byte: 10xxxxxx + // ------------------------------------------------------------ + else + if (nByteOrg_1 == 0xF0) + { + nEncodingType = 9; + nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); + nByte_2 = nByteOrg_2-0x80; + nByte_3 = nByteOrg_3-0x80; + nByte_4 = nByteOrg_4-0x80; + nUTF8 = FileHelper.impl_convertBytesToChar(0, nByte_2, nByte_3, nByte_4); + } + // wrong encoding ? + else + { + throw new java.lang.Exception("Non well formed UTF-8 encoding."); + } + + sBuffer.append(nUTF8); + // -> DEBUG ! + FileHelper.logEncodingData(sLog, nUTF8, nByteOrg_1, nByteOrg_2, nByteOrg_3, nByteOrg_4, nByte_1, nByte_2, nByte_3, nByte_4, nEncodingType); + // <- DEBUG ! + } + } + + } + catch(java.lang.Throwable ex) + { + // -> DEBUG ! + FileHelper.logEncodingData(sLog, nUTF8, nByteOrg_1, nByteOrg_2, nByteOrg_3, nByteOrg_4, nByte_1, nByte_2, nByte_3, nByte_4, nEncodingType); + + java.io.File aDir = new java.io.File(aFile.getParent()); + java.lang.String sDump = aFile.getName(); + java.io.File aDump = FileHelper.createUniqueFile(aDir, sDump, "dump"); + FileHelper.writeEncodedBufferToFile(aDump, "UTF-8", false, sLog); + // <- DEBUG ! + + java.lang.String sMsg = "File '"+aFile.getPath()+"' is not encoded right as UTF-8."; + throw new java.io.IOException(sMsg); + } + + aByteStream.close(); + } + + //___________________________________________ + + /** writes the given string buffer into the specified file + * using the specified encoding. + * + * Further it can be set, if the file should be expanded + * or replaced by this new string buffer. + * + * @param aFile + * must point to a system file. It can already exist! + * e.g.: "c:\temp\test.txt" + * "/tmp/test.txt" + * + * @param sEncoding + * will be used to encode the string content inside the file. + * e.g.: "UTF8" + * + * @param bAppend + * specify if an already existing file will be + * expanded or replaced. + * + * @param sBuffer + * the new string content for this file. + */ + public static void writeEncodedBufferToFile(java.io.File aFile , + java.lang.String sEncoding, + boolean bAppend , + java.lang.StringBuffer sBuffer ) + throws java.io.IOException + { + java.io.FileOutputStream aByteStream = new java.io.FileOutputStream(aFile.getAbsolutePath(), bAppend); + java.io.OutputStreamWriter aEncodedWriter = new java.io.OutputStreamWriter(aByteStream, sEncoding); + + java.lang.String sTemp = sBuffer.toString(); + aEncodedWriter.write(sTemp, 0, sTemp.length()); + + aEncodedWriter.flush(); + aEncodedWriter.close(); + + if (!aFile.exists()) + throw new java.io.IOException("File \""+aFile.getAbsolutePath()+"\" not written correctly."); + } +} diff --git a/l10ntools/source/filter/utils/Logger.java b/l10ntools/source/filter/utils/Logger.java new file mode 100644 index 000000000000..7657eba5f426 --- /dev/null +++ b/l10ntools/source/filter/utils/Logger.java @@ -0,0 +1,177 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: Logger.java,v $ + * $Revision: 1.8 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.filter.config.tools.utils; + +//_______________________________________________ +// imports + +import java.lang.*; +import java.util.*; + +//_______________________________________________ +// definition + +/** can be used to print out some debug messages + * and group it into warnings/errors or info statements. + * + * + */ +public class Logger +{ + //___________________________________________ + // const + + /** only error message will be shown. */ + public static final int LEVEL_ERRORS = 1; + + /** only errors and warnings will be shown. */ + public static final int LEVEL_WARNINGS = 2; + + /** enable errors/warnings and some global info + * message. */ + public static final int LEVEL_GLOBALINFOS = 3; + + /** enable anything! */ + public static final int LEVEL_DETAILEDINFOS = 4; + + //___________________________________________ + // member + + /** enable/disable different output level. + * e.g. warnings/errors/infos */ + private int m_nLevel; + + //___________________________________________ + // ctor + + /** initialize new debug object with the specified + * debug level. + * + * @param nLevel + * the new debug level. + * See const values LEVEL_xxx too. + */ + public Logger(int nLevel) + { + m_nLevel = nLevel; + } + + //___________________________________________ + // interface + + /** initialize new debug object with a default + * debug level. + */ + public Logger() + { + m_nLevel = LEVEL_DETAILEDINFOS; + } + + //___________________________________________ + // interface + + /** prints out an exception ... if the right level is set. + * + * @param ex + * the exception object + */ + public synchronized void setException(java.lang.Throwable ex) + { + if (m_nLevel >= LEVEL_ERRORS) + { + System.err.println("Exception:\n"); + ex.printStackTrace(); + } + } + + //___________________________________________ + // interface + + /** prints out an error ... if the right level is set. + * + * @param sError + * the error message. + */ + public synchronized void setError(java.lang.String sError) + { + if (m_nLevel >= LEVEL_ERRORS) + System.err.println("Error :\t\""+sError+"\""); + } + + //___________________________________________ + // interface + + /** prints out a warning ... if the right level is set. + * + * @param sWarning + * the warning message. + */ + public synchronized void setWarning(java.lang.String sWarning) + { + if (m_nLevel >= LEVEL_WARNINGS) + System.err.println("Warning :\t\""+sWarning+"\""); + } + + //___________________________________________ + // interface + + /** prints out a global info message ... if the right level is set. + * + * Global infos should be used to describe a complex operation. + * E.g.: loading of a document. + * But not for every sub operation like e.g. analyzing lines + * during loading the document! + * + * @param sInfo + * the info message. + */ + public synchronized void setGlobalInfo(java.lang.String sInfo) + { + if (m_nLevel >= LEVEL_GLOBALINFOS) + System.out.println("Info :\t\""+sInfo+"\""); + } + + //___________________________________________ + // interface + + /** prints out a mode detailed info message ... if the right level is set. + * + * Such detailed message are e.g. "analyze line [n] of file ...". + * + * @param sInfo + * the info message. + */ + public synchronized void setDetailedInfo(java.lang.String sInfo) + { + if (m_nLevel >= LEVEL_DETAILEDINFOS) + System.out.println("Detail :\t\""+sInfo+"\""); + } +} diff --git a/l10ntools/source/filter/utils/MalformedCommandLineException.java b/l10ntools/source/filter/utils/MalformedCommandLineException.java new file mode 100644 index 000000000000..e073dcb9adcc --- /dev/null +++ b/l10ntools/source/filter/utils/MalformedCommandLineException.java @@ -0,0 +1,50 @@ +/*_*********************************************************************** + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: MalformedCommandLineException.java,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + **********************************************************************_*/ + +package com.sun.star.filter.config.tools.utils; + +//_______________________________________________ +// imports + +import java.lang.*; + +//___________________________________________ +// types + +/** indicates a malformed command line. + * + * E.g. it must be thrown if the command line contains one item more then once, + * or use unsupported format. + */ +public class MalformedCommandLineException extends java.lang.Exception +{ + public MalformedCommandLineException() {} + public MalformedCommandLineException(java.lang.String sMsg) { super(sMsg); } +} diff --git a/l10ntools/source/filter/utils/XMLHelper.java b/l10ntools/source/filter/utils/XMLHelper.java new file mode 100644 index 000000000000..0f912cac8e25 --- /dev/null +++ b/l10ntools/source/filter/utils/XMLHelper.java @@ -0,0 +1,825 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: XMLHelper.java,v $ + * $Revision: 1.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.filter.config.tools.utils; + +//_______________________________________________ + +import java.lang.*; +import java.util.*; +import java.io.*; + +//_______________________________________________ + +/** + * It provides some constant values and some static helper routines + * which are neccessary to work with a xml file - especialy + * the filter configuration. + * + * + */ +public class XMLHelper +{ + //___________________________________________ + // public const + + /** its a possible value of the xml attribute "oor:type" and identify an integer type. */ + public static final java.lang.String XMLTYPE_INTEGER = "xs:int"; + + /** its a possible value of the xml attribute "oor:type" and identify an boolean type. */ + public static final java.lang.String XMLTYPE_BOOLEAN = "xs:boolean"; + + /** its a possible value of the xml attribute "oor:type" and identify an string type. */ + public static final java.lang.String XMLTYPE_STRING = "xs:string"; + + /** its a possible value of the xml attribute "oor:type" and identify an string list type. */ + public static final java.lang.String XMLTYPE_STRINGLIST = "oor:string-list"; + + /** its a xml attribute, which specify a property name. */ + public static final java.lang.String XMLATTRIB_OOR_NAME = "oor:name"; + + /** its a xml attribute, which specify a property type. */ + public static final java.lang.String XMLATTRIB_OOR_TYPE = "oor:type"; + + /** its a xml attribute, which specify a list separator. */ + public static final java.lang.String XMLATTRIB_OOR_SEPARATOR = "oor:separator"; + + /** its a xml attribute, which specify a localized value. */ + public static final java.lang.String XMLATTRIB_OOR_LOCALIZED = "oor:localized"; + + /** its a xml attribute, which specify a merge operation for cfg layering. */ + public static final java.lang.String XMLATTRIB_OOR_OP = "oor:op"; + + /** can be used as value for XMLATTRIB_OOR_OP. */ + public static final java.lang.String XMLATTRIB_OP_REPLACE = "replace"; + + /** its a xml attribute, which specify a locale value. */ + public static final java.lang.String XMLATTRIB_XML_LANG = "xml:lang"; + + /** its the tag name of a entry. */ + public static final java.lang.String XMLTAG_VALUE = "value"; + + /** its the tag name of a entry. */ + public static final java.lang.String XMLTAG_PROP = "prop"; + + /** its the tag name of a entry. */ + public static final java.lang.String XMLTAG_NODE = "node"; + + //___________________________________________ + // private const + + /** a static list of all possible separators, which can be used for configuration type string-list. */ + private static final java.lang.String[] DELIMS = {" ", ",", ";", ".", ":", "-", "_", "#", "'", "+", "*", "~", "=", "?"}; + + /** index of the default separator inside list DELIMS. + * Its neccessary to know such default separator; because it can + * be supressed as xml attribute of the corresponding value tag. */ + private static final int DEFAULT_SEPARATOR = 0; + + //___________________________________________ + + /** analyze the structures of the given XML node and + * return a property set of all found sub nodes. + * + * Such properties are organized as [name, value] pairs. + * The type of a xml node will be detected automaticly. + * Following types are supported: + * xs:int => java.lang.Integer + * xs:bool => java.lang.Boolean + * xs:string => java.lang.String + * oor:string-list => java.util.LinkedList[java.lang.String] + * oor:set => java.util.Vector[java.lang.Object] + * oor:localized => java.util.HashMap[java.lang.Object] + * + * @param aNode + * points directly to the xml node, where we should analyze + * the children nodes. + * + * @return [java.util.HashMap] + * contains every node name as key and its string(!) as value. + */ + public static java.util.HashMap convertNodeToPropSet(org.w3c.dom.Node aNode) + throws java.lang.Exception + { + java.util.HashMap aPropSet = new java.util.HashMap(); + + // get all child nodes, which seems to be properties + java.util.Vector lChildNodes = XMLHelper.extractChildNodesByTagName(aNode, XMLTAG_PROP); + java.util.Enumeration en1 = lChildNodes.elements(); + while(en1.hasMoreElements()) + { + org.w3c.dom.Node aChildNode = (org.w3c.dom.Node)en1.nextElement(); + + // read its name + java.lang.String sChildName = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_NAME); + if (sChildName == null) + throw new java.io.IOException("unsupported format: could not extract child node name"); + + // read its type info + java.lang.String sChildType = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_TYPE); + if (sChildType == null) + { + /** Special patch: + * If an xml tag has no type information set ... we can restore it + * by analyzing the already readed tag name :-) + * Not very nice - but it can help to read stripped xml files too. */ + sChildType = XMLHelper.getTypeForTag(sChildName); + if (sChildType == null) + throw new java.io.IOException("unsupported format: could not extract child node type"); + } + + // read its value(s?) + java.util.Vector lChildValues = XMLHelper.extractChildNodesByTagName(aChildNode, XMLTAG_VALUE); + java.util.Enumeration en2 = lChildValues.elements(); + int nValue = 0; + java.lang.Object aValue = null; + while(en2.hasMoreElements()) + { + org.w3c.dom.Node aValueNode = (org.w3c.dom.Node)en2.nextElement(); + java.lang.String sChildLocale = XMLHelper.extractNodeAttribByName(aValueNode, XMLATTRIB_XML_LANG); + boolean bLocalized = (sChildLocale != null); + + ++nValue; + + if (sChildType.equals(XMLTYPE_INTEGER)) + { + if (!bLocalized && nValue > 1) + throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); + java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); + aValue = new java.lang.Integer(sData); + } + else + if (sChildType.equals(XMLTYPE_BOOLEAN)) + { + if (!bLocalized && nValue > 1) + throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); + java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); + aValue = new java.lang.Boolean(sData); + } + else + if (sChildType.equals(XMLTYPE_STRING)) + { + if (!bLocalized && nValue > 1) + throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); + + java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); + + java.util.HashMap lLocalized = null; + if (bLocalized) + { + if (aValue == null) + aValue = new java.util.HashMap(); + lLocalized = (java.util.HashMap)aValue; + lLocalized.put(sChildLocale, sData); + } + else + aValue = sData; + } + else + if (sChildType.equals(XMLTYPE_STRINGLIST)) + { + if (!bLocalized && nValue > 1) + throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); + + java.lang.String sSeparator = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_SEPARATOR); + if (sSeparator == null) + sSeparator = " "; + + java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); + sData = sData.replace('\t', ' '); + sData = sData.replace('\n', ' '); + java.util.StringTokenizer aTokenizer = new java.util.StringTokenizer(sData, sSeparator); + java.util.Vector lList = new java.util.Vector(); + while(aTokenizer.hasMoreTokens()) + { + java.lang.String sToken = (java.lang.String)aTokenizer.nextToken(); + sToken.trim(); + if (sToken.length() < 1) + continue; + lList.add(sToken); + } + aValue = lList; + } + + aPropSet.put(sChildName, aValue); + } + } + + return aPropSet; + } + + //___________________________________________ + + private static java.lang.String getTypeForTag(java.lang.String sTag) + { + java.lang.String sType = null; + + if ( + (sTag.equals(Cache.PROPNAME_DATA )) || + (sTag.equals(Cache.PROPNAME_NAME )) || + (sTag.equals(Cache.PROPNAME_UINAME )) || + (sTag.equals(Cache.PROPNAME_MEDIATYPE )) || + (sTag.equals(Cache.PROPNAME_CLIPBOARDFORMAT )) || + (sTag.equals(Cache.PROPNAME_PREFERREDFILTER )) || + (sTag.equals(Cache.PROPNAME_DETECTSERVICE )) || + (sTag.equals(Cache.PROPNAME_FRAMELOADER )) || + (sTag.equals(Cache.PROPNAME_CONTENTHANDLER )) || + (sTag.equals(Cache.PROPNAME_DOCUMENTSERVICE )) || + (sTag.equals(Cache.PROPNAME_FILTERSERVICE )) || + (sTag.equals(Cache.PROPNAME_TEMPLATENAME )) || + (sTag.equals(Cache.PROPNAME_TYPE )) || + (sTag.equals(Cache.PROPNAME_UICOMPONENT )) + ) + sType = XMLTYPE_STRING; + else + if ( + (sTag.equals(Cache.PROPNAME_PREFERRED )) || + (sTag.equals("Installed" )) + ) + sType = XMLTYPE_BOOLEAN; + else + if ( + (sTag.equals(Cache.PROPNAME_UIORDER )) || + (sTag.equals(Cache.PROPNAME_DOCUMENTICONID )) || + (sTag.equals(Cache.PROPNAME_FILEFORMATVERSION)) + ) + sType = XMLTYPE_INTEGER; + else + if ( + (sTag.equals(Cache.PROPNAME_URLPATTERN )) || + (sTag.equals(Cache.PROPNAME_EXTENSIONS )) || + (sTag.equals(Cache.PROPNAME_USERDATA )) || + (sTag.equals(Cache.PROPNAME_FLAGS )) || + (sTag.equals(Cache.PROPNAME_TYPES )) + ) + sType = XMLTYPE_STRINGLIST; + + if (sType == null) + System.err.println("getTypeForTag("+sTag+") = "+sType); + + return sType; + } + + //___________________________________________ + + /** return a xml representation of the given property set. + * + * @param aPropSet + * a set of pairs, which should be translated to xml + * + * @return [java.lang.String] + * the xml string representation. + * + * @throws [java.lang.Exception] + * if anything during convertion fill fail. + */ + public static java.lang.String convertPropSetToXML(java.util.HashMap aPropSet , + int nPrettyTabs) + throws java.lang.Exception + { + java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); + + java.util.Iterator it1 = aPropSet.keySet().iterator(); + while(it1.hasNext()) + { + java.lang.String sProp = (java.lang.String)it1.next(); + java.lang.Object aVal = aPropSet.get(sProp); + + sProp = encodeHTMLSigns(sProp); + + // is it a simple type? + if ( + (aVal instanceof java.lang.Integer) || + (aVal instanceof java.lang.Boolean) || + (aVal instanceof java.lang.String ) + ) + { + sXML.append(XMLHelper.convertSimpleObjectToXML(sProp, aVal, nPrettyTabs)); + continue; + } + + // no! + // is it a list value? + if (aVal instanceof java.util.Vector) + { + java.util.Vector lVal = (java.util.Vector)aVal; + sXML.append(XMLHelper.convertListToXML(sProp, lVal, nPrettyTabs)); + continue; + } + + // its a localized value? + if (aVal instanceof java.util.HashMap) + { + java.util.HashMap lVal = (java.util.HashMap)aVal; + sXML.append(XMLHelper.convertLocalizedValueToXML(sProp, lVal, nPrettyTabs)); + continue; + } + + // unknown type! + java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); + sMsg.append("unsupported object type detected."); + sMsg.append("\ttype ? : \""+sProp+"\" = "+aVal); + sMsg.append("\tprop set: \""+aPropSet ); + throw new java.lang.Exception(sMsg.toString()); + } + + return sXML.toString(); + } + + public static java.lang.String encodeHTMLSigns(java.lang.String sValue) + { + java.lang.StringBuffer sSource = new java.lang.StringBuffer(sValue); + java.lang.StringBuffer sDestination = new java.lang.StringBuffer(1000 ); + + for (int i=0; i \""+sReturn+"\""); + + return sReturn; + } + + //___________________________________________ + + /** return a xml representation of an atomic property. + * + * Atomic property types are e.g. Integer, Boolean, String. + * + * @param sName + * the name of the property. + + * @param aValue + * the value of the property. + * + * @param nPrettyTabs + * count of tab signs for pretty format the xml code :-) + * + * @return [java.lang.String] + * the xml string representation. + * + * @throws [java.lang.Exception] + * if anything during convertion fill fail. + */ + private static java.lang.String convertSimpleObjectToXML(java.lang.String sName , + java.lang.Object aValue , + int nPrettyTabs) + throws java.lang.Exception + { + java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); + for (int t=0; t"); + sXML.append(""+aValue.toString()+""); + sXML.append("\n"); + } + else + if (aValue instanceof java.lang.Boolean) + { + sXML.append(""); + sXML.append(""+aValue.toString()+""); + sXML.append("\n"); + } + else + if (aValue instanceof java.lang.String) + { + sXML.append("\n"); + else + { + sXML.append(">"+sValue+""); + sXML.append("\n"); + } + } + else + { + System.err.println("name = "+sName); + System.err.println("value = "+aValue); + // ! can be used outside to detect - that it was not a simple type :-) + throw new java.lang.Exception("not an atomic type."); + } + + return sXML.toString(); + } + + //___________________________________________ + + /** return a xml representation of a string-list property. + * + * @param sName + * the name of the property. + + * @param aValue + * the value of the property. + * + * @param nPrettyTabs + * count of tab signs for pretty format the xml code :-) + * + * @return [java.lang.String] + * the xml string representation. + * + * @throws [java.lang.Exception] + * if anything during convertion fill fail. + */ + private static java.lang.String convertListToXML(java.lang.String sName , + java.util.Vector aValue , + int nPrettyTabs) + throws java.lang.Exception + { + java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); + + for (int t=0; t\n"); + return sXML.toString(); + } + + // step over all list items and add it to a string buffer + // Every item will be separated by a default separator "\n" first. + // Because "\n" is not a valid separator at all and can`t occure inside + // our list items. During we step over all items, we check if our current separator + // (we use a list of possible ones!) clash with an item. + // If it clash - we step to the next possible separator. + // If our list of possible separator values runs out of range we throw + // an exception :-) Its better then generating of wrong values + // If we found a valid seperator - we use it to replace our "\n" place holder + // at the end of the following loop ... + + int d = 0; + java.lang.StringBuffer sValBuff = new java.lang.StringBuffer(256); + for (int i=0; i= DELIMS.length) + throw new java.lang.Exception("No valid separator found for a string list item."); + if (sValue.length() < 1 && DELIMS[d].equals(" ")) + { + ++d; + continue; + } + if (sValue.indexOf(DELIMS[d]) != -1) + { + ++d; + continue; + } + break; + } + } + + // replace default separator with right one + System.out.println("TODO: must be adapted to java 1.3 :-("); + System.exit(-1); +//TODO_JAVA java.lang.String sListVal = sValBuff.toString().replaceAll("\n", DELIMS[d]); + java.lang.String sListVal = null; + + sXML.append(""); + if (d == DEFAULT_SEPARATOR) + sXML.append(""); + else + sXML.append(""); + sXML.append(sListVal); + sXML.append(""); + sXML.append("\n"); + + return sXML.toString(); + } + + //___________________________________________ + + /** return a xml representation of a localized property. + * + * @param sName + * the name of the property. + + * @param aValue + * the value of the property. + * + * @param nPrettyTabs + * count of tab signs for pretty format the xml code :-) + * + * @return [java.lang.String] + * the xml string representation. + * + * @throws [java.lang.Exception] + * if anything during convertion fill fail. + */ + private static java.lang.String convertLocalizedValueToXML(java.lang.String sName , + java.util.HashMap aValue , + int nPrettyTabs) + throws java.lang.Exception + { + java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); + + int c = aValue.size(); + if (c < 1) + throw new java.lang.Exception("Cant detect type of localized values. Because the given list is empty."); + + for (int t=0; t\n"); + java.util.Iterator it = aValue.keySet().iterator(); +// boolean bTypeKnown = false; + while(it.hasNext()) + { + java.lang.String sLocale = (java.lang.String)it.next(); + java.lang.Object aLocalizedValue = aValue.get(sLocale); +/* + if (!bTypeKnown) + { + bTypeKnown = true; + if (aLocalizedValue instanceof java.lang.Integer) + sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_INTEGER+"\">\n"); + else + if (aLocalizedValue instanceof java.lang.Boolean) + sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_BOOLEAN+"\">\n"); + else + if (aLocalizedValue instanceof java.lang.String) + sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_STRING+"\">\n"); + else + throw new java.lang.Exception("Unsupported type for localized value detected."); + } +*/ + java.lang.String sLocValue = aLocalizedValue.toString(); + java.lang.String sValue = encodeHTMLSigns(sLocValue); + + for (int t=0; t"+sValue+"\n"); + } + --nPrettyTabs; + for (int t=0; t\n"); + + return sXML.toString(); + } + + //___________________________________________ + + /** returns the value of an attribute of the given node. + * + * If the given node represent an lement node, may it supports some attributes. + * Then this method search for an attribute with the specified name and return it's value. + * If nothing could be found ... or the given node isn't a suitable node ... it returns null. + * + * @param aNode + * the node, which should be analyzed. + * + * @param sAttrib + * name of the attribute, which should be searched. + * + * @return The value of the specified attribute if it could be found at the given node. + * Can be null if node doesn't support attributes or the searched one does not exist there. + */ + public static java.lang.String extractNodeAttribByName(org.w3c.dom.Node aNode , + java.lang.String sAttrib) + throws java.lang.Exception + { + // We can get valid attributes for element nodes only! + if (aNode.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) + { +// System.err.println("not an element node"); + return null; + } + + // may it supports attributes in general ... but doesn't have anyone realy. + org.w3c.dom.NamedNodeMap lAttribs = aNode.getAttributes(); + if (lAttribs==null) + { +// System.err.println("no attributes at all"); + return null; + } + + // step over the attribute list and search for the requested one + for (int i=0; i\n"); + sHeader.append("\n"); + } + else + { + sHeader.append("\n\n"); + sHeader.append("\n"); + } + + return sHeader.toString(); + } + + public static java.lang.String generateFooter() + { + return "\n"; + } +} diff --git a/l10ntools/source/filter/utils/makefile.mk b/l10ntools/source/filter/utils/makefile.mk new file mode 100644 index 000000000000..4025c54b2c38 --- /dev/null +++ b/l10ntools/source/filter/utils/makefile.mk @@ -0,0 +1,57 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.9.98.2 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ = ..$/..$/.. +TARGET = FCFGUtils +PRJNAME = l10ntools +PACKAGE = com$/sun$/star$/filter$/config$/tools$/utils + +# --- Settings ----------------------------------------------------- + +.INCLUDE: settings.mk + +#----- compile .java files ----------------------------------------- + + +JAVACLASSFILES = \ + $(CLASSDIR)$/$(PACKAGE)$/AnalyzeStartupLog.class \ + $(CLASSDIR)$/$(PACKAGE)$/ConfigHelper.class \ + $(CLASSDIR)$/$(PACKAGE)$/Logger.class \ + $(CLASSDIR)$/$(PACKAGE)$/FileHelper.class \ + $(CLASSDIR)$/$(PACKAGE)$/MalformedCommandLineException.class \ + $(CLASSDIR)$/$(PACKAGE)$/Cache.class \ + $(CLASSDIR)$/$(PACKAGE)$/XMLHelper.class + +MAXLINELENGTH = 100000 + +# --- targets ----------------------------------------------------- + +.INCLUDE : target.mk diff --git a/l10ntools/source/gsicheck.cxx b/l10ntools/source/gsicheck.cxx new file mode 100644 index 000000000000..aa3b8157952d --- /dev/null +++ b/l10ntools/source/gsicheck.cxx @@ -0,0 +1,1177 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: gsicheck.cxx,v $ + * $Revision: 1.29 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +#include +#include + +// local includes +#include "tagtest.hxx" +#include "gsicheck.hxx" + +#define MAX_GID_LID_LEN 250 + +/*****************************************************************************/ +void PrintMessage( ByteString aType, ByteString aMsg, ByteString aPrefix, + ByteString aContext, BOOL bPrintContext, ULONG nLine, ByteString aUniqueId = ByteString() ) +/*****************************************************************************/ +{ + fprintf( stdout, "%s %s, Line %lu", aType.GetBuffer(), aPrefix.GetBuffer(), nLine ); + if ( aUniqueId.Len() ) + fprintf( stdout, ", UniqueID %s", aUniqueId.GetBuffer() ); + fprintf( stdout, ": %s", aMsg.GetBuffer() ); + + if ( bPrintContext ) + fprintf( stdout, " \"%s\"", aContext.GetBuffer() ); + fprintf( stdout, "\n" ); +} + +/*****************************************************************************/ +void PrintError( ByteString aMsg, ByteString aPrefix, + ByteString aContext, BOOL bPrintContext, ULONG nLine, ByteString aUniqueId = ByteString() ) +/*****************************************************************************/ +{ + PrintMessage( "Error:", aMsg, aPrefix, aContext, bPrintContext, nLine, aUniqueId ); +} + +BOOL LanguageOK( ByteString aLang ) +{ + if ( !aLang.Len() ) + return FALSE; + + if ( aLang.IsNumericAscii() ) + return TRUE; + + if ( aLang.GetTokenCount( '-' ) == 1 ) + return aLang.IsAlphaAscii() && aLang.IsLowerAscii(); + else if ( aLang.GetTokenCount( '-' ) == 2 ) + { + ByteString aTok0( aLang.GetToken( 0, '-' ) ); + ByteString aTok1( aLang.GetToken( 1, '-' ) ); + return aTok0.Len() && aTok0.IsAlphaAscii() && aTok0.IsLowerAscii() + && aTok1.Len() && aTok1.IsAlphaAscii() && aTok1.IsUpperAscii() + && !aTok1.EqualsIgnoreCaseAscii( aTok0 ); + } + + return FALSE; +} + + +// +// class LazySvFileStream +// + + +class LazySvFileStream : public SvFileStream +{ + +private: + String aFileName; + BOOL bOpened; + StreamMode eOpenMode; + +public: + LazySvFileStream() + : aFileName() + , bOpened( FALSE ) + , eOpenMode( 0 ) + {}; + + void SetOpenParams( const String& rFileName, StreamMode eOpenModeP ) + { + aFileName = rFileName; + eOpenMode = eOpenModeP; + }; + + void LazyOpen(); +}; + +void LazySvFileStream::LazyOpen() +{ + if ( !bOpened ) + { + Open( aFileName, eOpenMode ); + if ( !IsOpen()) + { + fprintf( stderr, "\nERROR: Could not open Output-File %s!\n\n", ByteString( aFileName, RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); + exit ( 4 ); + } + bOpened = TRUE; + } +} + + +// +// class GSILine +// + +/*****************************************************************************/ +GSILine::GSILine( const ByteString &rLine, ULONG nLine ) +/*****************************************************************************/ + : ByteString( rLine ) + , nLineNumber( nLine ) + , bOK( TRUE ) + , bFixed ( FALSE ) +{ + if ( rLine.GetTokenCount( '\t' ) == 15 ) + { + aFormat = FORMAT_SDF; + aUniqId = rLine.GetToken( 0, '\t' ); + aUniqId.Append("/").Append( rLine.GetToken( 1, '\t' ) ).Append("/").Append( rLine.GetToken( 3, '\t' ) ).Append("/").Append( rLine.GetToken( 4, '\t' ) ).Append("/").Append( rLine.GetToken( 5, '\t' ) ).Append("/").Append( rLine.GetToken( 6, '\t' ) ).Append("/").Append( rLine.GetToken( 7, '\t' ) ); + aLineType = ""; + aLangId = rLine.GetToken( 9, '\t' ); + aText = rLine.GetToken( 10, '\t' ); + aQuickHelpText = rLine.GetToken( 12, '\t' ); + aTitle = rLine.GetToken( 13, '\t' ); + + // do some more format checks here + if ( !rLine.GetToken( 8, '\t' ).IsNumericAscii() ) + { + PrintError( "The length field does not contain a number!", "Line format", rLine.GetToken( 8, '\t' ), TRUE, GetLineNumber(), GetUniqId() ); + NotOK(); + } + if ( !LanguageOK( aLangId ) ) + { + PrintError( "The Language is invalid!", "Line format", aLangId, TRUE, GetLineNumber(), GetUniqId() ); + NotOK(); + } + // limit GID and LID to MAX_GID_LID_LEN chars each for database conformity, see #137575# + if ( rLine.GetToken( 4, '\t' ).Len() > MAX_GID_LID_LEN || rLine.GetToken( 5, '\t' ).Len() > MAX_GID_LID_LEN ) + { + PrintError( ByteString("GID and LID may only be ").Append( ByteString::CreateFromInt32(MAX_GID_LID_LEN) ).Append( " chars long each!" ), "Line format", aLangId, TRUE, GetLineNumber(), GetUniqId() ); + NotOK(); + } + } + else // allow tabs in gsi files + { + aFormat = FORMAT_GSI; + ByteString sTmp( rLine ); + USHORT nPos = sTmp.Search( "($$)" ); + USHORT nStart = 0; + if ( nPos != STRING_NOTFOUND ) + { + aUniqId = sTmp.Copy( nStart, nPos - nStart ); + nStart = nPos + 4; // + length of the delemiter + nPos = sTmp.Search( "($$)", nStart ); + } + if ( nPos != STRING_NOTFOUND ) + { + aLineType = sTmp.Copy( nStart, nPos - nStart ); + nStart = nPos + 4; // + length of the delemiter + nPos = sTmp.Search( "($$)", nStart ); + aUniqId.Append( "/" ); + aUniqId.Append( aLineType ); + } + if ( nPos != STRING_NOTFOUND ) + { + aLangId = sTmp.Copy( nStart, nPos - nStart ); + nStart = nPos + 4; // + length of the delemiter + nPos = sTmp.Search( "($$)", nStart ); + } + if ( nPos != STRING_NOTFOUND ) + { +// ByteString aStatus = sTmp.Copy( nStart, nPos - nStart ); // ext int ... + nStart = nPos + 4; // + length of the delemiter + } + if ( nPos != STRING_NOTFOUND ) + aText = sTmp.Copy( nStart ); + else + aFormat = FORMAT_UNKNOWN; + } + + if ( FORMAT_UNKNOWN == GetLineFormat() ) + NotOK(); +} + +/*****************************************************************************/ +void GSILine::NotOK() +/*****************************************************************************/ +{ + bOK = FALSE; +} + +/*****************************************************************************/ +void GSILine::ReassembleLine() +/*****************************************************************************/ +{ + ByteString aReassemble; + if ( GetLineFormat() == FORMAT_SDF ) + { + USHORT i; + for ( i = 0 ; i < 10 ; i++ ) + { + aReassemble.Append( GetToken( i, '\t' ) ); + aReassemble.Append( "\t" ); + } + aReassemble.Append( aText ); + aReassemble.Append( "\t" ); + aReassemble.Append( GetToken( 11, '\t' ) ); // should be empty but there are some places in sc. Not reflected to sources!! + aReassemble.Append( "\t" ); + aReassemble.Append( aQuickHelpText ); + aReassemble.Append( "\t" ); + aReassemble.Append( aTitle ); + for ( i = 14 ; i < 15 ; i++ ) + { + aReassemble.Append( "\t" ); + aReassemble.Append( GetToken( i, '\t' ) ); + } + *(ByteString*)this = aReassemble; + } + else if ( GetLineFormat() == FORMAT_GSI ) + { + USHORT nPos = Search( "($$)" ); + USHORT nStart = 0; + if ( nPos != STRING_NOTFOUND ) + { + nStart = nPos + 4; // + length of the delemiter + nPos = Search( "($$)", nStart ); + } + if ( nPos != STRING_NOTFOUND ) + { + nStart = nPos + 4; // + length of the delemiter + nPos = Search( "($$)", nStart ); + } + if ( nPos != STRING_NOTFOUND ) + { + nStart = nPos + 4; // + length of the delemiter + nPos = Search( "($$)", nStart ); + } + if ( nPos != STRING_NOTFOUND ) + { + nStart = nPos + 4; // + length of the delemiter + } + if ( nPos != STRING_NOTFOUND ) + { + aReassemble = Copy( 0, nStart ); + aReassemble += aText; + *(ByteString*)this = aReassemble; + } + else + PrintError( "Cannot reassemble GSI line (internal Error).", "Line format", "", FALSE, GetLineNumber(), GetUniqId() ); + } + else + PrintError( "Cannot reassemble line of unknown type (internal Error).", "Line format", "", FALSE, GetLineNumber(), GetUniqId() ); +} + +// +// class GSIBlock +// +/*****************************************************************************/ +GSIBlock::GSIBlock( BOOL PbPrintContext, BOOL bSource, BOOL bTrans, BOOL bRef, BOOL bAllowKID, BOOL bAllowSusp ) +/*****************************************************************************/ + : pSourceLine( NULL ) + , pReferenceLine( NULL ) + , bPrintContext( PbPrintContext ) + , bCheckSourceLang( bSource ) + , bCheckTranslationLang( bTrans ) + , bReference( bRef ) + , bAllowKeyIDs( bAllowKID ) + , bAllowSuspicious( bAllowSusp ) + , bHasBlockError( FALSE ) +{ +} + +/*****************************************************************************/ +GSIBlock::~GSIBlock() +/*****************************************************************************/ +{ + delete pSourceLine; + delete pReferenceLine; + + for ( ULONG i = 0; i < Count(); i++ ) + delete ( GetObject( i )); +} + +/*****************************************************************************/ +void GSIBlock::InsertLine( GSILine* pLine, ByteString aSourceLang) +/*****************************************************************************/ +{ + if ( pLine->GetLanguageId().Equals( aSourceLang ) ) + { + if ( pSourceLine ) + { + PrintError( "Source Language entry double. Treating as Translation.", "File format", "", pLine->GetLineNumber(), pLine->GetUniqId() ); + bHasBlockError = TRUE; + pSourceLine->NotOK(); + pLine->NotOK(); + } + else + { + pSourceLine = pLine; + return; + } + } + ULONG nPos = 0; + + if ( aSourceLang.Len() ) // only check blockstructure if source lang is given + { + while ( nPos < Count() ) + { + if ( GetObject( nPos )->GetLanguageId().Equals( pLine->GetLanguageId() ) ) + { + PrintError( "Translation Language entry double. Checking both.", "File format", "", pLine->GetLineNumber(), pLine->GetUniqId() ); + bHasBlockError = TRUE; + GetObject( nPos )->NotOK(); + pLine->NotOK(); + } + nPos++; + } + } + Insert( pLine, LIST_APPEND ); +} + +/*****************************************************************************/ +void GSIBlock::SetReferenceLine( GSILine* pLine ) +/*****************************************************************************/ +{ + pReferenceLine = pLine; +} + +/*****************************************************************************/ +void GSIBlock::PrintMessage( ByteString aType, ByteString aMsg, ByteString aPrefix, + ByteString aContext, ULONG nLine, ByteString aUniqueId ) +/*****************************************************************************/ +{ + ::PrintMessage( aType, aMsg, aPrefix, aContext, bPrintContext, nLine, aUniqueId ); +} + +/*****************************************************************************/ +void GSIBlock::PrintError( ByteString aMsg, ByteString aPrefix, + ByteString aContext, ULONG nLine, ByteString aUniqueId ) +/*****************************************************************************/ +{ + PrintMessage( "Error:", aMsg, aPrefix, aContext, nLine, aUniqueId ); +} + +/*****************************************************************************/ +void GSIBlock::PrintList( ParserMessageList *pList, ByteString aPrefix, + GSILine *pLine ) +/*****************************************************************************/ +{ + ULONG i; + for ( i = 0 ; i < pList->Count() ; i++ ) + { + ParserMessage *pMsg = pList->GetObject( i ); + ByteString aContext; + if ( bPrintContext ) + { + if ( pMsg->GetTagBegin() == STRING_NOTFOUND ) + aContext = pLine->GetText().Copy( 0, 300 ); + else + aContext = pLine->Copy( pMsg->GetTagBegin()-150, 300 ); + aContext.EraseTrailingChars(' '); + aContext.EraseLeadingChars(' '); + } + + PrintMessage( pMsg->Prefix(), pMsg->GetErrorText(), aPrefix, aContext, pLine->GetLineNumber(), pLine->GetUniqId() ); + } +} + +/*****************************************************************************/ +BOOL GSIBlock::IsUTF8( const ByteString &aTestee, BOOL bFixTags, USHORT &nErrorPos, ByteString &aErrorMsg, BOOL &bHasBeenFixed, ByteString &aFixed ) const +/*****************************************************************************/ +{ + String aUTF8Tester( aTestee, RTL_TEXTENCODING_UTF8 ); + if ( STRING_MATCH != (nErrorPos = ByteString( aUTF8Tester, RTL_TEXTENCODING_UTF8 ).Match( aTestee )) ) + { + aUTF8Tester = String( aTestee.GetBuffer(), nErrorPos, RTL_TEXTENCODING_UTF8 ); + nErrorPos = aUTF8Tester.Len(); + aErrorMsg = ByteString( "UTF8 Encoding seems to be broken" ); + return FALSE; + } + + nErrorPos = aUTF8Tester.SearchChar( String::CreateFromAscii( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f" ).GetBuffer() ); + if ( nErrorPos != STRING_NOTFOUND ) + { + aErrorMsg = ByteString( "String contains illegal character" ); + return FALSE; + } + + if ( bFixTags ) + { + bHasBeenFixed = FALSE; + aFixed.Erase(); + } + + if ( !bAllowKeyIDs ) + { + BOOL bIsKeyID = FALSE; + BOOL bNewId = FALSE; + ByteString aID( aTestee ); + USHORT nAfterID = 0; + + if ( aTestee.Equals( "{&", 0, 2 ) ) + { // check for strings from instset_native like "{&Tahoma8}335795.Installation Wiza ..." + USHORT nTagEnd = aTestee.Search( '}' ); + if ( nTagEnd != STRING_NOTFOUND ) + { + if ( bFixTags ) + aFixed = aTestee.Copy( 0, nTagEnd+1 ); + nErrorPos = nTagEnd+1; + aID = aTestee.Copy( nTagEnd+1 ); + nAfterID = nTagEnd+1; + } + } + + ByteString aDelimiter( (String)String( sal_Unicode(0x2016) ), RTL_TEXTENCODING_UTF8 ); + + if ( aID.Equals( aDelimiter, 6, aDelimiter.Len() ) ) + { // New KeyId 6 Letters, digits and spechial chars followed by delimiter + bNewId = TRUE; + nErrorPos = 1; + aID = aID.Copy( 0, 6 ); + nAfterID += 6; + nAfterID = nAfterID + aDelimiter.Len(); + } + else if ( ( aID.GetChar(6) == '*' ) && aID.Equals( aDelimiter, 7, aDelimiter.Len() ) ) + { // New KeyId 6 Letters, digits and spechial chars followed by '*delimiter' to indicate translation in progress + bNewId = TRUE; + nErrorPos = 1; + aID = aID.Copy( 0, 6 ); + nAfterID += 7; + nAfterID = nAfterID + aDelimiter.Len(); + } + else if ( aID.GetTokenCount( '.' ) > 1 ) + { // test for old KeyIDs 5 to 6 digits followed by a dot '44373.' + bNewId = FALSE; + nErrorPos = 1; + aID = aID.GetToken( 0, '.' ); + nAfterID = nAfterID + aID.Len(); + } + else + { + aID.Erase(); + } + + if ( bNewId ) + { + if ( aID.Len() == 6 ) + { + bIsKeyID = TRUE; + ByteString aDigits("0123456789abcdefghijklmnopqrstuvwxyz+-<=>"); + for ( USHORT i=0 ; i < aID.Len() ;i++ ) + { + if ( aDigits.Search( aID.GetChar(i) ) == STRING_NOTFOUND ) + bIsKeyID = FALSE; + } + } + } + else + { + if ( aID.Len() > 0 && aID.GetChar(aID.Len()-1) == '*' ) + aID.Erase( aID.Len()-1 ); + + if ( aID.IsNumericAscii() && aID.Len() >= 5 ) + bIsKeyID = TRUE; + } + + if ( bIsKeyID ) + { + aErrorMsg = ByteString( "String contains KeyID" ); + if ( bFixTags ) + { + aFixed += aTestee.Copy( nAfterID ); + bHasBeenFixed = TRUE; + aErrorMsg = ByteString( "FIXED String containing KeyID" ); + } + else + aErrorMsg = ByteString( "String contains KeyID" ); + return FALSE; + } + } + + return TRUE; +} + +/*****************************************************************************/ +BOOL GSIBlock::TestUTF8( GSILine* pTestee, BOOL bFixTags ) +/*****************************************************************************/ +{ + USHORT nErrorPos = 0; + ByteString aErrorMsg; + BOOL bError = FALSE; + ByteString aFixed; + BOOL bHasBeenFixed = FALSE; + if ( !IsUTF8( pTestee->GetText(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) + { + ByteString aContext( pTestee->GetText().Copy( nErrorPos, 20 ) ); + PrintError( aErrorMsg.Append(" in Text at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); + bError = TRUE; + if ( bHasBeenFixed ) + { + pTestee->SetText( aFixed ); + pTestee->SetFixed(); + } + } + if ( !IsUTF8( pTestee->GetQuickHelpText(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) + { + ByteString aContext( pTestee->GetQuickHelpText().Copy( nErrorPos, 20 ) ); + PrintError( aErrorMsg.Append(" in QuickHelpText at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); + bError = TRUE; + if ( bHasBeenFixed ) + { + pTestee->SetQuickHelpText( aFixed ); + pTestee->SetFixed(); + } + } + if ( !IsUTF8( pTestee->GetTitle(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) + { + ByteString aContext( pTestee->GetTitle().Copy( nErrorPos, 20 ) ); + PrintError( aErrorMsg.Append(" in Title at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); + bError = TRUE; + if ( bHasBeenFixed ) + { + pTestee->SetTitle( aFixed ); + pTestee->SetFixed(); + } + } + if ( bError ) + pTestee->NotOK(); + return !bError; +} + + +/*****************************************************************************/ +BOOL GSIBlock::HasSuspiciousChars( GSILine* pTestee, GSILine* pSource ) +/*****************************************************************************/ +{ + USHORT nPos = 0; + if ( !bAllowSuspicious && ( nPos = pTestee->GetText().Search("??")) != STRING_NOTFOUND ) + if ( pSource->GetText().Search("??") == STRING_NOTFOUND ) + { + String aUTF8Tester = String( pTestee->GetText(), 0, nPos, RTL_TEXTENCODING_UTF8 ); + USHORT nErrorPos = aUTF8Tester.Len(); + ByteString aContext( pTestee->GetText().Copy( nPos, 20 ) ); + PrintError( ByteString("Found double questionmark in translation only. Looks like an encoding problem at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); + pTestee->NotOK(); + return TRUE; + } + + return FALSE; +} + + +/*****************************************************************************/ +BOOL GSIBlock::CheckSyntax( ULONG nLine, BOOL bRequireSourceLine, BOOL bFixTags ) +/*****************************************************************************/ +{ + static LingTest aTester; + BOOL bHasError = FALSE; + + if ( !pSourceLine ) + { + if ( bRequireSourceLine ) + { + PrintError( "No source language entry defined!", "File format", "", nLine ); + bHasBlockError = TRUE; + } + } + else + { + aTester.CheckReference( pSourceLine ); + if ( pSourceLine->HasMessages() ) + { + PrintList( pSourceLine->GetMessageList(), "ReferenceString", pSourceLine ); + pSourceLine->NotOK(); + bHasError = TRUE; + } + } + if ( bReference ) + { + if ( !pReferenceLine ) + { + GSILine *pSource; + if ( pSourceLine ) + pSource = pSourceLine; + else + pSource = GetObject( 0 ); // get some other line + if ( pSource ) + PrintError( "No reference line found. Entry is new in source file", "File format", "", pSource->GetLineNumber(), pSource->GetUniqId() ); + else + PrintError( "No reference line found. Entry is new in source file", "File format", "", nLine ); + bHasBlockError = TRUE; + } + else + { + if ( pSourceLine && !pSourceLine->Equals( *pReferenceLine ) ) + { + xub_StrLen nPos = pSourceLine->Match( *pReferenceLine ); + ByteString aContext( pReferenceLine->Copy( nPos - 5, 15) ); + aContext.Append( "\" --> \"" ).Append( pSourceLine->Copy( nPos - 5, 15) ); + PrintError( "Source Language Entry has changed.", "File format", aContext, pSourceLine->GetLineNumber(), pSourceLine->GetUniqId() ); + pSourceLine->NotOK(); + bHasError = TRUE; + } + } + } + + if ( pSourceLine ) + bHasError |= !TestUTF8( pSourceLine, bFixTags ); + + ULONG i; + for ( i = 0; i < Count(); i++ ) + { + aTester.CheckTestee( GetObject( i ), pSourceLine != NULL, bFixTags ); + if ( GetObject( i )->HasMessages() || aTester.HasCompareWarnings() ) + { + if ( GetObject( i )->HasMessages() || aTester.GetCompareWarnings().HasErrors() ) + GetObject( i )->NotOK(); + bHasError = TRUE; + PrintList( GetObject( i )->GetMessageList(), "Translation", GetObject( i ) ); + PrintList( &(aTester.GetCompareWarnings()), "Translation Tag Missmatch", GetObject( i ) ); + } + bHasError |= !TestUTF8( GetObject( i ), bFixTags ); + if ( pSourceLine ) + bHasError |= HasSuspiciousChars( GetObject( i ), pSourceLine ); + } + + return bHasError || bHasBlockError; +} + +void GSIBlock::WriteError( LazySvFileStream &aErrOut, BOOL bRequireSourceLine ) +{ + if ( pSourceLine && pSourceLine->IsOK() && bCheckSourceLang && !bHasBlockError ) + return; + + BOOL bHasError = FALSE; + BOOL bCopyAll = ( !pSourceLine && bRequireSourceLine ) || ( pSourceLine && !pSourceLine->IsOK() && !bCheckTranslationLang ) || bHasBlockError; + ULONG i; + for ( i = 0; i < Count(); i++ ) + { + if ( !GetObject( i )->IsOK() || bCopyAll ) + { + bHasError = TRUE; + aErrOut.LazyOpen(); + aErrOut.WriteLine( *GetObject( i ) ); + } + } + + if ( pSourceLine && ( bHasError || !pSourceLine->IsOK() ) && !( !bHasError && bCheckTranslationLang ) ) + { + aErrOut.LazyOpen(); + aErrOut.WriteLine( *pSourceLine ); + } +} + +void GSIBlock::WriteCorrect( LazySvFileStream &aOkOut, BOOL bRequireSourceLine ) +{ + if ( ( !pSourceLine && bRequireSourceLine ) || ( pSourceLine && !pSourceLine->IsOK() && !bCheckTranslationLang ) ) + return; + + BOOL bHasOK = FALSE; + ULONG i; + for ( i = 0; i < Count(); i++ ) + { + if ( ( GetObject( i )->IsOK() || bCheckSourceLang ) && !bHasBlockError ) + { + bHasOK = TRUE; + aOkOut.LazyOpen(); + aOkOut.WriteLine( *GetObject( i ) ); + } + } + + if ( ( pSourceLine && pSourceLine->IsOK() && ( Count() || !bCheckTranslationLang ) ) || ( bHasOK && bCheckTranslationLang ) ) + { + aOkOut.LazyOpen(); + aOkOut.WriteLine( *pSourceLine ); + } +} + +void GSIBlock::WriteFixed( LazySvFileStream &aFixOut, BOOL /*bRequireSourceLine*/ ) +{ + if ( pSourceLine && !pSourceLine->IsFixed() && bCheckSourceLang ) + return; + + BOOL bHasFixes = FALSE; + ULONG i; + for ( i = 0; i < Count(); i++ ) + { + if ( GetObject( i )->IsFixed() ) + { + bHasFixes = TRUE; + aFixOut.LazyOpen(); + aFixOut.WriteLine( *GetObject( i ) ); + } + } + + if ( pSourceLine && ( bHasFixes || pSourceLine->IsFixed() ) ) + { + aFixOut.LazyOpen(); + aFixOut.WriteLine( *pSourceLine ); + } +} + + +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ + +/*****************************************************************************/ +void Help() +/*****************************************************************************/ +{ + fprintf( stdout, "\n" ); + fprintf( stdout, "gsicheck Version 1.9.0 (c)1999 - 2006 by SUN Microsystems\n" ); + fprintf( stdout, "=========================================================\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "gsicheck checks the syntax of tags in GSI-Files and SDF-Files\n" ); + fprintf( stdout, " checks for inconsistencies and malicious UTF8 encoding\n" ); + fprintf( stdout, " checks tags in Online Help\n" ); + fprintf( stdout, " checks for *new* KeyIDs and relax GID/LID length to %s\n", ByteString::CreateFromInt32(MAX_GID_LID_LEN).GetBuffer() ); + fprintf( stdout, "\n" ); + fprintf( stdout, "Syntax: gsicheck [ -c ] [-f] [ -we ] [ -wef ErrorFilename ] [ -wc ]\n" ); + fprintf( stdout, " [ -wcf CorrectFilename ] [ -s | -t ] [ -l LanguageID ]\n" ); + fprintf( stdout, " [ -r ReferenceFile ] filename\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "-c Add context to error message (Print the line containing the error)\n" ); + fprintf( stdout, "-f try to fix errors. See also -wf -wff \n" ); + fprintf( stdout, "-wf Write File containing all fixed parts\n" ); + fprintf( stdout, "-wff Same as above but give own filename\n" ); + fprintf( stdout, "-we Write File containing all errors\n" ); + fprintf( stdout, "-wef Same as above but give own filename\n" ); + fprintf( stdout, "-wc Write File containing all correct parts\n" ); + fprintf( stdout, "-wcf Same as above but give own filename\n" ); + fprintf( stdout, "-s Check only source language. Should be used before handing out to vendor.\n" ); + fprintf( stdout, "-t Check only Translation language(s). Should be used before merging.\n" ); + fprintf( stdout, "-k Allow KeyIDs to be present in strings\n" ); + fprintf( stdout, "-e disable encoding checks. E.g.: double questionmark \'??\' which may be the\n" ); + fprintf( stdout, " result of false conversions\n" ); + fprintf( stdout, "-l ISO Languagecode or numerical 2 digits Identifier of the source language.\n" ); + fprintf( stdout, " Default is en-US. Use \"\" (empty string) or 'none'\n" ); + fprintf( stdout, " to disable source language dependent checks\n" ); + fprintf( stdout, "-r Reference filename to check that source language entries\n" ); + fprintf( stdout, " have not been changed\n" ); + fprintf( stdout, "\n" ); +} + +/*****************************************************************************/ +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + + BOOL bError = FALSE; + BOOL bPrintContext = FALSE; + BOOL bCheckSourceLang = FALSE; + BOOL bCheckTranslationLang = FALSE; + BOOL bWriteError = FALSE; + BOOL bWriteCorrect = FALSE; + BOOL bWriteFixed = FALSE; + BOOL bFixTags = FALSE; + BOOL bAllowKID = FALSE; + BOOL bAllowSuspicious = FALSE; + String aErrorFilename; + String aCorrectFilename; + String aFixedFilename; + BOOL bFileHasError = FALSE; + ByteString aSourceLang( "en-US" ); // English is default + ByteString aFilename; + ByteString aReferenceFilename; + BOOL bReferenceFile = FALSE; + for ( USHORT i = 1 ; i < argc ; i++ ) + { + if ( *argv[ i ] == '-' ) + { + switch (*(argv[ i ]+1)) + { + case 'c':bPrintContext = TRUE; + break; + case 'w': + { + if ( (*(argv[ i ]+2)) == 'e' ) + { + if ( (*(argv[ i ]+3)) == 'f' ) + if ( (i+1) < argc ) + { + aErrorFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); + bWriteError = TRUE; + i++; + } + else + { + fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); + bError = TRUE; + } + else + bWriteError = TRUE; + } + else if ( (*(argv[ i ]+2)) == 'c' ) + if ( (*(argv[ i ]+3)) == 'f' ) + if ( (i+1) < argc ) + { + aCorrectFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); + bWriteCorrect = TRUE; + i++; + } + else + { + fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); + bError = TRUE; + } + else + bWriteCorrect = TRUE; + else if ( (*(argv[ i ]+2)) == 'f' ) + if ( (*(argv[ i ]+3)) == 'f' ) + if ( (i+1) < argc ) + { + aFixedFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); + bWriteFixed = TRUE; + bFixTags = TRUE; + i++; + } + else + { + fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); + bError = TRUE; + } + else + { + bWriteFixed = TRUE; + bFixTags = TRUE; + } + else + { + fprintf( stderr, "\nERROR: Unknown Switch %s!\n\n", argv[ i ] ); + bError = TRUE; + } + } + break; + case 's':bCheckSourceLang = TRUE; + break; + case 't':bCheckTranslationLang = TRUE; + break; + case 'l': + { + if ( (i+1) < argc ) + { + aSourceLang = ByteString( argv[ i+1 ] ); + if ( aSourceLang.EqualsIgnoreCaseAscii( "none" ) ) + aSourceLang.Erase(); + i++; + } + else + { + fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); + bError = TRUE; + } + } + break; + case 'r': + { + if ( (i+1) < argc ) + { + aReferenceFilename = argv[ i+1 ]; + bReferenceFile = TRUE; + i++; + } + else + { + fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); + bError = TRUE; + } + } + break; + case 'f': + { + bFixTags = TRUE; + } + break; + case 'k': + { + bAllowKID = TRUE; + } + break; + case 'e': + { + bAllowSuspicious = TRUE; + } + break; + default: + fprintf( stderr, "\nERROR: Unknown Switch %s!\n\n", argv[ i ] ); + bError = TRUE; + } + } + else + { + if ( !aFilename.Len()) + aFilename = ByteString( argv[ i ] ); + else + { + fprintf( stderr, "\nERROR: Only one filename may be specified!\n\n"); + bError = TRUE; + } + } + } + + + if ( !aFilename.Len() || bError ) + { + Help(); + exit ( 0 ); + } + + if ( aSourceLang.Len() && !LanguageOK( aSourceLang ) ) + { + fprintf( stderr, "\nERROR: The Language '%s' is invalid!\n\n", aSourceLang.GetBuffer() ); + Help(); + exit ( 1 ); + } + + if ( bCheckSourceLang && bCheckTranslationLang ) + { + fprintf( stderr, "\nERROR: The Options -s and -t are mutually exclusive.\nUse only one of them.\n\n" ); + Help(); + exit ( 1 ); + } + + + + DirEntry aSource = DirEntry( String( aFilename, RTL_TEXTENCODING_ASCII_US )); + if ( !aSource.Exists()) { + fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", aFilename.GetBuffer() ); + exit ( 2 ); + } + + SvFileStream aGSI( String( aFilename, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); + if ( !aGSI.IsOpen()) { + fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", aFilename.GetBuffer() ); + exit ( 3 ); + } + + SvFileStream aReferenceGSI; + if ( bReferenceFile ) + { + DirEntry aReferenceSource = DirEntry( String( aReferenceFilename, RTL_TEXTENCODING_ASCII_US )); + if ( !aReferenceSource.Exists()) { + fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", aFilename.GetBuffer() ); + exit ( 2 ); + } + + aReferenceGSI.Open( String( aReferenceFilename, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); + if ( !aReferenceGSI.IsOpen()) { + fprintf( stderr, "\nERROR: Could not open Input-File %s!\n\n", aFilename.GetBuffer() ); + exit ( 3 ); + } + } + + LazySvFileStream aOkOut; + String aBaseName = aSource.GetBase(); + if ( bWriteCorrect ) + { + if ( !aCorrectFilename.Len() ) + { + String sTmpBase( aBaseName ); + sTmpBase += String( "_ok", RTL_TEXTENCODING_ASCII_US ); + aSource.SetBase( sTmpBase ); + aCorrectFilename = aSource.GetFull(); + } + aOkOut.SetOpenParams( aCorrectFilename , STREAM_STD_WRITE | STREAM_TRUNC ); + } + + LazySvFileStream aErrOut; + if ( bWriteError ) + { + if ( !aErrorFilename.Len() ) + { + String sTmpBase( aBaseName ); + sTmpBase += String( "_err", RTL_TEXTENCODING_ASCII_US ); + aSource.SetBase( sTmpBase ); + aErrorFilename = aSource.GetFull(); + } + aErrOut.SetOpenParams( aErrorFilename , STREAM_STD_WRITE | STREAM_TRUNC ); + } + + LazySvFileStream aFixOut; + if ( bWriteFixed ) + { + if ( !aFixedFilename.Len() ) + { + String sTmpBase( aBaseName ); + sTmpBase += String( "_fix", RTL_TEXTENCODING_ASCII_US ); + aSource.SetBase( sTmpBase ); + aFixedFilename = aSource.GetFull(); + } + aFixOut.SetOpenParams( aFixedFilename , STREAM_STD_WRITE | STREAM_TRUNC ); + } + + + ByteString sReferenceLine; + GSILine* pReferenceLine = NULL; + ByteString aOldReferenceId("No Valid ID"); // just set to something which can never be an ID + ULONG nReferenceLine = 0; + + ByteString sGSILine; + GSILine* pGSILine = NULL; + ByteString aOldId("No Valid ID"); // just set to something which can never be an ID + GSIBlock *pBlock = NULL; + ULONG nLine = 0; + + while ( !aGSI.IsEof() ) + { + aGSI.ReadLine( sGSILine ); + nLine++; + pGSILine = new GSILine( sGSILine, nLine ); + BOOL bDelete = TRUE; + + + if ( pGSILine->Len() ) + { + if ( FORMAT_UNKNOWN == pGSILine->GetLineFormat() ) + { + PrintError( "Format of line is unknown. Ignoring!", "Line format", pGSILine->Copy( 0,40 ), bPrintContext, pGSILine->GetLineNumber() ); + pGSILine->NotOK(); + if ( bWriteError ) + { + bFileHasError = TRUE; + aErrOut.LazyOpen(); + aErrOut.WriteLine( *pGSILine ); + } + } + else if ( pGSILine->GetLineType().EqualsIgnoreCaseAscii("res-comment") ) + { // ignore comment lines, but write them to Correct Items File + if ( bWriteCorrect ) + { + aOkOut.LazyOpen(); + aOkOut.WriteLine( *pGSILine ); + } + } + else + { + ByteString aId = pGSILine->GetUniqId(); + if ( aId != aOldId ) + { + if ( pBlock ) + { + bFileHasError |= pBlock->CheckSyntax( nLine, aSourceLang.Len() != 0, bFixTags ); + + if ( bWriteError ) + pBlock->WriteError( aErrOut, aSourceLang.Len() != 0 ); + if ( bWriteCorrect ) + pBlock->WriteCorrect( aOkOut, aSourceLang.Len() != 0 ); + if ( bWriteFixed ) + pBlock->WriteFixed( aFixOut, aSourceLang.Len() != 0 ); + + delete pBlock; + } + pBlock = new GSIBlock( bPrintContext, bCheckSourceLang, bCheckTranslationLang, bReferenceFile, bAllowKID, bAllowSuspicious ); + + aOldId = aId; + + + // find corresponding line in reference file + if ( bReferenceFile ) + { + BOOL bContinueSearching = TRUE; + while ( ( !aReferenceGSI.IsEof() || pReferenceLine ) && bContinueSearching ) + { + if ( !pReferenceLine ) + { + aReferenceGSI.ReadLine( sReferenceLine ); + nReferenceLine++; + pReferenceLine = new GSILine( sReferenceLine, nReferenceLine ); + } + if ( pReferenceLine->GetLineFormat() != FORMAT_UNKNOWN ) + { + if ( pReferenceLine->GetUniqId() == aId && pReferenceLine->GetLanguageId().Equals( aSourceLang ) ) + { + pBlock->SetReferenceLine( pReferenceLine ); + pReferenceLine = NULL; + } + else if ( pReferenceLine->GetUniqId() > aId ) + { +// if ( pGSILine->GetLanguageId() == aSourceLang ) +// PrintError( "No reference line found. Entry is new in source file", "File format", "", bPrintContext, pGSILine->GetLineNumber(), aId ); + bContinueSearching = FALSE; + } + else + { + if ( pReferenceLine->GetUniqId() < aId && pReferenceLine->GetLanguageId().Equals( aSourceLang ) ) + PrintError( "No Entry in source file found. Entry has been removed from source file", "File format", "", bPrintContext, pGSILine->GetLineNumber(), pReferenceLine->GetUniqId() ); + delete pReferenceLine; + pReferenceLine = NULL; + } + } + else + { + delete pReferenceLine; + pReferenceLine = NULL; + } + + } + } + + } + + pBlock->InsertLine( pGSILine, aSourceLang ); + bDelete = FALSE; + } + } + if ( bDelete ) + delete pGSILine; + + } + if ( pBlock ) + { + bFileHasError |= pBlock->CheckSyntax( nLine, aSourceLang.Len() != 0, bFixTags ); + + if ( bWriteError ) + pBlock->WriteError( aErrOut, aSourceLang.Len() != 0 ); + if ( bWriteCorrect ) + pBlock->WriteCorrect( aOkOut, aSourceLang.Len() != 0 ); + if ( bWriteFixed ) + pBlock->WriteFixed( aFixOut, aSourceLang.Len() != 0 ); + + delete pBlock; + } + aGSI.Close(); + + if ( bWriteError ) + aErrOut.Close(); + if ( bWriteCorrect ) + aOkOut.Close(); + if ( bWriteFixed ) + aFixOut.Close(); + + if ( bFileHasError ) + return 55; + else + return 0; +} diff --git a/l10ntools/source/gsiconv.cxx b/l10ntools/source/gsiconv.cxx new file mode 100644 index 000000000000..e127e55482da --- /dev/null +++ b/l10ntools/source/gsiconv.cxx @@ -0,0 +1,372 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: gsiconv.cxx,v $ + * $Revision: 1.8 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +#include + +// local includes +#include "utf8conv.hxx" + +#define GSI_FILE_UNKNOWN 0x0000 +#define GSI_FILE_OLDSTYLE 0x0001 +#define GSI_FILE_L10NFRAMEWORK 0x0002 + +/*****************************************************************************/ +USHORT GetGSIFileType( SvStream &rStream ) +/*****************************************************************************/ +{ + USHORT nFileType = GSI_FILE_UNKNOWN; + + ULONG nPos( rStream.Tell()); + rStream.Seek( STREAM_SEEK_TO_BEGIN ); + + ByteString sLine; + while( !rStream.IsEof() && !sLine.Len()) + rStream.ReadLine( sLine ); + + if( sLine.Len()) { + if( sLine.Search( "($$)" ) != STRING_NOTFOUND ) + nFileType = GSI_FILE_OLDSTYLE; + else + nFileType = GSI_FILE_L10NFRAMEWORK; + } + + rStream.Seek( nPos ); + + return nFileType; +} + +/*****************************************************************************/ +ByteString GetGSILineId( const ByteString &rLine, USHORT nFileType ) +/*****************************************************************************/ +{ + ByteString sId; + switch ( nFileType ) { + case GSI_FILE_OLDSTYLE: + sId = rLine; + sId.SearchAndReplaceAll( "($$)", "\t" ); + sId = sId.GetToken( 0, '\t' ); + break; + + case GSI_FILE_L10NFRAMEWORK: + sId = rLine.GetToken( 0, '\t' ); + sId += "\t"; + sId += rLine.GetToken( 1, '\t' ); + sId += "\t"; + sId += rLine.GetToken( 4, '\t' ); + sId += "\t"; + sId += rLine.GetToken( 5, '\t' ); + break; + } + return sId; +} + +/*****************************************************************************/ +ByteString GetGSILineLangId( const ByteString &rLine, USHORT nFileType ) +/*****************************************************************************/ +{ + ByteString sLangId; + switch ( nFileType ) { + case GSI_FILE_OLDSTYLE: + sLangId = rLine; + sLangId.SearchAndReplaceAll( "($$)", "\t" ); + sLangId = sLangId.GetToken( 2, '\t' ); + break; + + case GSI_FILE_L10NFRAMEWORK: + sLangId = rLine.GetToken( 9, '\t' ); + break; + } + return sLangId; +} + +/*****************************************************************************/ +void ConvertGSILine( BOOL bToUTF8, ByteString &rLine, + rtl_TextEncoding nEncoding, USHORT nFileType ) +/*****************************************************************************/ +{ + switch ( nFileType ) { + case GSI_FILE_OLDSTYLE: + if ( bToUTF8 ) + rLine = UTF8Converter::ConvertToUTF8( rLine, nEncoding ); + else + rLine = UTF8Converter::ConvertFromUTF8( rLine, nEncoding ); + break; + + case GSI_FILE_L10NFRAMEWORK: { + ByteString sConverted; + for ( USHORT i = 0; i < rLine.GetTokenCount( '\t' ); i++ ) { + ByteString sToken = rLine.GetToken( i, '\t' ); + if (( i > 9 ) && ( i < 14 )) { + if( bToUTF8 ) + sToken = UTF8Converter::ConvertToUTF8( sToken, nEncoding ); + else + sToken = UTF8Converter::ConvertFromUTF8( sToken, nEncoding ); + } + if ( i ) + sConverted += "\t"; + sConverted += sToken; + } + rLine = sConverted; + } + break; + } +} + +/*****************************************************************************/ +void Help() +/*****************************************************************************/ +{ + fprintf( stdout, "\n" ); + fprintf( stdout, "gsiconv (c)1999 by StarOffice Entwicklungs GmbH\n" ); + fprintf( stdout, "===============================================\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "gsiconv converts strings in GSI-Files (Gutschmitt Interface) from or to UTF-8\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "Syntax: gsiconv (-t|-f langid charset)|(-p n) filename\n" ); + fprintf( stdout, "Switches: -t => conversion from charset to UTF-8\n" ); + fprintf( stdout, " -f => conversion from UTF-8 to charset\n" ); + fprintf( stdout, " -p n => creates several files with ca. n lines\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "Allowed charsets:\n" ); + fprintf( stdout, " MS_932 => Japanese\n" ); + fprintf( stdout, " MS_936 => Chinese Simplified\n" ); + fprintf( stdout, " MS_949 => Korean\n" ); + fprintf( stdout, " MS_950 => Chinese Traditional\n" ); + fprintf( stdout, " MS_1250 => East Europe\n" ); + fprintf( stdout, " MS_1251 => Cyrillic\n" ); + fprintf( stdout, " MS_1252 => West Europe\n" ); + fprintf( stdout, " MS_1253 => Greek\n" ); + fprintf( stdout, " MS_1254 => Turkish\n" ); + fprintf( stdout, " MS_1255 => Hebrew\n" ); + fprintf( stdout, " MS_1256 => Arabic\n" ); + fprintf( stdout, "\n" ); + fprintf( stdout, "Allowed langids:\n" ); + fprintf( stdout, " 1 => ENGLISH_US\n" ); + fprintf( stdout, " 3 => PORTUGUESE \n" ); + fprintf( stdout, " 4 => GERMAN_DE (new german style)\n" ); + fprintf( stdout, " 7 => RUSSIAN\n" ); + fprintf( stdout, " 30 => GREEK\n" ); + fprintf( stdout, " 31 => DUTCH\n" ); + fprintf( stdout, " 33 => FRENCH\n" ); + fprintf( stdout, " 34 => SPANISH\n" ); + fprintf( stdout, " 35 => FINNISH\n" ); + fprintf( stdout, " 36 => HUNGARIAN\n" ); + fprintf( stdout, " 39 => ITALIAN\n" ); + fprintf( stdout, " 42 => CZECH\n" ); + fprintf( stdout, " 44 => ENGLISH (UK)\n" ); + fprintf( stdout, " 45 => DANISH\n" ); + fprintf( stdout, " 46 => SWEDISH\n" ); + fprintf( stdout, " 47 => NORWEGIAN\n" ); + fprintf( stdout, " 49 => GERMAN (old german style)\n" ); + fprintf( stdout, " 55 => PORTUGUESE_BRAZILIAN\n" ); + fprintf( stdout, " 81 => JAPANESE\n" ); + fprintf( stdout, " 82 => KOREAN\n" ); + fprintf( stdout, " 86 => CHINESE_SIMPLIFIED\n" ); + fprintf( stdout, " 88 => CHINESE_TRADITIONAL\n" ); + fprintf( stdout, " 90 => TURKISH\n" ); + fprintf( stdout, " 96 => ARABIC\n" ); + fprintf( stdout, " 97 => HEBREW\n" ); + fprintf( stdout, "\n" ); +} + +/*****************************************************************************/ +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + if (( argc != 5 ) && ( argc != 4 )) { + Help(); + exit ( 0 ); + } + + if ( argc == 4 ) { + if ( ByteString( argv[ 1 ] ) == "-p" ) { + + DirEntry aSource = DirEntry( String( argv[ 3 ], RTL_TEXTENCODING_ASCII_US )); + if ( !aSource.Exists()) { + fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); + exit ( 2 ); + } + + DirEntry aOutput( aSource ); + + String sBase = aOutput.GetBase(); + String sExt = aOutput.GetExtension(); + + String sGSI( argv[ 3 ], RTL_TEXTENCODING_ASCII_US ); + SvFileStream aGSI( sGSI, STREAM_STD_READ ); + if ( !aGSI.IsOpen()) { + fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); + exit ( 3 ); + } + + USHORT nFileType( GetGSIFileType( aGSI )); + + ULONG nMaxLines = (ULONG) ByteString( argv[ 2 ] ).ToInt64(); + if ( !nMaxLines ) { + fprintf( stderr, "\nERROR: Linecount must be at least 1!\n\n" ); + exit ( 3 ); + } + + ByteString sGSILine; + ByteString sOldId; + ULONG nLine = 0; + ULONG nOutputFile = 1; + + String sOutput( sBase ); + sOutput += String( "_", RTL_TEXTENCODING_ASCII_US ); + sOutput += String::CreateFromInt64( nOutputFile ); + if ( sExt.Len()) { + sOutput += String( ".", RTL_TEXTENCODING_ASCII_US ); + sOutput += sExt; + } + nOutputFile ++; + + aOutput.SetName( sOutput ); + SvFileStream aOutputStream( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); + + while ( !aGSI.IsEof()) { + + aGSI.ReadLine( sGSILine ); + ByteString sId( GetGSILineId( sGSILine, nFileType )); + + nLine++; + + if (( nLine >= nMaxLines ) && ( sId != sOldId )) { + aOutputStream.Close(); + + ByteString sText( aOutput.GetFull(), gsl_getSystemTextEncoding()); + sText += " with "; + sText += ByteString::CreateFromInt64( nLine ); + sText += " lines written."; + + fprintf( stdout, "%s\n", sText.GetBuffer()); + String sOutput1( sBase ); + sOutput1 += String( "_", RTL_TEXTENCODING_ASCII_US ); + sOutput1 += String::CreateFromInt64( nOutputFile ); + if ( sExt.Len()) { + sOutput1 += String( ".", RTL_TEXTENCODING_ASCII_US ); + sOutput1 += sExt; + } + nOutputFile ++; + + aOutput.SetName( sOutput1 ); + + aOutputStream.Open( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); + nLine = 0; + } + + aOutputStream.WriteLine( sGSILine ); + + sOldId = sId; + } + + aGSI.Close(); + aOutputStream.Close(); + + ByteString sText( aOutput.GetFull(), RTL_TEXTENCODING_ASCII_US ); + sText += " with "; + sText += ByteString::CreateFromInt64( nLine ); + sText += " lines written."; + } + else { + Help(); + exit( 1 ); + } + } + else { + if ( ByteString( argv[ 1 ] ) == "-t" || ByteString( argv[ 1 ] ) == "-f" ) { + rtl_TextEncoding nEncoding; + + ByteString sCurLangId( argv[ 2 ] ); + + ByteString sCharset( argv[ 3 ] ); + sCharset.ToUpperAscii(); + + if ( sCharset == "MS_932" ) nEncoding = RTL_TEXTENCODING_MS_932; + else if ( sCharset == "MS_936" ) nEncoding = RTL_TEXTENCODING_MS_936; + else if ( sCharset == "MS_949" ) nEncoding = RTL_TEXTENCODING_MS_949; + else if ( sCharset == "MS_950" ) nEncoding = RTL_TEXTENCODING_MS_950; + else if ( sCharset == "MS_1250" ) nEncoding = RTL_TEXTENCODING_MS_1250; + else if ( sCharset == "MS_1251" ) nEncoding = RTL_TEXTENCODING_MS_1251; + else if ( sCharset == "MS_1252" ) nEncoding = RTL_TEXTENCODING_MS_1252; + else if ( sCharset == "MS_1253" ) nEncoding = RTL_TEXTENCODING_MS_1253; + else if ( sCharset == "MS_1254" ) nEncoding = RTL_TEXTENCODING_MS_1254; + else if ( sCharset == "MS_1255" ) nEncoding = RTL_TEXTENCODING_MS_1255; + else if ( sCharset == "MS_1256" ) nEncoding = RTL_TEXTENCODING_MS_1256; + else if ( sCharset == "MS_1257" ) nEncoding = RTL_TEXTENCODING_MS_1257; + else if ( sCharset == "UTF8" ) nEncoding = RTL_TEXTENCODING_UTF8; + + else { + Help(); + exit ( 1 ); + } + + DirEntry aSource = DirEntry( String( argv[ 4 ], RTL_TEXTENCODING_ASCII_US )); + if ( !aSource.Exists()) { + fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); + exit ( 2 ); + } + + String sGSI( argv[ 4 ], RTL_TEXTENCODING_ASCII_US ); + SvFileStream aGSI( sGSI, STREAM_STD_READ ); + if ( !aGSI.IsOpen()) { + fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); + exit ( 3 ); + } + USHORT nFileType( GetGSIFileType( aGSI )); + + ByteString sGSILine; + while ( !aGSI.IsEof()) { + + aGSI.ReadLine( sGSILine ); + ByteString sLangId( GetGSILineLangId( sGSILine, nFileType )); + if ( sLangId == sCurLangId ) + ConvertGSILine(( ByteString( argv[ 1 ] ) == "-t" ), sGSILine, nEncoding, nFileType ); + + fprintf( stdout, "%s\n", sGSILine.GetBuffer()); + } + + aGSI.Close(); + } + else { + Help(); + exit( 1 ); + } + } + return 0; +} diff --git a/l10ntools/source/help/HelpCompiler.cxx b/l10ntools/source/help/HelpCompiler.cxx new file mode 100644 index 000000000000..5001d0907972 --- /dev/null +++ b/l10ntools/source/help/HelpCompiler.cxx @@ -0,0 +1,593 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: HelpCompiler.cxx,v $ + * $Revision: 1.9 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + + +#include "HelpCompiler.hxx" +#include +#include +#include +#include +#include +#include +#include +#ifdef __MINGW32__ +#include +#include +#endif +#include + +static void impl_sleep( sal_uInt32 nSec ) +{ + TimeValue aTime; + aTime.Seconds = nSec; + aTime.Nanosec = 0; + + osl::Thread::wait( aTime ); +} + +HelpCompiler::HelpCompiler(StreamTable &in_streamTable, const fs::path &in_inputFile, + const fs::path &in_src, const fs::path &in_resEmbStylesheet, + const std::string &in_module, const std::string &in_lang, bool in_bExtensionMode) + : streamTable(in_streamTable), inputFile(in_inputFile), + src(in_src), module(in_module), lang(in_lang), resEmbStylesheet(in_resEmbStylesheet), + bExtensionMode( in_bExtensionMode ) +{ + xmlKeepBlanksDefaultValue = 0; +} + +xmlDocPtr HelpCompiler::getSourceDocument(const fs::path &filePath) +{ + static const char *params[4 + 1]; + static xsltStylesheetPtr cur = NULL; + + xmlDocPtr res; + if( bExtensionMode ) + { + res = xmlParseFile(filePath.native_file_string().c_str()); + if( !res ){ + impl_sleep( 3 ); + res = xmlParseFile(filePath.native_file_string().c_str()); + } + } + else + { + if (!cur) + { + static std::string fsroot('\'' + src.toUTF8() + '\''); + static std::string esclang('\'' + lang + '\''); + + xmlSubstituteEntitiesDefault(1); + xmlLoadExtDtdDefaultValue = 1; + cur = xsltParseStylesheetFile((const xmlChar *)resEmbStylesheet.native_file_string().c_str()); + + int nbparams = 0; + params[nbparams++] = "Language"; + params[nbparams++] = esclang.c_str(); + params[nbparams++] = "fsroot"; + params[nbparams++] = fsroot.c_str(); + params[nbparams] = NULL; + } + xmlDocPtr doc = xmlParseFile(filePath.native_file_string().c_str()); + if( !doc ) + { + impl_sleep( 3 ); + doc = xmlParseFile(filePath.native_file_string().c_str()); + } + + //???res = xmlParseFile(filePath.native_file_string().c_str()); + + res = xsltApplyStylesheet(cur, doc, params); + xmlFreeDoc(doc); + } + return res; +} + +HashSet HelpCompiler::switchFind(xmlDocPtr doc) +{ + HashSet hs; + xmlChar *xpath = (xmlChar*)"//switchinline"; + + xmlXPathContextPtr context = xmlXPathNewContext(doc); + xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context); + xmlXPathFreeContext(context); + if (result) + { + xmlNodeSetPtr nodeset = result->nodesetval; + for (int i = 0; i < nodeset->nodeNr; i++) + { + xmlNodePtr el = nodeset->nodeTab[i]; + xmlChar *select = xmlGetProp(el, (xmlChar*)"select"); + if (select) + { + if (!strcmp((const char*)select, "appl")) + { + xmlNodePtr n1 = el->xmlChildrenNode; + while (n1) + { + if ((!xmlStrcmp(n1->name, (const xmlChar*)"caseinline"))) + { + xmlChar *appl = xmlGetProp(n1, (xmlChar*)"select"); + hs.push_back(std::string((const char*)appl)); + xmlFree(appl); + } + else if ((!xmlStrcmp(n1->name, (const xmlChar*)"defaultinline"))) + hs.push_back(std::string("DEFAULT")); + n1 = n1->next; + } + } + xmlFree(select); + } + } + xmlXPathFreeObject(result); + } + hs.push_back(std::string("DEFAULT")); + return hs; +} + +// returns a node representing the whole stuff compiled for the current +// application. +xmlNodePtr HelpCompiler::clone(xmlNodePtr node, const std::string& appl) +{ + xmlNodePtr parent = xmlCopyNode(node, 2); + xmlNodePtr n = node->xmlChildrenNode; + while (n != NULL) + { + bool isappl = false; + if ( (!strcmp((const char*)n->name, "switchinline")) || + (!strcmp((const char*)n->name, "switch")) ) + { + xmlChar *select = xmlGetProp(n, (xmlChar*)"select"); + if (select) + { + if (!strcmp((const char*)select, "appl")) + isappl = true; + xmlFree(select); + } + } + if (isappl) + { + xmlNodePtr caseNode = n->xmlChildrenNode; + if (appl == "DEFAULT") + { + while (caseNode) + { + if (!strcmp((const char*)caseNode->name, "defaultinline")) + { + xmlNodePtr cnl = caseNode->xmlChildrenNode; + while (cnl) + { + xmlAddChild(parent, clone(cnl, appl)); + cnl = cnl->next; + } + break; + } + caseNode = caseNode->next; + } + } + else + { + while (caseNode) + { + isappl=false; + if (!strcmp((const char*)caseNode->name, "caseinline")) + { + xmlChar *select = xmlGetProp(n, (xmlChar*)"select"); + if (select) + { + if (!strcmp((const char*)select, appl.c_str())) + isappl = true; + xmlFree(select); + } + if (isappl) + { + xmlNodePtr cnl = caseNode->xmlChildrenNode; + while (cnl) + { + xmlAddChild(parent, clone(cnl, appl)); + cnl = cnl->next; + } + break; + } + + } + caseNode = caseNode->next; + } + } + + } + else + xmlAddChild(parent, clone(n, appl)); + + n = n->next; + } + return parent; +} + +class myparser +{ +public: + std::string documentId; + std::string fileName; + std::string title; + HashSet *hidlist; + Hashtable *keywords; + Stringtable *helptexts; +private: + HashSet extendedHelpText; +public: + myparser(const std::string &indocumentId, const std::string &infileName, + const std::string &intitle) : documentId(indocumentId), fileName(infileName), + title(intitle) + { + hidlist = new HashSet; + keywords = new Hashtable; + helptexts = new Stringtable; + } + void traverse( xmlNodePtr parentNode ); +private: + std::string dump(xmlNodePtr node); +}; + +std::string myparser::dump(xmlNodePtr node) +{ + std::string app; + if (node->xmlChildrenNode) + { + xmlNodePtr list = node->xmlChildrenNode; + while (list) + { + app += dump(list); + list = list->next; + } + } + if (xmlNodeIsText(node)) + { + xmlChar *pContent = xmlNodeGetContent(node); + app += std::string((const char*)pContent); + xmlFree(pContent); + // std::cout << app << std::endl; + } + return app; +} + +void trim(std::string& str) +{ + std::string::size_type pos = str.find_last_not_of(' '); + if(pos != std::string::npos) + { + str.erase(pos + 1); + pos = str.find_first_not_of(' '); + if(pos != std::string::npos) + str.erase(0, pos); + } + else + str.erase(str.begin(), str.end()); +} + +void myparser::traverse( xmlNodePtr parentNode ) +{ + // traverse all nodes that belong to the parent + xmlNodePtr test ; + for (test = parentNode->xmlChildrenNode; test; test = test->next) + { + if (fileName.empty() && !strcmp((const char*)test->name, "filename")) + { + xmlNodePtr node = test->xmlChildrenNode; + if (xmlNodeIsText(node)) + { + xmlChar *pContent = xmlNodeGetContent(node); + fileName = std::string((const char*)pContent); + xmlFree(pContent); + } + } + else if (title.empty() && !strcmp((const char*)test->name, "title")) + { + title = dump(test); + if (title.empty()) + title = ""; + } + else if (!strcmp((const char*)test->name, "bookmark")) + { + xmlChar *branchxml = xmlGetProp(test, (const xmlChar*)"branch"); + xmlChar *idxml = xmlGetProp(test, (const xmlChar*)"id"); + std::string branch((const char*)branchxml); + std::string anchor((const char*)idxml); + xmlFree (branchxml); + xmlFree (idxml); + + std::string hid; + + if (branch.find("hid") == 0) + { + size_t index = branch.find('/'); + if (index != std::string::npos) + { + hid = branch.substr(1 + index); + // one shall serve as a documentId + if (documentId.empty()) + documentId = hid; + extendedHelpText.push_back(hid); + std::string foo = anchor.empty() ? hid : hid + "#" + anchor; + HCDBG(std::cerr << "hid pushback" << foo << std::endl); + hidlist->push_back( anchor.empty() ? hid : hid + "#" + anchor); + } + else + continue; + } + else if (branch.compare("index") == 0) + { + LinkedList ll; + + for (xmlNodePtr nd = test->xmlChildrenNode; nd; nd = nd->next) + { + if (strcmp((const char*)nd->name, "bookmark_value")) + continue; + + std::string embedded; + xmlChar *embeddedxml = xmlGetProp(nd, (const xmlChar*)"embedded"); + if (embeddedxml) + { + embedded = std::string((const char*)embeddedxml); + xmlFree (embeddedxml); + std::transform (embedded.begin(), embedded.end(), + embedded.begin(), tolower); + } + + bool isEmbedded = !embedded.empty() && embedded.compare("true") == 0; + if (isEmbedded) + continue; + + std::string keyword = dump(nd); + size_t keywordSem = keyword.find(';'); + if (keywordSem != std::string::npos) + { + std::string tmppre = + keyword.substr(0,keywordSem); + trim(tmppre); + std::string tmppos = + keyword.substr(1+keywordSem); + trim(tmppos); + keyword = tmppre + ";" + tmppos; + } + ll.push_back(keyword); + } + if (!ll.empty()) + (*keywords)[anchor] = ll; + } + else if (branch.compare("contents") == 0) + { + // currently not used + } + } + else if (!strcmp((const char*)test->name, "ahelp")) + { + std::string text = dump(test); + trim(text); + std::string name; + + HashSet::const_iterator aEnd = extendedHelpText.end(); + for (HashSet::const_iterator iter = extendedHelpText.begin(); iter != aEnd; + ++iter) + { + name = *iter; + (*helptexts)[name] = text; + } + extendedHelpText.clear(); + } + + // traverse children + traverse(test); + } +} + +bool HelpCompiler::compile( void ) throw( HelpProcessingException ) +{ + // we now have the jaroutputstream, which will contain the document. + // now determine the document as a dom tree in variable docResolved + + xmlDocPtr docResolvedOrg = getSourceDocument(inputFile); + + // now add path to the document + // resolve the dom + if (!docResolvedOrg) + { + impl_sleep( 3 ); + docResolvedOrg = getSourceDocument(inputFile); + if( !docResolvedOrg ) + { + std::stringstream aStrStream; + aStrStream << "ERROR: file not existing: " << inputFile.native_file_string().c_str() << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + } + + // now find all applications for which one has to compile + std::string documentId; + std::string fileName; + std::string title; + // returns all applications for which one has to compile + HashSet applications = switchFind(docResolvedOrg); + + HashSet::const_iterator aEnd = applications.end(); + for (HashSet::const_iterator aI = applications.begin(); aI != aEnd; ++aI) + { + std::string appl = *aI; + std::string modulename = appl; + if (modulename[0] == 'S') + { + modulename = modulename.substr(1); + std::transform(modulename.begin(), modulename.end(), modulename.begin(), tolower); + } + if (modulename != "DEFAULT" && modulename != module) + continue; + + // returns a clone of the document with swich-cases resolved + xmlNodePtr docResolved = clone(xmlDocGetRootElement(docResolvedOrg), appl); + myparser aparser(documentId, fileName, title); + aparser.traverse(docResolved); + + documentId = aparser.documentId; + fileName = aparser.fileName; + title = aparser.title; + + HCDBG(std::cerr << documentId << " : " << fileName << " : " << title << std::endl); + + xmlDocPtr docResolvedDoc = xmlCopyDoc(docResolvedOrg, false); + xmlDocSetRootElement(docResolvedDoc, docResolved); + + if (modulename == "DEFAULT") + { + streamTable.dropdefault(); + streamTable.default_doc = docResolvedDoc; + streamTable.default_hidlist = aparser.hidlist; + streamTable.default_helptexts = aparser.helptexts; + streamTable.default_keywords = aparser.keywords; + } + else if (modulename == module) + { + streamTable.dropappl(); + streamTable.appl_doc = docResolvedDoc; + streamTable.appl_hidlist = aparser.hidlist; + streamTable.appl_helptexts = aparser.helptexts; + streamTable.appl_keywords = aparser.keywords; + } + else + { + std::stringstream aStrStream; + aStrStream << "ERROR: Found unexpected module name \"" << modulename + << "\" in file" << src.native_file_string().c_str() << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + } // end iteration over all applications + + streamTable.document_id = documentId; + streamTable.document_path = fileName; + streamTable.document_title = title; + std::string actMod = module; + if ( !bExtensionMode && !fileName.empty()) + { + if (fileName.find("/text/") == 0) + { + int len = strlen("/text/"); + actMod = fileName.substr(len); + actMod = actMod.substr(0, actMod.find('/')); + } + } + streamTable.document_module = actMod; + + xmlFreeDoc(docResolvedOrg); + return true; +} + +namespace fs +{ + rtl_TextEncoding getThreadTextEncoding( void ) + { + static bool bNeedsInit = true; + static rtl_TextEncoding nThreadTextEncoding; + if( bNeedsInit ) + { + bNeedsInit = false; + nThreadTextEncoding = osl_getThreadTextEncoding(); + } + return nThreadTextEncoding; + } + + void create_directory(const fs::path indexDirName) + { + HCDBG( + std::cerr << "creating " << + rtl::OUStringToOString(indexDirName.data, RTL_TEXTENCODING_UTF8).getStr() + << std::endl + ); + osl::Directory::createPath(indexDirName.data); + } + + void rename(const fs::path &src, const fs::path &dest) + { + osl::File::move(src.data, dest.data); + } + + void copy(const fs::path &src, const fs::path &dest) + { + osl::File::copy(src.data, dest.data); + } + + bool exists(const fs::path &in) + { + osl::File tmp(in.data); + return (tmp.open(osl_File_OpenFlag_Read) == osl::FileBase::E_None); + } + + void remove(const fs::path &in) + { + osl::File::remove(in.data); + } + + void removeRecursive(rtl::OUString const& _suDirURL) + { + { + osl::Directory aDir(_suDirURL); + aDir.open(); + if (aDir.isOpen()) + { + osl::DirectoryItem aItem; + osl::FileStatus aStatus(osl_FileStatus_Mask_FileName | osl_FileStatus_Mask_Attributes); + while (aDir.getNextItem(aItem) == ::osl::FileBase::E_None) + { + if (osl::FileBase::E_None == aItem.getFileStatus(aStatus) && + aStatus.isValid(osl_FileStatus_Mask_FileName | osl_FileStatus_Mask_Attributes)) + { + rtl::OUString suFilename = aStatus.getFileName(); + rtl::OUString suFullFileURL; + suFullFileURL += _suDirURL; + suFullFileURL += rtl::OUString::createFromAscii("/"); + suFullFileURL += suFilename; + + if (aStatus.getFileType() == osl::FileStatus::Directory) + removeRecursive(suFullFileURL); + else + osl::File::remove(suFullFileURL); + } + } + aDir.close(); + } + } + osl::Directory::remove(_suDirURL); + } + + void remove_all(const fs::path &in) + { + removeRecursive(in.data); + } +} + +/* vi:set tabstop=4 shiftwidth=4 expandtab: */ diff --git a/l10ntools/source/help/HelpCompiler.hxx b/l10ntools/source/help/HelpCompiler.hxx new file mode 100644 index 000000000000..7ffb096bd635 --- /dev/null +++ b/l10ntools/source/help/HelpCompiler.hxx @@ -0,0 +1,320 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: HelpCompiler.hxx,v $ + * $Revision: 1.8 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef HELPCOMPILER_HXX +#define HELPCOMPILER_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef SYSTEM_DB +#include +#else +#include +#endif + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#define EMULATEORIGINAL 1 + +#ifdef CMCDEBUG + #define HCDBG(foo) do { if (1) foo; } while(0) +#else + #define HCDBG(foo) do { if (0) foo; } while(0) +#endif + +namespace fs +{ + rtl_TextEncoding getThreadTextEncoding( void ); + + enum convert { native }; + class path + { + public: + ::rtl::OUString data; + public: + path() {} + path(const path &rOther) : data(rOther.data) {} + path(const std::string &in, convert) + { + rtl::OUString sWorkingDir; + osl_getProcessWorkingDir(&sWorkingDir.pData); + + rtl::OString tmp(in.c_str()); + rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); + osl::File::getFileURLFromSystemPath(ustrSystemPath, data); + osl::File::getAbsoluteFileURL(sWorkingDir, data, data); + } + path(const std::string &FileURL) + { + rtl::OString tmp(FileURL.c_str()); + data = rtl::OStringToOUString(tmp, getThreadTextEncoding()); + } + std::string native_file_string() const + { + ::rtl::OUString ustrSystemPath; + osl::File::getSystemPathFromFileURL(data, ustrSystemPath); + rtl::OString tmp(rtl::OUStringToOString(ustrSystemPath, getThreadTextEncoding())); + HCDBG(std::cerr << "native_file_string is " << tmp.getStr() << std::endl); + return std::string(tmp.getStr()); + } + std::string native_directory_string() const { return native_file_string(); } + std::string toUTF8() const + { + rtl::OString tmp(rtl::OUStringToOString(data, RTL_TEXTENCODING_UTF8)); + return std::string(tmp.getStr()); + } + bool empty() const { return data.getLength() == 0; } + path operator/(const std::string &in) const + { + path ret(*this); + HCDBG(std::cerr << "orig was " << + rtl::OUStringToOString(ret.data, RTL_TEXTENCODING_UTF8).getStr() << std::endl); + rtl::OString tmp(in.c_str()); + rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); + ret.data += rtl::OUString(sal_Unicode('/')); + ret.data += ustrSystemPath; + HCDBG(std::cerr << "final is " << + rtl::OUStringToOString(ret.data, RTL_TEXTENCODING_UTF8).getStr() << std::endl); + return ret; + } + void append(const char *in) + { + rtl::OString tmp(in); + rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); + data = data + ustrSystemPath; + } + void append(const std::string &in) { append(in.c_str()); } + }; + + void create_directory(const fs::path indexDirName); + void rename(const fs::path &src, const fs::path &dest); + void copy(const fs::path &src, const fs::path &dest); + bool exists(const fs::path &in); + void remove_all(const fs::path &in); + void remove(const fs::path &in); +} + +struct joaat_hash +{ + size_t operator()(const std::string &str) const + { + size_t hash = 0; + const char *key = str.data(); + for (size_t i = 0; i < str.size(); i++) + { + hash += key[i]; + hash += (hash << 10); + hash ^= (hash >> 6); + } + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + return hash; + } +}; + +#define get16bits(d) ((((sal_uInt32)(((const sal_uInt8 *)(d))[1])) << 8)\ + +(sal_uInt32)(((const sal_uInt8 *)(d))[0]) ) + +struct SuperFastHash +{ + size_t operator()(const std::string &str) const + { + const char * data = str.data(); + int len = str.size(); + size_t hash = len, tmp; + if (len <= 0 || data == NULL) return 0; + + int rem = len & 3; + len >>= 2; + + /* Main loop */ + for (;len > 0; len--) + { + hash += get16bits (data); + tmp = (get16bits (data+2) << 11) ^ hash; + hash = (hash << 16) ^ tmp; + data += 2*sizeof (sal_uInt16); + hash += hash >> 11; + } + + /* Handle end cases */ + switch (rem) + { + case 3: hash += get16bits (data); + hash ^= hash << 16; + hash ^= data[sizeof (sal_uInt16)] << 18; + hash += hash >> 11; + break; + case 2: hash += get16bits (data); + hash ^= hash << 11; + hash += hash >> 17; + break; + case 1: hash += *data; + hash ^= hash << 10; + hash += hash >> 1; + } + + /* Force "avalanching" of final 127 bits */ + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + + return hash; + } +}; + +#define pref_hash joaat_hash + +typedef std::hash_map Stringtable; +typedef std::list LinkedList; +typedef std::vector HashSet; + +typedef std::hash_map Hashtable; + +class StreamTable +{ +public: + std::string document_id; + std::string document_path; + std::string document_module; + std::string document_title; + + HashSet *appl_hidlist; + Hashtable *appl_keywords; + Stringtable *appl_helptexts; + xmlDocPtr appl_doc; + + HashSet *default_hidlist; + Hashtable *default_keywords; + Stringtable *default_helptexts; + xmlDocPtr default_doc; + + StreamTable() : + appl_hidlist(NULL), appl_keywords(NULL), appl_helptexts(NULL), appl_doc(NULL), + default_hidlist(NULL), default_keywords(NULL), default_helptexts(NULL), default_doc(NULL) + {} + void dropdefault() + { + delete default_hidlist; + delete default_keywords; + delete default_helptexts; + if (default_doc) xmlFreeDoc(default_doc); + } + void dropappl() + { + delete appl_hidlist; + delete appl_keywords; + delete appl_helptexts; + if (appl_doc) xmlFreeDoc(appl_doc); + } + ~StreamTable() + { + dropappl(); + dropdefault(); + } +}; + +struct HelpProcessingException +{ + HelpProcessingErrorClass m_eErrorClass; + std::string m_aErrorMsg; + std::string m_aXMLParsingFile; + int m_nXMLParsingLine; + + HelpProcessingException( HelpProcessingErrorClass eErrorClass, const std::string& aErrorMsg ) + : m_eErrorClass( eErrorClass ) + , m_aErrorMsg( aErrorMsg ) + {} + HelpProcessingException( const std::string& aErrorMsg, const std::string& aXMLParsingFile, int nXMLParsingLine ) + : m_eErrorClass( HELPPROCESSING_XMLPARSING_ERROR ) + , m_aErrorMsg( aErrorMsg ) + , m_aXMLParsingFile( aXMLParsingFile ) + , m_nXMLParsingLine( nXMLParsingLine ) + {} +}; + +class HelpCompiler +{ +public: + HelpCompiler(StreamTable &streamTable, + const fs::path &in_inputFile, + const fs::path &in_src, + const fs::path &in_resEmbStylesheet, + const std::string &in_module, + const std::string &in_lang, + bool in_bExtensionMode); + bool compile( void ) throw (HelpProcessingException); + void addEntryToJarFile(const std::string &prefix, + const std::string &entryName, const std::string &bytesToAdd); + void addEntryToJarFile(const std::string &prefix, + const std::string &entryName, const HashSet &bytesToAdd); + void addEntryToJarFile(const std::string &prefix, + const std::string &entryName, const Stringtable &bytesToAdd); + void addEntryToJarFile(const std::string &prefix, + const std::string &entryName, const Hashtable &bytesToAdd); +private: + xmlDocPtr getSourceDocument(const fs::path &filePath); + HashSet switchFind(xmlDocPtr doc); + xmlNodePtr clone(xmlNodePtr node, const std::string& appl); + StreamTable &streamTable; + const fs::path inputFile, src; + const std::string module, lang; + const fs::path resEmbStylesheet; + bool bExtensionMode; +}; + +#endif + +/* vi:set tabstop=4 shiftwidth=4 expandtab: */ diff --git a/l10ntools/source/help/HelpFileDocument.java b/l10ntools/source/help/HelpFileDocument.java new file mode 100644 index 000000000000..2212db27f251 --- /dev/null +++ b/l10ntools/source/help/HelpFileDocument.java @@ -0,0 +1,89 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: HelpFileDocument.java,v $ + * $Revision: 1.2 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.help; + +import java.io.File; +import java.io.Reader; +import java.io.FileInputStream; +import java.io.InputStreamReader; +//import java.io.FileReader; +import java.io.StringReader; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; + +/** Lucene Document for help files */ +public class HelpFileDocument +{ + /** Creates reader for UTF-8 files + */ + private static Reader getReaderForFile( File aFile ) + throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException { + Reader aReader; + if( aFile != null ) { + FileInputStream fis = new FileInputStream( aFile ); + aReader = new InputStreamReader( fis, "UTF-8" ); + } + else { + aReader = new StringReader( "" ); + } + return aReader; + } + + /** Makes a document for a File. + */ + public static Document Document( String aModule, File aCaptionFile, File aContentFile ) + throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException { + Document doc = new Document(); + + // Add the path of the file as a field named "path". Use a field that is + // indexed (i.e. searchable), but don't tokenize the field into words. + File aFile = aCaptionFile != null ? aCaptionFile : aContentFile; + if( aFile != null ) + { + String aPath = "#HLP#" + aModule + "/" + aFile.getName(); + doc.add(new Field("path", aPath, Field.Store.YES, Field.Index.UN_TOKENIZED)); + } + + // Add the caption of the file to a field named "caption". Specify a Reader, + // so that the text of the file is tokenized and indexed, but not stored. + doc.add( new Field( "caption", getReaderForFile( aCaptionFile ) ) ); + + // Add the contents of the file to a field named "content". Specify a Reader, + // so that the text of the file is tokenized and indexed, but not stored. + doc.add( new Field( "content", getReaderForFile( aContentFile ) ) ); + + // return the document + return doc; + } + + private HelpFileDocument() {} +} diff --git a/l10ntools/source/help/HelpIndexerTool.java b/l10ntools/source/help/HelpIndexerTool.java new file mode 100644 index 000000000000..6bf22d1ac344 --- /dev/null +++ b/l10ntools/source/help/HelpIndexerTool.java @@ -0,0 +1,372 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: HelpIndexer.java,v $ + * $Revision: 1.21 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.help; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import java.util.zip.CRC32; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.analysis.cjk.CJKAnalyzer; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.index.IndexWriter; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Date; + +public class HelpIndexerTool +{ + public HelpIndexerTool() + { + } + + + /** + * @param args the command line arguments + */ + public static void main( String[] args ) + { + boolean bExtensionMode = false; + mainImpl( args, bExtensionMode ); + } + + public static void mainImpl( String[] args, boolean bExtensionMode ) + { + String aDirToZipStr = ""; + String aSrcDirStr = ""; + String aLanguageStr = ""; + String aModule = ""; + String aTargetZipFileStr = ""; + String aCfsName = ""; + + // Scan arguments + boolean bLang = false; + boolean bMod = false; + boolean bZipDir = false; + boolean bSrcDir = false; + boolean bOutput = false; + boolean bCfsName = false; + + int nArgCount = args.length; + for( int i = 0 ; i < nArgCount ; i++ ) + { + if( "-lang".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aLanguageStr = args[i + 1]; + bLang = true; + } + i++; + } + else if( "-mod".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aModule = args[i + 1]; + bMod = true; + } + i++; + } + else if( "-zipdir".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aDirToZipStr = args[i + 1]; + bZipDir = true; + } + i++; + } + else if( "-srcdir".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aSrcDirStr = args[i + 1]; + bSrcDir = true; + } + i++; + } + else if( "-o".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aTargetZipFileStr = args[i + 1]; + bOutput = true; + } + i++; + } + else if( "-checkcfsname".equals(args[i]) ) + { + if( i + 1 < nArgCount ) + { + aCfsName = args[i + 1] + ".cfs"; + bCfsName = true; + } + i++; + } + } + + if( !bLang || !bMod || !bZipDir || (!bOutput && !bExtensionMode) ) + { + if( bExtensionMode ) + return; + + System.out.println("Usage: HelpIndexer -lang ISOLangCode -mod HelpModule -zipdir TempZipDir -o OutputZipFile"); + System.exit( -1 ); + } + + String aIndexDirName = aModule + ".idxl"; + File aIndexDir = new File( aDirToZipStr + File.separator + aIndexDirName ); + if( !bSrcDir ) + aSrcDirStr = aDirToZipStr; + File aCaptionFilesDir = new File( aSrcDirStr + File.separator + "caption" ); + File aContentFilesDir = new File( aSrcDirStr + File.separator + "content" ); + + try + { + Date start = new Date(); + Analyzer analyzer = aLanguageStr.equals("ja") ? (Analyzer)new CJKAnalyzer() : (Analyzer)new StandardAnalyzer(); + IndexWriter writer = new IndexWriter( aIndexDir, analyzer, true ); + if( !bExtensionMode ) + System.out.println( "Lucene: Indexing to directory '" + aIndexDir + "'..." ); + int nRet = indexDocs( writer, aModule, bExtensionMode, aCaptionFilesDir, aContentFilesDir ); + if( nRet != -1 ) + { + if( !bExtensionMode ) + { + System.out.println(); + System.out.println( "Optimizing ..." ); + } + writer.optimize(); + } + writer.close(); + + boolean bCfsFileOk = true; + if( bCfsName && !bExtensionMode && nRet != -1 ) + { + String aCompleteCfsFileName = aDirToZipStr + File.separator + aIndexDirName + File.separator + aCfsName; + File aCfsFile = new File( aCompleteCfsFileName ); + bCfsFileOk = aCfsFile.exists(); + System.out.println( "Checking cfs file " + aCfsName+ ": " + (bCfsFileOk ? "Found" : "Not found") ); + } + + if( bExtensionMode ) + { + if( !bSrcDir ) + { + deleteRecursively( aCaptionFilesDir ); + deleteRecursively( aContentFilesDir ); + } + } + else + { + if( nRet == -1 ) + deleteRecursively( aIndexDir ); + + if( bCfsFileOk ) + System.out.println( "Zipping ..." ); + File aDirToZipFile = new File( aDirToZipStr ); + createZipFile( aDirToZipFile, aTargetZipFileStr ); + deleteRecursively( aDirToZipFile ); + } + + if( !bCfsFileOk ) + { + System.out.println( "cfs file check failed, terminating..." ); + System.exit( -1 ); + } + + Date end = new Date(); + if( !bExtensionMode ) + System.out.println(end.getTime() - start.getTime() + " total milliseconds"); + } + catch (IOException e) + { + if( bExtensionMode ) + return; + + System.out.println(" caught a " + e.getClass() + + "\n with message: " + e.getMessage()); + System.exit( -1 ); + } + } + + private static int indexDocs(IndexWriter writer, String aModule, boolean bExtensionMode, + File aCaptionFilesDir, File aContentFilesDir) throws IOException + { + if( !aCaptionFilesDir.canRead() || !aCaptionFilesDir.isDirectory() ) + { + if( !bExtensionMode ) + System.out.println( "Not found: " + aCaptionFilesDir ); + return -1; + } + if( !aContentFilesDir.canRead() || !aContentFilesDir.isDirectory() ) + { + if( !bExtensionMode ) + System.out.println( "Not found: " + aContentFilesDir ); + return -1; + } + + String[] aCaptionFiles = aCaptionFilesDir.list(); + List aCaptionFilesList = Arrays.asList( aCaptionFiles ); + HashSet aCaptionFilesHashSet = new HashSet( aCaptionFilesList ); + + String[] aContentFiles = aContentFilesDir.list(); + List aContentFilesList = Arrays.asList( aContentFiles ); + HashSet aContentFilesHashSet = new HashSet( aContentFilesList ); + + // Loop over caption files and find corresponding content file + if( !bExtensionMode ) + System.out.println( "Indexing, adding files" ); + int nCaptionFilesLen = aCaptionFiles.length; + for( int i = 0 ; i < nCaptionFilesLen ; i++ ) + { + String aCaptionFileStr = aCaptionFiles[i]; + File aCaptionFile = new File( aCaptionFilesDir, aCaptionFileStr ); + File aContentFile = null; + if( aContentFilesHashSet.contains( aCaptionFileStr ) ) + aContentFile = new File( aContentFilesDir, aCaptionFileStr ); + + if( !bExtensionMode ) + System.out.print( "." ); + writer.addDocument( HelpFileDocument.Document( aModule, aCaptionFile, aContentFile ) ); + } + + // Loop over content files to find remaining files not mapped to caption files + int nContentFilesLen = aContentFiles.length; + for( int i = 0 ; i < nContentFilesLen ; i++ ) + { + String aContentFileStr = aContentFiles[i]; + if( !aCaptionFilesHashSet.contains( aContentFileStr ) ) + { + // Not already handled in caption files loop + File aCaptionFile = null; + File aContentFile = new File( aContentFilesDir, aContentFileStr ); + if( !bExtensionMode ) + System.out.print( "." ); + writer.addDocument( HelpFileDocument.Document( aModule, aCaptionFile, aContentFile ) ); + } + } + return 0; + } + + public static void createZipFile( File aDirToZip, String aTargetZipFileStr ) + throws FileNotFoundException, IOException + { + FileOutputStream fos = new FileOutputStream( aTargetZipFileStr ); + ZipOutputStream zos = new ZipOutputStream( fos ); + + File[] aChildrenFiles = aDirToZip.listFiles(); + int nFileCount = aChildrenFiles.length; + for( int i = 0 ; i < nFileCount ; i++ ) + addToZipRecursively( zos, aChildrenFiles[i], null ); + + zos.close(); + } + + public static void addToZipRecursively( ZipOutputStream zos, File aFile, String aBasePath ) + throws FileNotFoundException, IOException + { + if( aFile.isDirectory() ) + { + String aDirName = aFile.getName(); + if( aDirName.equalsIgnoreCase( "caption" ) || aDirName.equalsIgnoreCase( "content" ) ) + return; + + File[] aChildrenFiles = aFile.listFiles(); + String aNewBasePath = ""; + if( aBasePath != null ) + aNewBasePath += aBasePath + File.separator; + aNewBasePath += aDirName; + + int nFileCount = aChildrenFiles.length; + for( int i = 0 ; i < nFileCount ; i++ ) + addToZipRecursively( zos, aChildrenFiles[i], aNewBasePath ); + + return; + } + + // No directory + // read contents of file we are going to put in the zip + int fileLength = (int) aFile.length(); + FileInputStream fis = new FileInputStream( aFile ); + byte[] wholeFile = new byte[fileLength]; + int bytesRead = fis.read( wholeFile, 0, fileLength ); + fis.close(); + + String aFileName = aFile.getName(); + String aEntryName = ""; + if( aBasePath != null ) + aEntryName += aBasePath + "/"; + aEntryName += aFileName; + ZipEntry aZipEntry = new ZipEntry( aEntryName ); + aZipEntry.setTime( aFile.lastModified() ); + aZipEntry.setSize( fileLength ); + + int nMethod = ( aFileName.toLowerCase().endsWith( ".jar" ) ) + ? ZipEntry.STORED : ZipEntry.DEFLATED; + aZipEntry.setMethod( nMethod ); + + CRC32 tempCRC = new CRC32(); + tempCRC.update( wholeFile, 0, wholeFile.length ); + aZipEntry.setCrc( tempCRC.getValue() ); + + // write the contents into the zip element + zos.putNextEntry( aZipEntry ); + zos.write( wholeFile, 0, fileLength ); + zos.closeEntry(); + } + + static public boolean deleteRecursively( File aFile ) + { + if( aFile.isDirectory() ) + { + File[] aChildrenFiles = aFile.listFiles(); + int nFileCount = aChildrenFiles.length; + for( int i = 0 ; i < nFileCount ; i++ ) + { + File aChildrenFile = aChildrenFiles[i]; + boolean bSuccess = deleteRecursively( aChildrenFile ); + if( !bSuccess ) + return false; + } + } + + return aFile.delete(); + } +} + diff --git a/l10ntools/source/help/HelpLinker.cxx b/l10ntools/source/help/HelpLinker.cxx new file mode 100644 index 000000000000..7dfe4ee4a2a2 --- /dev/null +++ b/l10ntools/source/help/HelpLinker.cxx @@ -0,0 +1,1173 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: HelpLinker.cxx,v $ + * $Revision: 1.16 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#include "HelpCompiler.hxx" + +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#define DBHELP_ONLY + + +class IndexerPreProcessor +{ +private: + std::string m_aModuleName; + fs::path m_fsIndexBaseDir; + fs::path m_fsCaptionFilesDirName; + fs::path m_fsContentFilesDirName; + + xsltStylesheetPtr m_xsltStylesheetPtrCaption; + xsltStylesheetPtr m_xsltStylesheetPtrContent; + +public: + IndexerPreProcessor( const std::string& aModuleName, const fs::path& fsIndexBaseDir, + const fs::path& idxCaptionStylesheet, const fs::path& idxContentStylesheet ); + ~IndexerPreProcessor(); + + void processDocument( xmlDocPtr doc, const std::string& EncodedDocPath ); +}; + +IndexerPreProcessor::IndexerPreProcessor + ( const std::string& aModuleName, const fs::path& fsIndexBaseDir, + const fs::path& idxCaptionStylesheet, const fs::path& idxContentStylesheet ) + : m_aModuleName( aModuleName ) + , m_fsIndexBaseDir( fsIndexBaseDir ) +{ + m_fsCaptionFilesDirName = fsIndexBaseDir / "caption"; + fs::create_directory( m_fsCaptionFilesDirName ); + + m_fsContentFilesDirName = fsIndexBaseDir / "content"; + fs::create_directory( m_fsContentFilesDirName ); + + m_xsltStylesheetPtrCaption = xsltParseStylesheetFile + ((const xmlChar *)idxCaptionStylesheet.native_file_string().c_str()); + m_xsltStylesheetPtrContent = xsltParseStylesheetFile + ((const xmlChar *)idxContentStylesheet.native_file_string().c_str()); +} + +IndexerPreProcessor::~IndexerPreProcessor() +{ + if( m_xsltStylesheetPtrCaption ) + xsltFreeStylesheet( m_xsltStylesheetPtrCaption ); + if( m_xsltStylesheetPtrContent ) + xsltFreeStylesheet( m_xsltStylesheetPtrContent ); +} + + +std::string getEncodedPath( const std::string& Path ) +{ + rtl::OString aOStr_Path( Path.c_str() ); + rtl::OUString aOUStr_Path( rtl::OStringToOUString + ( aOStr_Path, fs::getThreadTextEncoding() ) ); + rtl::OUString aPathURL; + osl::File::getFileURLFromSystemPath( aOUStr_Path, aPathURL ); + rtl::OString aOStr_PathURL( rtl::OUStringToOString + ( aPathURL, fs::getThreadTextEncoding() ) ); + std::string aStdStr_PathURL( aOStr_PathURL.getStr() ); + return aStdStr_PathURL; +} + +void IndexerPreProcessor::processDocument + ( xmlDocPtr doc, const std::string &EncodedDocPath ) +{ + std::string aStdStr_EncodedDocPathURL = getEncodedPath( EncodedDocPath ); + + if( m_xsltStylesheetPtrCaption ) + { + xmlDocPtr resCaption = xsltApplyStylesheet( m_xsltStylesheetPtrCaption, doc, NULL ); + xmlNodePtr pResNodeCaption = resCaption->xmlChildrenNode; + if( pResNodeCaption ) + { + fs::path fsCaptionPureTextFile_docURL = m_fsCaptionFilesDirName / aStdStr_EncodedDocPathURL; + std::string aCaptionPureTextFileStr_docURL = fsCaptionPureTextFile_docURL.native_file_string(); + FILE* pFile_docURL = fopen( aCaptionPureTextFileStr_docURL.c_str(), "w" ); + if( pFile_docURL ) + { + fprintf( pFile_docURL, "%s\n", pResNodeCaption->content ); + fclose( pFile_docURL ); + } + } + xmlFreeDoc(resCaption); + } + + if( m_xsltStylesheetPtrContent ) + { + xmlDocPtr resContent = xsltApplyStylesheet( m_xsltStylesheetPtrContent, doc, NULL ); + xmlNodePtr pResNodeContent = resContent->xmlChildrenNode; + if( pResNodeContent ) + { + fs::path fsContentPureTextFile_docURL = m_fsContentFilesDirName / aStdStr_EncodedDocPathURL; + std::string aContentPureTextFileStr_docURL = fsContentPureTextFile_docURL.native_file_string(); + FILE* pFile_docURL = fopen( aContentPureTextFileStr_docURL.c_str(), "w" ); + if( pFile_docURL ) + { + fprintf( pFile_docURL, "%s\n", pResNodeContent->content ); + fclose( pFile_docURL ); + } + } + xmlFreeDoc(resContent); + } +} + +struct Data +{ + std::vector _idList; + typedef std::vector::const_iterator cIter; + + void append(const std::string &id) + { + _idList.push_back(id); + } + + std::string getString() const + { + std::string ret; + cIter aEnd = _idList.end(); + for (cIter aIter = _idList.begin(); aIter != aEnd; ++aIter) + ret += *aIter + ";"; + return ret; + } +}; + +void writeKeyValue_DBHelp( FILE* pFile, const std::string& aKeyStr, const std::string& aValueStr ) +{ + if( pFile == NULL ) + return; + char cLF = 10; + unsigned int nKeyLen = aKeyStr.length(); + unsigned int nValueLen = aValueStr.length(); + fprintf( pFile, "%x ", nKeyLen ); + if( nKeyLen > 0 ) + { + if (fwrite( aKeyStr.c_str(), 1, nKeyLen, pFile ) != nKeyLen) + fprintf(stderr, "fwrite to db failed\n"); + } + if (fprintf( pFile, " %x ", nValueLen ) < 0) + fprintf(stderr, "fwrite to db failed\n"); + if( nValueLen > 0 ) + { + if (fwrite( aValueStr.c_str(), 1, nValueLen, pFile ) != nValueLen) + fprintf(stderr, "fwrite to db failed\n"); + } + if (fprintf( pFile, "%c", cLF ) < 0) + fprintf(stderr, "fwrite to db failed\n"); +} + +class HelpKeyword +{ +private: + typedef std::hash_map DataHashtable; + DataHashtable _hash; + +public: + void insert(const std::string &key, const std::string &id) + { + Data &data = _hash[key]; + data.append(id); + } + + void dump(DB* table) + { + DataHashtable::const_iterator aEnd = _hash.end(); + for (DataHashtable::const_iterator aIter = _hash.begin(); aIter != aEnd; ++aIter) + { + const std::string &keystr = aIter->first; + DBT key; + memset(&key, 0, sizeof(key)); + key.data = const_cast(keystr.c_str()); + key.size = keystr.length(); + + const Data &data = aIter->second; + std::string str = data.getString(); + DBT value; + memset(&value, 0, sizeof(value)); + value.data = const_cast(str.c_str()); + value.size = str.length(); + + table->put(table, NULL, &key, &value, 0); + } + } + + void dump_DBHelp( const std::string& rFileName ) + { + FILE* pFile = fopen( rFileName.c_str(), "wb" ); + if( pFile == NULL ) + return; + + DataHashtable::const_iterator aEnd = _hash.end(); + for (DataHashtable::const_iterator aIter = _hash.begin(); aIter != aEnd; ++aIter) + writeKeyValue_DBHelp( pFile, aIter->first, aIter->second.getString() ); + + fclose( pFile ); + } +}; + +class HelpLinker +{ +public: + void main(std::vector &args, + std::string* pExtensionPath = NULL, const rtl::OUString* pOfficeHelpPath = NULL ) + throw( HelpProcessingException ); + + HelpLinker() + : init(true) + , m_pIndexerPreProcessor(NULL) + {} + ~HelpLinker() + { delete m_pIndexerPreProcessor; } + +private: + int locCount, totCount; + Stringtable additionalFiles; + HashSet helpFiles; + fs::path sourceRoot; + fs::path embeddStylesheet; + fs::path idxCaptionStylesheet; + fs::path idxContentStylesheet; + fs::path zipdir; + fs::path outputFile; + std::string module; + std::string lang; + std::string hid; + std::string extensionPath; + bool bExtensionMode; + fs::path indexDirName; + Stringtable hidlistTranslation; + fs::path indexDirParentName; + bool init; + IndexerPreProcessor* m_pIndexerPreProcessor; + void initIndexerPreProcessor(); + void link() throw( HelpProcessingException ); + void addBookmark( DB* dbBase, FILE* pFile_DBHelp, std::string thishid, + const std::string& fileB, const std::string& anchorB, + const std::string& jarfileB, const std::string& titleB ); +#if 0 + /** + * @param outputFile + * @param module + * @param lang + * @param hid + * @param helpFiles + * @param additionalFiles + */ + + private HelpURLStreamHandlerFactory urlHandler = null; +#endif +}; + +namespace URLEncoder +{ + static std::string encode(const std::string &rIn) + { + const char *good = "!$&'()*+,-.=@_"; + static const char hex[17] = "0123456789ABCDEF"; + + std::string result; + for (size_t i=0; i < rIn.length(); ++i) + { + unsigned char c = rIn[i]; + if (isalnum (c) || strchr (good, c)) + result += c; + else { + result += '%'; + result += hex[c >> 4]; + result += hex[c & 0xf]; + } + } + return result; + } +} + +void HelpLinker::addBookmark( DB* dbBase, FILE* pFile_DBHelp, std::string thishid, + const std::string& fileB, const std::string& anchorB, + const std::string& jarfileB, const std::string& titleB) +{ + HCDBG(std::cerr << "HelpLinker::addBookmark " << thishid << " " << + fileB << " " << anchorB << " " << jarfileB << " " << titleB << std::endl); + + std::string temp = thishid; + std::transform (temp.begin(), temp.end(), temp.begin(), toupper); + std::replace(temp.begin(), temp.end(), ':', '_'); + const std::string& translatedHid = hidlistTranslation[temp]; + if (!translatedHid.empty()) + thishid = translatedHid; + + thishid = URLEncoder::encode(thishid); + + DBT key; + memset(&key, 0, sizeof(key)); + key.data = const_cast(thishid.c_str()); + key.size = thishid.length(); + + int fileLen = fileB.length(); + if (!anchorB.empty()) + fileLen += (1 + anchorB.length()); + int dataLen = 1 + fileLen + 1 + jarfileB.length() + 1 + titleB.length(); + + std::vector dataB(dataLen); + size_t i = 0; + dataB[i++] = static_cast(fileLen); + for (size_t j = 0; j < fileB.length(); ++j) + dataB[i++] = fileB[j]; + if (!anchorB.empty()) + { + dataB[i++] = '#'; + for (size_t j = 0; j < anchorB.length(); ++j) + dataB[i++] = anchorB[j]; + } + dataB[i++] = static_cast(jarfileB.length()); + for (size_t j = 0; j < jarfileB.length(); ++j) + dataB[i++] = jarfileB[j]; + + dataB[i++] = static_cast(titleB.length()); + for (size_t j = 0; j < titleB.length(); ++j) + dataB[i++] = titleB[j]; + + DBT data; + memset(&data, 0, sizeof(data)); + data.data = &dataB[0]; + data.size = dataB.size(); + + if( dbBase != NULL ) + dbBase->put(dbBase, NULL, &key, &data, 0); + + if( pFile_DBHelp != NULL ) + { + std::string aValueStr( dataB.begin(), dataB.end() ); + writeKeyValue_DBHelp( pFile_DBHelp, thishid, aValueStr ); + } +} + +void HelpLinker::initIndexerPreProcessor() +{ + if( m_pIndexerPreProcessor ) + delete m_pIndexerPreProcessor; + std::string mod = module; + std::transform (mod.begin(), mod.end(), mod.begin(), tolower); + m_pIndexerPreProcessor = new IndexerPreProcessor( mod, indexDirParentName, + idxCaptionStylesheet, idxContentStylesheet ); +} + +/** +* +*/ +void HelpLinker::link() throw( HelpProcessingException ) +{ + bool bIndexForExtension = true; + + if( bExtensionMode ) + { + indexDirParentName = sourceRoot; + } + else + { + indexDirParentName = zipdir; + fs::create_directory(indexDirParentName); + } + +#ifdef CMC_DEBUG + std::cerr << "will not delete tmpdir of " << indexDirParentName.native_file_string().c_str() << std::endl; +#endif + + std::string mod = module; + std::transform (mod.begin(), mod.end(), mod.begin(), tolower); + + // do the work here + // continue with introduction of the overall process thing into the + // here all hzip files will be worked on + std::string appl = mod; + if (appl[0] == 's') + appl = appl.substr(1); + + bool bUse_ = true; +#ifdef DBHELP_ONLY + if( !bExtensionMode ) + bUse_ = false; +#endif + + DB* helpText(0); +#ifndef DBHELP_ONLY + fs::path helpTextFileName(indexDirParentName / (mod + ".ht")); + db_create(&helpText,0,0); + helpText->open(helpText, NULL, helpTextFileName.native_file_string().c_str(), NULL, DB_BTREE, + DB_CREATE | DB_TRUNCATE, 0644); +#endif + + fs::path helpTextFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".ht_" : ".ht"))); + FILE* pFileHelpText_DBHelp = fopen + ( helpTextFileName_DBHelp.native_file_string().c_str(), "wb" ); + + DB* dbBase(0); +#ifndef DBHELP_ONLY + fs::path dbBaseFileName(indexDirParentName / (mod + ".db")); + db_create(&dbBase,0,0); + dbBase->open(dbBase, NULL, dbBaseFileName.native_file_string().c_str(), NULL, DB_BTREE, + DB_CREATE | DB_TRUNCATE, 0644); +#endif + + fs::path dbBaseFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".db_" : ".db"))); + FILE* pFileDbBase_DBHelp = fopen + ( dbBaseFileName_DBHelp.native_file_string().c_str(), "wb" ); + +#ifndef DBHELP_ONLY + DB* keyWord(0); + fs::path keyWordFileName(indexDirParentName / (mod + ".key")); + db_create(&keyWord,0,0); + keyWord->open(keyWord, NULL, keyWordFileName.native_file_string().c_str(), NULL, DB_BTREE, + DB_CREATE | DB_TRUNCATE, 0644); +#endif + + fs::path keyWordFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".key_" : ".key"))); + + HelpKeyword helpKeyword; + + // catch HelpProcessingException to avoid locking data bases + try + { + + std::ifstream fileReader(hid.c_str()); + while (fileReader) + { + std::string key; + fileReader >> key; + std::transform (key.begin(), key.end(), key.begin(), toupper); + std::replace(key.begin(), key.end(), ':', '_'); + std::string data; + fileReader >> data; + if (!key.empty() && !data.empty()) + hidlistTranslation[key] = data; + } + fileReader.close(); + + // lastly, initialize the indexBuilder + if ( (!bExtensionMode || bIndexForExtension) && !helpFiles.empty()) + initIndexerPreProcessor(); + + if( !bExtensionMode ) + { +#ifndef OS2 // YD @TODO@ crashes libc runtime :-( + std::cout << "Making " << outputFile.native_file_string() << + " from " << helpFiles.size() << " input files" << std::endl; +#endif + } + + // here we start our loop over the hzip files. + HashSet::iterator end = helpFiles.end(); + for (HashSet::iterator iter = helpFiles.begin(); iter != end; ++iter) + { + if( !bExtensionMode ) + { + std::cout << "."; + std::cout.flush(); + } + + // process one file + // streamTable contains the streams in the hzip file + StreamTable streamTable; + const std::string &xhpFileName = *iter; + + if (!bExtensionMode && xhpFileName.rfind(".xhp") != xhpFileName.length()-4) + { + // only work on .xhp - files + std::cerr << + "ERROR: input list entry '" + << xhpFileName + << "' has the wrong extension (only files with extension .xhp " + << "are accepted)"; + continue; + } + + fs::path langsourceRoot(sourceRoot); + fs::path xhpFile; + + if( bExtensionMode ) + { + // langsourceRoot == sourceRoot for extensions + std::string xhpFileNameComplete( extensionPath ); + xhpFileNameComplete.append( '/' + xhpFileName ); + xhpFile = fs::path( xhpFileNameComplete ); + } + else + { + langsourceRoot.append('/' + lang + '/'); + xhpFile = fs::path(xhpFileName, fs::native); + } + + HelpCompiler hc( streamTable, xhpFile, langsourceRoot, + embeddStylesheet, module, lang, bExtensionMode ); + + HCDBG(std::cerr << "before compile of " << xhpFileName << std::endl); + bool success = hc.compile(); + HCDBG(std::cerr << "after compile of " << xhpFileName << std::endl); + + if (!success && !bExtensionMode) + { + std::stringstream aStrStream; + aStrStream << + "\nERROR: compiling help particle '" + << xhpFileName + << "' for language '" + << lang + << "' failed!"; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + const std::string documentBaseId = streamTable.document_id; + std::string documentPath = streamTable.document_path; + if (documentPath.find("/") == 0) + documentPath = documentPath.substr(1); + + std::string documentJarfile = streamTable.document_module + ".jar"; + + std::string documentTitle = streamTable.document_title; + if (documentTitle.empty()) + documentTitle = ""; + +#if 0 + std::cout << "for " << xhpFileName << " documentBaseId is " << documentBaseId << "\n"; + std::cout << "for " << xhpFileName << " documentPath is " << documentPath << "\n"; + std::cout << "for " << xhpFileName << " documentJarfile is " << documentJarfile << "\n"; + std::cout << "for " << xhpFileName << " documentPath is " << documentTitle << "\n"; +#endif + + const std::string& fileB = documentPath; + const std::string& jarfileB = documentJarfile; + std::string& titleB = documentTitle; + + // add once this as its own id. + addBookmark(dbBase, pFileDbBase_DBHelp, documentPath, fileB, std::string(), jarfileB, titleB); + + // first the database *.db + // ByteArrayInputStream bais = null; + // ObjectInputStream ois = null; + + const HashSet *hidlist = streamTable.appl_hidlist; + if (!hidlist) + hidlist = streamTable.default_hidlist; + if (hidlist && !hidlist->empty()) + { + // now iterate over all elements of the hidlist + HashSet::const_iterator aEnd = hidlist->end(); + for (HashSet::const_iterator hidListIter = hidlist->begin(); + hidListIter != aEnd; ++hidListIter) + { + std::string thishid = *hidListIter; + + std::string anchorB; + size_t index = thishid.rfind('#'); + if (index != std::string::npos) + { + anchorB = thishid.substr(1 + index); + thishid = thishid.substr(0, index); + } + addBookmark(dbBase, pFileDbBase_DBHelp, thishid, fileB, anchorB, jarfileB, titleB); + } + } + + // now the keywords + const Hashtable *anchorToLL = streamTable.appl_keywords; + if (!anchorToLL) + anchorToLL = streamTable.default_keywords; + if (anchorToLL && !anchorToLL->empty()) + { + std::string fakedHid = URLEncoder::encode(documentPath); + Hashtable::const_iterator aEnd = anchorToLL->end(); + for (Hashtable::const_iterator enumer = anchorToLL->begin(); + enumer != aEnd; ++enumer) + { + const std::string &anchor = enumer->first; + addBookmark(dbBase, pFileDbBase_DBHelp, documentPath, fileB, + anchor, jarfileB, titleB); + std::string totalId = fakedHid + "#" + anchor; + // std::cerr << hzipFileName << std::endl; + const LinkedList& ll = enumer->second; + LinkedList::const_iterator aOtherEnd = ll.end(); + for (LinkedList::const_iterator llIter = ll.begin(); + llIter != aOtherEnd; ++llIter) + { + helpKeyword.insert(*llIter, totalId); + } + } + + } + + // and last the helptexts + const Stringtable *helpTextHash = streamTable.appl_helptexts; + if (!helpTextHash) + helpTextHash = streamTable.default_helptexts; + if (helpTextHash && !helpTextHash->empty()) + { + Stringtable::const_iterator aEnd = helpTextHash->end(); + for (Stringtable::const_iterator helpTextIter = helpTextHash->begin(); + helpTextIter != aEnd; ++helpTextIter) + { + std::string helpTextId = helpTextIter->first; + const std::string& helpTextText = helpTextIter->second; + + std::string temp = helpTextId; + std::transform (temp.begin(), temp.end(), temp.begin(), toupper); + std::replace(temp.begin(), temp.end(), ':', '_'); + + const std::string& tHid = hidlistTranslation[temp]; + if (!tHid.empty()) + helpTextId = tHid; + helpTextId = URLEncoder::encode(helpTextId); + + DBT keyDbt; + memset(&keyDbt, 0, sizeof(keyDbt)); + keyDbt.data = const_cast(helpTextId.c_str()); + keyDbt.size = helpTextId.length(); + + DBT textDbt; + memset(&textDbt, 0, sizeof(textDbt)); + textDbt.data = const_cast(helpTextText.c_str()); + textDbt.size = helpTextText.length(); + + if( helpText != NULL ) + helpText->put(helpText, NULL, &keyDbt, &textDbt, 0); + + if( pFileHelpText_DBHelp != NULL ) + writeKeyValue_DBHelp( pFileHelpText_DBHelp, helpTextId, helpTextText ); + } + } + + //IndexerPreProcessor + if( !bExtensionMode || bIndexForExtension ) + { + // now the indexing + xmlDocPtr document = streamTable.appl_doc; + if (!document) + document = streamTable.default_doc; + if (document) + { + std::string temp = module; + std::transform (temp.begin(), temp.end(), temp.begin(), tolower); + m_pIndexerPreProcessor->processDocument(document, URLEncoder::encode(documentPath) ); + } + } + + } // while loop over hzip files ending + if( !bExtensionMode ) + std::cout << std::endl; + + } // try + catch( HelpProcessingException& ) + { + // catch HelpProcessingException to avoid locking data bases +#ifndef DBHELP_ONLY + helpText->close(helpText, 0); + dbBase->close(dbBase, 0); + keyWord->close(keyWord, 0); +#endif + if( pFileHelpText_DBHelp != NULL ) + fclose( pFileHelpText_DBHelp ); + if( pFileDbBase_DBHelp != NULL ) + fclose( pFileDbBase_DBHelp ); + throw; + } + +#ifndef DBHELP_ONLY + helpText->close(helpText, 0); + dbBase->close(dbBase, 0); + helpKeyword.dump(keyWord); + keyWord->close(keyWord, 0); +#endif + if( pFileHelpText_DBHelp != NULL ) + fclose( pFileHelpText_DBHelp ); + if( pFileDbBase_DBHelp != NULL ) + fclose( pFileDbBase_DBHelp ); + + helpKeyword.dump_DBHelp( keyWordFileName_DBHelp.native_file_string() ); + + if( !bExtensionMode ) + { + // New index + Stringtable::iterator aEnd = additionalFiles.end(); + for (Stringtable::iterator enumer = additionalFiles.begin(); enumer != aEnd; + ++enumer) + { + const std::string &additionalFileName = enumer->second; + const std::string &additionalFileKey = enumer->first; + + fs::path fsAdditionalFileName( additionalFileName, fs::native ); + std::string aNativeStr = fsAdditionalFileName.native_file_string(); + const char* pStr = aNativeStr.c_str(); + std::cerr << pStr; + + fs::path fsTargetName( indexDirParentName / additionalFileKey ); + + fs::copy( fsAdditionalFileName, fsTargetName ); + } + } + +/* + ///////////////////////////////////////////////////////////////////////// + /// remove temprary directory for index creation + ///////////////////////////////////////////////////////////////////////// +#ifndef CMC_DEBUG + if( !bExtensionMode ) + fs::remove_all( indexDirParentName ); +#endif +*/ +} + + +void HelpLinker::main( std::vector &args, + std::string* pExtensionPath, const rtl::OUString* pOfficeHelpPath ) + throw( HelpProcessingException ) +{ + rtl::OUString aOfficeHelpPath; + + bExtensionMode = false; + if( pExtensionPath && pExtensionPath->length() > 0 && pOfficeHelpPath ) + { + helpFiles.clear(); + bExtensionMode = true; + extensionPath = *pExtensionPath; + sourceRoot = fs::path(extensionPath); + + aOfficeHelpPath = *pOfficeHelpPath; + } + if (args.size() > 0 && args[0][0] == '@') + { + std::vector stringList; + std::string strBuf; + std::ifstream fileReader(args[0].substr(1).c_str()); + + while (fileReader) + { + std::string token; + fileReader >> token; + if (!token.empty()) + stringList.push_back(token); + } + fileReader.close(); + + args = stringList; + } + + size_t i = 0; + + while (i < args.size()) + { + if (args[i].compare("-src") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "sourceroot missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + if( !bExtensionMode ) + sourceRoot = fs::path(args[i], fs::native); + } + else if (args[i].compare("-sty") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "embeddingStylesheet missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + embeddStylesheet = fs::path(args[i], fs::native); + } + else if (args[i].compare("-zipdir") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "idxtemp missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + zipdir = fs::path(args[i], fs::native); + } + else if (args[i].compare("-idxcaption") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "idxcaption stylesheet missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + idxCaptionStylesheet = fs::path(args[i], fs::native); + } + else if (args[i].compare("-idxcontent") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "idxcontent stylesheet missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + idxContentStylesheet = fs::path(args[i], fs::native); + } + else if (args[i].compare("-o") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "outputfilename missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + outputFile = fs::path(args[i], fs::native); + } + else if (args[i].compare("-mod") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "module name missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + module = args[i]; + } + else if (args[i].compare("-lang") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "language name missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + lang = args[i]; + } + else if (args[i].compare("-hid") == 0) + { + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "hid list missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + hid = args[i]; + } + else if (args[i].compare("-add") == 0) + { + std::string addFile, addFileUnderPath; + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "pathname missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + addFileUnderPath = args[i]; + ++i; + if (i >= args.size()) + { + std::stringstream aStrStream; + aStrStream << "pathname missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + addFile = args[i]; + if (!addFileUnderPath.empty() && !addFile.empty()) + additionalFiles[addFileUnderPath] = addFile; + } + else + helpFiles.push_back(args[i]); + ++i; + } + + if (!bExtensionMode && zipdir.empty()) + { + std::stringstream aStrStream; + aStrStream << "no index dir given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (!bExtensionMode && idxCaptionStylesheet.empty()) + { + std::stringstream aStrStream; + aStrStream << "no index caption stylesheet given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + else if ( bExtensionMode ) + { + rtl::OUString aIdxCaptionPathFileURL( aOfficeHelpPath ); + aIdxCaptionPathFileURL += rtl::OUString::createFromAscii( "/idxcaption.xsl" ); + + rtl::OString aOStr_IdxCaptionPathFileURL( rtl::OUStringToOString + ( aIdxCaptionPathFileURL, fs::getThreadTextEncoding() ) ); + std::string aStdStr_IdxCaptionPathFileURL( aOStr_IdxCaptionPathFileURL.getStr() ); + + idxCaptionStylesheet = fs::path( aStdStr_IdxCaptionPathFileURL ); + } + if (!bExtensionMode && idxContentStylesheet.empty()) + { + std::stringstream aStrStream; + aStrStream << "no index content stylesheet given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + else if ( bExtensionMode ) + { + rtl::OUString aIdxContentPathFileURL( aOfficeHelpPath ); + aIdxContentPathFileURL += rtl::OUString::createFromAscii( "/idxcontent.xsl" ); + + rtl::OString aOStr_IdxContentPathFileURL( rtl::OUStringToOString + ( aIdxContentPathFileURL, fs::getThreadTextEncoding() ) ); + std::string aStdStr_IdxContentPathFileURL( aOStr_IdxContentPathFileURL.getStr() ); + + idxContentStylesheet = fs::path( aStdStr_IdxContentPathFileURL ); + } + if (!bExtensionMode && embeddStylesheet.empty()) + { + std::stringstream aStrStream; + aStrStream << "no embedding resolving file given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (sourceRoot.empty()) + { + std::stringstream aStrStream; + aStrStream << "no sourceroot given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (!bExtensionMode && outputFile.empty()) + { + std::stringstream aStrStream; + aStrStream << "no output file given" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (module.empty()) + { + std::stringstream aStrStream; + aStrStream << "module missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (!bExtensionMode && lang.empty()) + { + std::stringstream aStrStream; + aStrStream << "language missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + if (!bExtensionMode && hid.empty()) + { + std::stringstream aStrStream; + aStrStream << "hid list missing" << std::endl; + throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); + } + + link(); +} + +int main(int argc, char**argv) +{ + sal_uInt32 starttime = osl_getGlobalTimer(); + std::vector args; + for (int i = 1; i < argc; ++i) + args.push_back(std::string(argv[i])); + try + { + HelpLinker* pHelpLinker = new HelpLinker(); + pHelpLinker->main( args ); + delete pHelpLinker; + } + catch( const HelpProcessingException& e ) + { + std::cerr << e.m_aErrorMsg; + exit(1); + } + sal_uInt32 endtime = osl_getGlobalTimer(); +#ifndef OS2 // YD @TODO@ crashes libc runtime :-( + std::cout << "time taken was " << (endtime-starttime)/1000.0 << " seconds" << std::endl; +#endif + return 0; +} + +// Variable to set an exception in "C" StructuredXMLErrorFunction +static const HelpProcessingException* GpXMLParsingException = NULL; + +extern "C" void StructuredXMLErrorFunction(void *userData, xmlErrorPtr error) +{ + (void)userData; + (void)error; + + std::string aErrorMsg = error->message; + std::string aXMLParsingFile; + if( error->file != NULL ) + aXMLParsingFile = error->file; + int nXMLParsingLine = error->line; + HelpProcessingException* pException = new HelpProcessingException( aErrorMsg, aXMLParsingFile, nXMLParsingLine ); + GpXMLParsingException = pException; + + // Reset error handler + xmlSetStructuredErrorFunc( NULL, NULL ); +} + +HelpProcessingErrorInfo& HelpProcessingErrorInfo::operator=( const struct HelpProcessingException& e ) +{ + m_eErrorClass = e.m_eErrorClass; + rtl::OString tmpErrorMsg( e.m_aErrorMsg.c_str() ); + m_aErrorMsg = rtl::OStringToOUString( tmpErrorMsg, fs::getThreadTextEncoding() ); + rtl::OString tmpXMLParsingFile( e.m_aXMLParsingFile.c_str() ); + m_aXMLParsingFile = rtl::OStringToOUString( tmpXMLParsingFile, fs::getThreadTextEncoding() ); + m_nXMLParsingLine = e.m_nXMLParsingLine; + return *this; +} + + +// Returns true in case of success, false in case of error +HELPLINKER_DLLPUBLIC bool compileExtensionHelp +( + const rtl::OUString& aOfficeHelpPath, + const rtl::OUString& aExtensionName, + const rtl::OUString& aExtensionLanguageRoot, + sal_Int32 nXhpFileCount, const rtl::OUString* pXhpFiles, + HelpProcessingErrorInfo& o_rHelpProcessingErrorInfo +) +{ + bool bSuccess = true; + + sal_Int32 argc = nXhpFileCount + 3; + const char** argv = new const char*[argc]; + argv[0] = ""; + argv[1] = "-mod"; + rtl::OString aOExtensionName = rtl::OUStringToOString( aExtensionName, fs::getThreadTextEncoding() ); + argv[2] = aOExtensionName.getStr(); + + for( sal_Int32 iXhp = 0 ; iXhp < nXhpFileCount ; ++iXhp ) + { + rtl::OUString aXhpFile = pXhpFiles[iXhp]; + + rtl::OString aOXhpFile = rtl::OUStringToOString( aXhpFile, fs::getThreadTextEncoding() ); + char* pArgStr = new char[aOXhpFile.getLength() + 1]; + strcpy( pArgStr, aOXhpFile.getStr() ); + argv[iXhp + 3] = pArgStr; + } + + std::vector args; + for( sal_Int32 i = 1; i < argc; ++i ) + args.push_back(std::string( argv[i]) ); + + for( sal_Int32 iXhp = 0 ; iXhp < nXhpFileCount ; ++iXhp ) + delete argv[iXhp + 3]; + delete[] argv; + + rtl::OString aOExtensionLanguageRoot = rtl::OUStringToOString( aExtensionLanguageRoot, fs::getThreadTextEncoding() ); + const char* pExtensionPath = aOExtensionLanguageRoot.getStr(); + std::string aStdStrExtensionPath = pExtensionPath; + + // Set error handler + xmlSetStructuredErrorFunc( NULL, (xmlStructuredErrorFunc)StructuredXMLErrorFunction ); + try + { + HelpLinker* pHelpLinker = new HelpLinker(); + pHelpLinker->main( args, &aStdStrExtensionPath, &aOfficeHelpPath ); + delete pHelpLinker; + } + catch( const HelpProcessingException& e ) + { + if( GpXMLParsingException != NULL ) + { + o_rHelpProcessingErrorInfo = *GpXMLParsingException; + delete GpXMLParsingException; + GpXMLParsingException = NULL; + } + else + { + o_rHelpProcessingErrorInfo = e; + } + bSuccess = false; + } + // Reset error handler + xmlSetStructuredErrorFunc( NULL, NULL ); + + // i83624: Tree files + ::rtl::OUString aTreeFileURL = aExtensionLanguageRoot; + aTreeFileURL += rtl::OUString::createFromAscii( "/help.tree" ); + osl::DirectoryItem aTreeFileItem; + osl::FileBase::RC rcGet = osl::DirectoryItem::get( aTreeFileURL, aTreeFileItem ); + osl::FileStatus aFileStatus( FileStatusMask_FileSize ); + if( rcGet == osl::FileBase::E_None && + aTreeFileItem.getFileStatus( aFileStatus ) == osl::FileBase::E_None && + aFileStatus.isValid( FileStatusMask_FileSize ) ) + { + sal_uInt64 ret, len = aFileStatus.getFileSize(); + char* s = new char[ int(len) ]; // the buffer to hold the installed files + osl::File aFile( aTreeFileURL ); + aFile.open( OpenFlag_Read ); + aFile.read( s, len, ret ); + aFile.close(); + + XML_Parser parser = XML_ParserCreate( 0 ); + int parsed = XML_Parse( parser, s, int( len ), true ); + + if( parsed == 0 ) + { + XML_Error nError = XML_GetErrorCode( parser ); + o_rHelpProcessingErrorInfo.m_eErrorClass = HELPPROCESSING_XMLPARSING_ERROR; + o_rHelpProcessingErrorInfo.m_aErrorMsg = rtl::OUString::createFromAscii( XML_ErrorString( nError ) );; + o_rHelpProcessingErrorInfo.m_aXMLParsingFile = aTreeFileURL; + // CRAHSES!!! o_rHelpProcessingErrorInfo.m_nXMLParsingLine = XML_GetCurrentLineNumber( parser ); + bSuccess = false; + } + + XML_ParserFree( parser ); + delete[] s; + } + + return bSuccess; +} + +// vnd.sun.star.help://swriter/52821?Language=en-US&System=UNIX +/* vi:set tabstop=4 shiftwidth=4 expandtab: */ + diff --git a/l10ntools/source/help/compilehelp.hxx b/l10ntools/source/help/compilehelp.hxx new file mode 100644 index 000000000000..d123d628be27 --- /dev/null +++ b/l10ntools/source/help/compilehelp.hxx @@ -0,0 +1,81 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: compilehelp.hxx,v $ + * $Revision: 1.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +#ifndef COMPILE_HXX +#define COMPILE_HXX + +#include "sal/types.h" + +#if defined(HELPLINKER_DLLIMPLEMENTATION) +#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT +#else +#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT +#endif +#define HELPLINKER_DLLPRIVATE SAL_DLLPRIVATE + + +//#include +#include + +enum HelpProcessingErrorClass +{ + HELPPROCESSING_NO_ERROR, + HELPPROCESSING_GENERAL_ERROR, // Missing files, options etc. + HELPPROCESSING_INTERNAL_ERROR, // Unexpected problems + HELPPROCESSING_XMLPARSING_ERROR // Errors thrown by libxml +}; + +struct HelpProcessingErrorInfo +{ + HelpProcessingErrorClass m_eErrorClass; + rtl::OUString m_aErrorMsg; + rtl::OUString m_aXMLParsingFile; + sal_Int32 m_nXMLParsingLine; + + HelpProcessingErrorInfo( void ) + : m_eErrorClass( HELPPROCESSING_NO_ERROR ) + , m_nXMLParsingLine( -1 ) + {} + + HelpProcessingErrorInfo& operator=( const struct HelpProcessingException& e ); +}; + + +// Returns true in case of success, false in case of error +HELPLINKER_DLLPUBLIC bool compileExtensionHelp +( + const rtl::OUString& aOfficeHelpPath, + const rtl::OUString& aExtensionName, + const rtl::OUString& aExtensionLanguageRoot, + sal_Int32 nXhpFileCount, const rtl::OUString* pXhpFiles, + HelpProcessingErrorInfo& o_rHelpProcessingErrorInfo +); + +#endif diff --git a/l10ntools/source/help/helplinker.pmk b/l10ntools/source/help/helplinker.pmk new file mode 100644 index 000000000000..569c5f4dbdee --- /dev/null +++ b/l10ntools/source/help/helplinker.pmk @@ -0,0 +1,35 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: helplinker.pmk,v $ +# +# $Revision: 1.4 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +# define HELPLINKER_DLLIMPLEMENTATION (see @ inc/xmlhelp/helplinkerdllapi.h) +CDEFS += -DHELPLINKER_DLLIMPLEMENTATION + +VISIBILITY_HIDDEN=TRUE diff --git a/l10ntools/source/help/makefile.mk b/l10ntools/source/help/makefile.mk new file mode 100644 index 000000000000..57164004af8b --- /dev/null +++ b/l10ntools/source/help/makefile.mk @@ -0,0 +1,120 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.38 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ = ..$/.. +PRJNAME = l10ntools +TARGET = HelpLinker +LIBBASENAME = helplinker +PACKAGE = com$/sun$/star$/help +TARGETTYPE=CUI + +# --- Settings ----------------------------------------------------- + +.INCLUDE : settings.mk +.INCLUDE : helplinker.pmk + +.IF "$(SYSTEM_LIBXSLT)" == "YES" +CFLAGS+= $(LIBXSLT_CFLAGS) +.ELSE +LIBXSLTINCDIR=external$/libxslt +CFLAGS+= -I$(SOLARINCDIR)$/$(LIBXSLTINCDIR) +.ENDIF + +.IF "$(SYSTEM_DB)" == "YES" +CFLAGS+=-DSYSTEM_DB -I$(DB_INCLUDES) +.ENDIF + +.IF "$(SYSTEM_EXPAT)" == "YES" +CFLAGS+=-DSYSTEM_EXPAT +.ENDIF + +OBJFILES=\ + $(OBJ)$/HelpLinker.obj \ + $(OBJ)$/HelpCompiler.obj +SLOFILES=\ + $(SLO)$/HelpLinker.obj \ + $(SLO)$/HelpCompiler.obj + +EXCEPTIONSFILES=\ + $(OBJ)$/HelpLinker.obj \ + $(OBJ)$/HelpCompiler.obj \ + $(SLO)$/HelpLinker.obj \ + $(SLO)$/HelpCompiler.obj +.IF "$(OS)" == "MACOSX" && "$(CPU)" == "P" && "$(COM)" == "GCC" +# There appears to be a GCC 4.0.1 optimization error causing _file:good() to +# report true right before the call to writeOut at HelpLinker.cxx:1.12 l. 954 +# but out.good() to report false right at the start of writeOut at +# HelpLinker.cxx:1.12 l. 537: +NOOPTFILES=\ + $(OBJ)$/HelpLinker.obj \ + $(SLO)$/HelpLinker.obj +.ENDIF + +APP1TARGET= $(TARGET) +APP1OBJS=\ + $(OBJ)$/HelpLinker.obj \ + $(OBJ)$/HelpCompiler.obj + +APP1STDLIBS+=$(SALLIB) $(BERKELEYLIB) $(XSLTLIB) $(EXPATASCII3RDLIB) + +SHL1TARGET =$(LIBBASENAME)$(DLLPOSTFIX) +SHL1LIBS= $(SLB)$/$(TARGET).lib +SHL1IMPLIB =i$(LIBBASENAME) +SHL1DEF =$(MISC)$/$(SHL1TARGET).def +SHL1STDLIBS =$(SALLIB) $(BERKELEYLIB) $(XSLTLIB) $(EXPATASCII3RDLIB) +SHL1USE_EXPORTS =ordinal + +DEF1NAME =$(SHL1TARGET) +DEFLIB1NAME =$(TARGET) + +JAVAFILES = \ + HelpIndexerTool.java \ + HelpFileDocument.java + + +JAVACLASSFILES = \ + $(CLASSDIR)$/$(PACKAGE)$/HelpIndexerTool.class \ + $(CLASSDIR)$/$(PACKAGE)$/HelpFileDocument.class + +.IF "$(SYSTEM_LUCENE)" == "YES" +CLASSPATH!:=$(CLASSPATH)$(PATH_SEPERATOR)$(LUCENE_CORE_JAR)$(PATH_SEPERATOR)$(LUCENE_ANALYZERS_JAR) +.ELSE +JARFILES += lucene-core-2.3.jar lucene-analyzers-2.3.jar +.ENDIF +JAVAFILES = $(subst,$(CLASSDIR)$/$(PACKAGE)$/, $(subst,.class,.java $(JAVACLASSFILES))) + +JARCLASSDIRS = $(PACKAGE)/* +JARTARGET = HelpIndexerTool.jar +JARCOMPRESS = TRUE + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk diff --git a/l10ntools/source/helpex.cxx b/l10ntools/source/helpex.cxx new file mode 100644 index 000000000000..8f0b6c1d218f --- /dev/null +++ b/l10ntools/source/helpex.cxx @@ -0,0 +1,299 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: helpex.cxx,v $ + * $Revision: 1.14 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include + +// local includes +#include "helpmerge.hxx" + +// defines to parse command line +#define STATE_NON 0x0001 +#define STATE_INPUT 0x0002 +#define STATE_OUTPUT 0x0003 +#define STATE_PRJ 0x0004 +#define STATE_ROOT 0x0005 +#define STATE_SDFFILE 0x0006 +#define STATE_ERRORLOG 0x0007 +#define STATE_BREAKHELP 0x0008 +#define STATE_UNMERGE 0x0009 +#define STATE_UTF8 0x000A +#define STATE_LANGUAGES 0x000B +#define STATE_FORCE_LANGUAGES 0x000C +#define STATE_OUTPUTX 0xfe +#define STATE_OUTPUTY 0xff + +// set of global variables +ByteString sInputFile; +BOOL bEnableExport; +BOOL bMergeMode; +BOOL bErrorLog; +BOOL bUTF8; +ByteString sPrj; +ByteString sPrjRoot; +ByteString sOutputFile; +ByteString sOutputFileX; +ByteString sOutputFileY; +ByteString sSDFFile; +bool bQuiet; + +/*****************************************************************************/ +BOOL ParseCommandLine( int argc, char* argv[]) +/*****************************************************************************/ +{ + bEnableExport = FALSE; + bMergeMode = FALSE; + bErrorLog = TRUE; + bUTF8 = TRUE; + sPrj = ""; + sPrjRoot = ""; + bQuiet = false; + Export::sLanguages = ""; + Export::sForcedLanguages = ""; + + USHORT nState = STATE_NON; + BOOL bInput = FALSE; + + // parse command line + for( int i = 1; i < argc; i++ ) { + if ( ByteString( argv[ i ]).ToUpperAscii() == "-I" ) { + nState = STATE_INPUT; // next tokens specifies source files + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-O" ) { + nState = STATE_OUTPUT; // next token specifies the dest file + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-X" ) { + nState = STATE_OUTPUTX; // next token specifies the dest file + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-Y" ) { + nState = STATE_OUTPUTY; // next token specifies the dest file + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-P" ) { + nState = STATE_PRJ; // next token specifies the cur. project + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-LF" ) { + nState = STATE_FORCE_LANGUAGES; + } + + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-R" ) { + nState = STATE_ROOT; // next token specifies path to project root + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-M" ) { + nState = STATE_SDFFILE; // next token specifies the merge database + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-E" ) { + nState = STATE_ERRORLOG; + bErrorLog = FALSE; + } + else if ( ByteString( argv[ i ] ).ToUpperAscii() == "-QQ" ) { + bQuiet = true; + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-UTF8" ) { + nState = STATE_UTF8; + bUTF8 = TRUE; + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-NOUTF8" ) { + nState = STATE_UTF8; + bUTF8 = FALSE; + } + else if ( ByteString( argv[ i ]).ToUpperAscii() == "-L" ) { + nState = STATE_LANGUAGES; + } + else { + switch ( nState ) { + case STATE_NON: { + return FALSE; // no valid command line + } + //break; + case STATE_INPUT: { + sInputFile = argv[ i ]; + bInput = TRUE; // source file found + } + break; + case STATE_OUTPUT: { + sOutputFile = argv[ i ]; // the dest. file + } + break; + case STATE_OUTPUTX: { + sOutputFileX = argv[ i ]; // the dest. file + } + break; + case STATE_OUTPUTY: { + sOutputFileY = argv[ i ]; // the dest. file + } + break; + case STATE_PRJ: { + sPrj = argv[ i ]; +// sPrj.ToLowerAscii(); // the project + } + break; + case STATE_ROOT: { + sPrjRoot = argv[ i ]; // path to project root + } + break; + case STATE_SDFFILE: { + sSDFFile = argv[ i ]; + bMergeMode = TRUE; // activate merge mode, cause merge database found + } + break; + case STATE_LANGUAGES: { + Export::sLanguages = argv[ i ]; + } + case STATE_FORCE_LANGUAGES:{ + Export::sForcedLanguages = argv[ i ]; + } + break; + } + } + } + + if ( bInput ) { + // command line is valid + bEnableExport = TRUE; + return TRUE; + } + + // command line is not valid + return FALSE; +} + + +/*****************************************************************************/ +void Help() +/*****************************************************************************/ +{ + fprintf( stdout, "Syntax: HELPEX[-p Prj][-r PrjRoot]-i FileIn ( -o FileOut | -x path -y relfile )[-m DataBase][-e][-b][-u][-L l1,l2,...][-QQ] -LF l1,l2 \n" ); + fprintf( stdout, " Prj: Project\n" ); + fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); + fprintf( stdout, " FileIn: Source file (*.lng)\n" ); + fprintf( stdout, " FileOut: Destination file (*.*)\n" ); + fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); + fprintf( stdout, " -QQ: quiet output\n" ); + fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (en-US,fr,de...)\n" ); + fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); + fprintf( stdout, " f1, f2,... are also elements of (en-US,fr,de...)\n" ); + fprintf( stdout, " Example: -L fr=en-US\n" ); + fprintf( stdout, " Restriction to fr, en-US will be fallback for fr\n" ); + fprintf( stdout, " -LF: Force the creation of that languages\n" ); + +} + +/*****************************************************************************/ +#ifndef TESTDRIVER + +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + + if ( !ParseCommandLine( argc, argv )) { + Help(); + return 1; + } + //sal_uInt32 startfull = Export::startMessure(); + + bool hasInputList = sInputFile.GetBuffer()[0]=='@'; +// printf("x = %s , y = %s , o = %s\n", sOutputFileX.GetBuffer(), sOutputFileY.GetBuffer() , sOutputFile.GetBuffer() ); + bool hasNoError = true; + + if ( sOutputFile.Len() ){ // Merge single file ? + //printf("DBG: Inputfile = %s\n",sInputFile.GetBuffer()); + HelpParser aParser( sInputFile, bUTF8 , false ); + + if ( bMergeMode ) + { + + //sal_uInt64 startreadloc = Export::startMessure(); + MergeDataFile aMergeDataFile( sSDFFile, sInputFile , FALSE, RTL_TEXTENCODING_MS_1252 ); + //MergeDataFile aMergeDataFile( sSDFFile, sInputFile , FALSE, RTL_TEXTENCODING_MS_1252, false ); + //Export::stopMessure( ByteString("read localize.sdf") , startreadloc ); + + hasNoError = aParser.Merge( sSDFFile, sOutputFile , Export::sLanguages , aMergeDataFile ); + } + else + hasNoError = aParser.CreateSDF( sOutputFile, sPrj, sPrjRoot, sInputFile, new XMLFile( '0' ), "help" ); + }else if ( sOutputFileX.Len() && sOutputFileY.Len() && hasInputList ) { // Merge multiple files ? + if ( bMergeMode ){ + + ifstream aFStream( sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() , ios::in ); + + if( !aFStream ){ + cerr << "ERROR: - helpex - Can't open the file " << sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() << "\n"; + exit(-1); + } + + vector filelist; + rtl::OStringBuffer filename; + sal_Char aChar; + while( aFStream.get( aChar ) ) + { + if( aChar == ' ' || aChar == '\n') + filelist.push_back( ByteString( filename.makeStringAndClear().getStr() ) ); + else + filename.append( aChar ); + } + if( filename.getLength() > 0 ) + filelist.push_back( ByteString ( filename.makeStringAndClear().getStr() ) ); + + aFStream.close(); + ByteString sHelpFile(""); // dummy + //MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , FALSE, RTL_TEXTENCODING_MS_1252, false ); + MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , FALSE, RTL_TEXTENCODING_MS_1252 ); + + //aMergeDataFile.Dump(); + std::vector aLanguages; + HelpParser::parse_languages( aLanguages , aMergeDataFile ); + + bool bCreateDir = true; + for( vector::iterator pos = filelist.begin() ; pos != filelist.end() ; ++pos ) + { + sHelpFile = *pos; + cout << ".";cout.flush(); + + HelpParser aParser( sHelpFile , bUTF8 , true ); + hasNoError = aParser.Merge( sSDFFile , sOutputFileX , sOutputFileY , true , aLanguages , aMergeDataFile , bCreateDir ); + bCreateDir = false; + } + } + } else + cerr << "helpex ERROR: Wrong input parameters!\n"; + + //Export::stopMessure( ByteString("full cycle") , startfull ); + if( hasNoError ) + return 0; + else + return 1; +} +#endif diff --git a/l10ntools/source/helpmerge.cxx b/l10ntools/source/helpmerge.cxx new file mode 100644 index 000000000000..84d73e94f312 --- /dev/null +++ b/l10ntools/source/helpmerge.cxx @@ -0,0 +1,730 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: helpmerge.cxx,v $ + * $Revision: 1.24 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +// local includes +#include +#include +#include "helpmerge.hxx" +#include "utf8conv.hxx" +#include +#include +#include +#include +#include +#include +#include "rtl/strbuf.hxx" +#ifdef WNT +#include +//#include +#include "tools/prewin.h" +#include +#include "tools/postwin.h" +#endif + +/*****************************************************************************/ +void HelpParser::FillInFallbacks( LangHashMap& rElem_out, ByteString sLangIdx_in ){ +/*****************************************************************************/ + static const ByteString ENGLISH_LANGUAGECODE( "en-US" ); + static const ByteString GERMAN_LANGUAGECODE ( "de" ); + ByteString sCur; + XMLElement* pTmp = NULL; + XMLElement* pTmp2 = NULL; + + sCur = sLangIdx_in; + ByteString sFallback( sCur ); + GetIsoFallback( sFallback ); + if( (rElem_out.find( sFallback ) != rElem_out.end()) && rElem_out[ sFallback ] != NULL ){ + pTmp2 = rElem_out[ sFallback ]; + pTmp = new XMLElement( *pTmp2 ) ; // Copy + pTmp->SetPos( pTmp2->GetPos()+1 ); + pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US) ); + rElem_out[ sLangIdx_in ] = pTmp; + pTmp2 = NULL; + } + else if( (rElem_out.find( ENGLISH_LANGUAGECODE ) != rElem_out.end()) && rElem_out[ ENGLISH_LANGUAGECODE ] != NULL ){// No English + pTmp2 = rElem_out[ ENGLISH_LANGUAGECODE ]; + pTmp = new XMLElement( *pTmp2 ) ; // Copy + pTmp->SetPos( pTmp2->GetPos()+1 ); + pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US) ); + rElem_out[ sCur ] = pTmp; + pTmp2 = NULL; + } + else if( (rElem_out.find( GERMAN_LANGUAGECODE ) != rElem_out.end() ) && rElem_out[ GERMAN_LANGUAGECODE ] != NULL ){// No English + pTmp2 = rElem_out[ GERMAN_LANGUAGECODE ]; + pTmp = new XMLElement( *pTmp2 ); // Copy + pTmp->SetPos( pTmp2->GetPos()+1 ); + pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US ) ); + rElem_out[ sCur ] = pTmp; + pTmp2 = NULL; + }else{ + fprintf(stdout,"ERROR: No Fallback found for language %s:\n",sCur.GetBuffer()); + rElem_out[ sCur ]=new XMLElement(); // Use dummy element + } +} + +/*****************************************************************************/ +void HelpParser::Dump(XMLHashMap* rElem_in) { +/*****************************************************************************/ + for(XMLHashMap::iterator pos = rElem_in->begin();pos != rElem_in->end(); ++pos){ + Dump(pos->second,pos->first); + } +} +/*****************************************************************************/ +void HelpParser::Dump(LangHashMap* rElem_in,const ByteString sKey_in) { +/*****************************************************************************/ + ByteString x; + OString y; + fprintf(stdout,"+------------%s-----------+\n",sKey_in.GetBuffer() ); + for(LangHashMap::iterator posn=rElem_in->begin();posn!=rElem_in->end();++posn){ + x=posn->first; + y=posn->second->ToOString(); + fprintf(stdout,"key=%s value=%s\n",x.GetBuffer(),y.getStr()); + } + fprintf(stdout,"+--------------------------+\n"); +} + +HelpParser::HelpParser( const ByteString &rHelpFile, bool rUTF8 , bool rHasInputList ) + : sHelpFile( rHelpFile ), + bUTF8 ( rUTF8 ), + bHasInputList( rHasInputList ) + {}; + +/*****************************************************************************/ +bool HelpParser::CreateSDF( +/*****************************************************************************/ + const ByteString &rSDFFile_in, const ByteString &rPrj_in,const ByteString &rRoot_in, + const ByteString &sHelpFile, XMLFile *pXmlFile, const ByteString &rGsi1){ + // GSI File constants + static const String GSI_SEQUENCE1( String::CreateFromAscii("\t0\t") ); + static const String GSI_SEQUENCE2( String::CreateFromAscii("\t\t\t0\t") ); + static const String GSI_TAB ( String::CreateFromAscii("\t") ); + static const String GSI_SEQUENCE4( String::CreateFromAscii("\t\t\t\t") ); + static const String ret ( String::CreateFromAscii("\n") ); + static const String ret_char ( String::CreateFromAscii("") ); + static const String tab ( String::CreateFromAscii("\t") ); + static const String tab_char ( String::CreateFromAscii("") ); + + SimpleXMLParser aParser; + String sUsedTempFile; + String sXmlFile; + + if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ){ + DirEntry aTempFile = Export::GetTempFile(); + DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); + aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); + String sTempFile = aTempFile.GetFull(); + Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); + sUsedTempFile = sTempFile; + sXmlFile = sTempFile; + }else{ + sUsedTempFile = String::CreateFromAscii(""); + sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); + } + +// ByteString fullFilePath; + //DirEntry aFile( sXmlFile ); + //makeAbsolutePath( sHelpFile , rRoot_in); + ByteString fullFilePath = rPrj_in; + fullFilePath.Append( "\\" ); + fullFilePath.Append( makeAbsolutePath( sHelpFile , rRoot_in ) ); + fullFilePath.SearchAndReplaceAll( "\\", "/" ); + + String strFullPath( fullFilePath.GetBuffer() , RTL_TEXTENCODING_ASCII_US ); + + //printf( "%s\n", fullFilePath.GetBuffer() ); + std::auto_ptr file ( aParser.Execute( strFullPath , sXmlFile, pXmlFile ) ); + + if(file.get() == NULL){ + printf("%s\n",ByteString(aParser.GetError().sMessage,RTL_TEXTENCODING_ASCII_US).GetBuffer()); + exit(-1); + //return false; + } + file->Extract(); + if( !file->CheckExportStatus() ){ + return true; + } + SvFileStream aSDFStream( String( rSDFFile_in, RTL_TEXTENCODING_ASCII_US ), + STREAM_STD_WRITE | STREAM_TRUNC ); + + if ( !aSDFStream.IsOpen()) { + fprintf(stdout,"Can't open file %s\n",rSDFFile_in.GetBuffer()); + return false; + } + + ByteString sActFileName = makeAbsolutePath( sHelpFile , rRoot_in ); + +/* DirEntry aEntry( String( sHelpFile, RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + String sFullEntry = aEntry.GetFull(); + aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( rRoot_in ); + ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); + ByteString sActFileName( + sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); + + sActFileName.SearchAndReplaceAll( "/", "\\" ); +*/ + XMLHashMap* aXMLStrHM = file->GetStrings(); + LangHashMap* pElem; + XMLElement* pXMLElement = NULL; + + //Dump(aXMLStrHM); + + ByteString sTimeStamp( Export::GetTimeStamp() ); + OUString sOUTimeStamp( sTimeStamp.GetBuffer() , sTimeStamp.Len() , RTL_TEXTENCODING_ASCII_US ); + + OUStringBuffer sBuffer; + const OUString sOUPrj( rPrj_in.GetBuffer() , rPrj_in.Len() , RTL_TEXTENCODING_ASCII_US ); + const OUString sOUActFileName(sActFileName.GetBuffer() , sActFileName.Len() , RTL_TEXTENCODING_ASCII_US ); + const OUString sOUGsi1( rGsi1.GetBuffer() , rGsi1.Len() , RTL_TEXTENCODING_ASCII_US ); + + Export::InitLanguages( false ); + std::vector aLanguages = Export::GetLanguages(); + + std::vector order = file->getOrder(); + std::vector::iterator pos; + XMLHashMap::iterator posm; + + for( pos = order.begin(); pos != order.end() ; ++pos ) + { + posm = aXMLStrHM->find( *pos ); + pElem = posm->second; + ByteString sCur; + + for( unsigned int n = 0; n < aLanguages.size(); n++ ) + { + sCur = aLanguages[ n ]; + if(pElem->find( sCur )==pElem->end()) + { + FillInFallbacks( *pElem , sCur ); + } + pXMLElement = (*pElem)[ sCur ]; + + if( pXMLElement != NULL ) + { + OUString data = pXMLElement->ToOUString(); + String sTmp = String(data.getStr()); + sTmp.SearchAndReplaceAll(ret,ret_char); // Remove \n + sTmp.SearchAndReplaceAll(tab,tab_char); // Remove \t + + data = OUString( sTmp ); + sBuffer.append( sOUPrj ); + sBuffer.append( GSI_TAB ); //"\t"; + if ( rRoot_in.Len()) + sBuffer.append( sOUActFileName ); + sBuffer.append( GSI_SEQUENCE1 ); //"\t0\t"; + sBuffer.append( sOUGsi1 ); //"help"; + sBuffer.append( GSI_TAB ); //"\t"; + ByteString sID = posm->first; // ID + sBuffer.append( OUString( sID.GetBuffer() , sID.Len() , RTL_TEXTENCODING_UTF8 ) ); + sBuffer.append( GSI_TAB ); //"\t"; + ByteString sOldRef = pXMLElement->GetOldref(); // oldref + sBuffer.append( OUString(sOldRef.GetBuffer() , sOldRef.Len() , RTL_TEXTENCODING_UTF8 ) ); + sBuffer.append( GSI_SEQUENCE2 ); //"\t\t\t0\t"; + sBuffer.append( OUString( sCur.GetBuffer() , sCur.Len() , RTL_TEXTENCODING_UTF8 ) ); + sBuffer.append( GSI_TAB ); //"\t"; + sBuffer.append( data ); + sBuffer.append( GSI_SEQUENCE4 ); //"\t\t\t\t"; + sBuffer.append( sOUTimeStamp ); + ByteString sOut( sBuffer.makeStringAndClear().getStr() , RTL_TEXTENCODING_UTF8 ); + //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( rPrj_in ) ) ) + //{ + if( data.getLength() > 0 ) aSDFStream.WriteLine( sOut ); + //} + pXMLElement=NULL; + }else fprintf(stdout,"\nDBG: NullPointer in HelpParser::CreateSDF , Language %s\n",sCur.GetBuffer() ); + } + + } + //Dump(aXMLStrHM); + aSDFStream.Close(); + + if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ + DirEntry aTempFile( sUsedTempFile ); + aTempFile.Kill(); + } + return TRUE; +} + +ByteString HelpParser::makeAbsolutePath( const ByteString& sHelpFile , const ByteString& rRoot_in ) +{ + DirEntry aEntry( String( sHelpFile, RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + String sFullEntry = aEntry.GetFull(); + aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( rRoot_in ); + ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); + ByteString sActFileName( + sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); + + sActFileName.SearchAndReplaceAll( "/", "\\" ); + return sActFileName; +} +bool HelpParser::Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile , + ByteString& sLanguage , MergeDataFile& aMergeDataFile ) +{ + + (void) rSDFFile; + bool hasNoError = true; + + SimpleXMLParser aParser; + + String sUsedTempFile; + String sXmlFile; + + if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ){ + DirEntry aTempFile = Export::GetTempFile(); + DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); + aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); + String sTempFile = aTempFile.GetFull(); + Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); + sUsedTempFile = sTempFile; + sXmlFile = sTempFile; + }else{ + sUsedTempFile = String::CreateFromAscii(""); + sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); + } + + OUString sOUHelpFile( sXmlFile ); + String fullFilePath; + DirEntry aFile( sXmlFile ); + + XMLFile* xmlfile = ( aParser.Execute( aFile.GetFull() , sOUHelpFile, new XMLFile( '0' ) ) ); + printf("Dest file %s\n",rDestinationFile.GetBuffer()); + hasNoError = MergeSingleFile( xmlfile , aMergeDataFile , sLanguage , rDestinationFile ); + delete xmlfile; + if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ + DirEntry aTempFile( sUsedTempFile ); + aTempFile.Kill(); + } + return hasNoError; +} + +bool ByteStringEqual( const ByteString& rKey1, const ByteString& rKey2 ) { + return rKey1.CompareTo( rKey2 )==COMPARE_EQUAL; +}; +bool ByteStringLess( const ByteString& rKey1, const ByteString& rKey2 ) { + return rKey1.CompareTo( rKey2 )==COMPARE_LESS; +} + +void HelpParser::parse_languages( std::vector& aLanguages , MergeDataFile& aMergeDataFile ){ + std::vector aTmp; + + const ByteString DE ("de"); + const ByteString ENUS ("en-US"); + static const ByteString ALL( "ALL" ); + + Export::InitLanguages( false ); + + if( Export::sLanguages.EqualsIgnoreCaseAscii( ALL ) ) + { + aLanguages = aMergeDataFile.GetLanguages(); + aLanguages.push_back( DE ); + aLanguages.push_back( ENUS ); + + if( !Export::sForcedLanguages.Equals("") ) + { + std::vector aFL = Export::GetForcedLanguages(); + std::copy( aFL.begin() , + aFL.end() , + back_inserter( aLanguages ) + ); + std::sort( aLanguages.begin() , aLanguages.end() , ByteStringLess ); + std::vector::iterator unique_iter = std::unique( aLanguages.begin() , aLanguages.end() , ByteStringEqual ); + std::copy( aLanguages.begin() , unique_iter , back_inserter( aTmp ) ); + aLanguages = aTmp; + } + } + else{ + aLanguages = Export::GetLanguages(); + } + +} + +bool HelpParser::Merge( + const ByteString &rSDFFile, const ByteString &rPathX , const ByteString &rPathY , bool bISO , + const std::vector& aLanguages , MergeDataFile& aMergeDataFile , bool bCreateDir ) +{ + + + (void) rSDFFile ; + bool hasNoError = true; + SimpleXMLParser aParser; + String sUsedTempFile; + String sXmlFile; + + if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ) + { + DirEntry aTempFile = Export::GetTempFile(); + DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); + aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); + String sTempFile = aTempFile.GetFull(); + Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); + sUsedTempFile = sTempFile; + sXmlFile = sTempFile; + } + else + { + sUsedTempFile = String::CreateFromAscii(""); + sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); + } + + + OUString sOUHelpFile( sXmlFile ); + String fullFilePath; + DirEntry aFile( sXmlFile ); + + XMLFile* xmlfile = ( aParser.Execute( aFile.GetFull() , sOUHelpFile, new XMLFile( '0' ) ) ); + xmlfile->Extract(); + + if( xmlfile == NULL) + { + printf("%s\n",ByteString(aParser.GetError().sMessage,RTL_TEXTENCODING_UTF8).GetBuffer()); + exit(-1); + //return false; + } + + + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + ByteString sFilepath; + if( bISO ) sFilepath = GetOutpath( rPathX , sCur , rPathY ); + else sFilepath = rPathX; + if( bCreateDir ) MakeDir( sFilepath ); + + XMLFile* file = new XMLFile( *xmlfile ); + sFilepath.Append( sHelpFile ); + hasNoError = MergeSingleFile( file , aMergeDataFile , sCur , sFilepath ); + delete file; + + if( !hasNoError ) return false; // Stop on error + } + + if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ) + { + DirEntry aTempFile( sUsedTempFile ); + aTempFile.Kill(); + } + delete xmlfile; + return hasNoError; +} + +bool HelpParser::MergeSingleFile( XMLFile* file , MergeDataFile& aMergeDataFile , const ByteString& sLanguage , + ByteString sPath ) +{ + file->Extract(); + + XMLHashMap* aXMLStrHM = file->GetStrings(); + LangHashMap* aLangHM; + static ResData pResData( "","",""); + pResData.sResTyp = "help"; + + ByteString sTmp = Export::sLanguages; + + sTmp.EraseLeadingAndTrailingChars(); + + for(XMLHashMap::iterator pos=aXMLStrHM->begin();pos!=aXMLStrHM->end();++pos) // Merge every l10n related string + { + + aLangHM = pos->second; + //printf("*********************DUMPING HASHMAP***************************************"); + //Dump( aXMLStrHM ); + //printf("DBG: sHelpFile = %s\n",sHelpFile.GetBuffer() ); + + pResData.sGId = pos->first; + pResData.sFilename = sHelpFile; + + ProcessHelp( aLangHM , sLanguage, &pResData , aMergeDataFile ); + } + + + // Init temp and target file + ByteString sTempFile; + ByteString sTargetFile( sPath ); + ByteString sTempFileCopy; + + static const ByteString INPATH = Export::GetEnv( "INPATH" ); + Export::getRandomName( sPath , sTempFile , INPATH ); + Export::getRandomName( sPath , sTempFileCopy , INPATH ); + // Write in the temp file + bool hasNoError = file->Write ( sTempFile ); + if( !hasNoError ) + { + cerr << "ERROR: file->Write failed\n"; + return false; + } + + DirEntry aTmp( sTempFile ); + DirEntry aTmp2( sTempFileCopy ); + DirEntry aTar( sTargetFile ); + + if( !Export::CopyFile( sTempFile , sTempFileCopy ) ) + { +#if defined(UNX) || defined(OS2) + sleep( 3 ); +#else + Sleep( 3 ); +#endif + if( !Export::CopyFile( sTempFile , sTempFileCopy ) ) + { + cerr << "ERROR: Can not copy file from " << sTempFile.GetBuffer() << " to " << sTempFileCopy.GetBuffer() << "\n"; + return false; + } + } + //remove( sTargetFile.GetBuffer() ); + + FileStat aFSTest( aTar ); + if( aFSTest.GetSize() < 1 ) + { + remove( sTargetFile.GetBuffer() ); + } + int rc; +#if defined(UNX) || defined(OS2) + rc = rename( sTempFile.GetBuffer() , sTargetFile.GetBuffer() ); +#else + rc = MoveFileEx( sTempFile.GetBuffer() , sTargetFile.GetBuffer(), MOVEFILE_REPLACE_EXISTING ); +#endif + FileStat aFS( aTar ); + + //cout << "mv " << sTempFile.GetBuffer() << " " << sTargetFile.GetBuffer() << "\n"; + //cout << "rc -> " << rc << " filesize -> " << aFS.GetSize() << "\n"; +// Windows rename returns -1 if the file already exits +//#ifdef UNX + if( rc < 0 || aFS.GetSize() < 1 ) +//#else +// if( aFS.GetSize() < 1 ) +//#endif + { +#if defined(UNX) || defined(OS2) + sleep( 3 ); +#else + Sleep( 3 ); +#endif + aFSTest.Update( aTar ); + if( aFSTest.GetSize() < 1 ) + { + remove( sTargetFile.GetBuffer() ); + } +#if defined(UNX) || defined(OS2) + rc = rename( sTempFileCopy.GetBuffer() , sTargetFile.GetBuffer() ); +#else + rc = MoveFileEx( sTempFileCopy.GetBuffer() , sTargetFile.GetBuffer() , MOVEFILE_REPLACE_EXISTING ); +#endif + aFS.Update( aTar ); + + //cout << "mv2 " << sTempFileCopy.GetBuffer() << " " << sTargetFile.GetBuffer() << "\n"; + //cout << "rc -> " << rc << " filesize -> " << aFS.GetSize() << "\n"; + +// Windows rename returns -1 if the file already exits +//#ifdef WNT +// if( aFS.GetSize() < 1 ) +//#else + if( rc < 0 || aFS.GetSize() < 1 ) +//#endif + { + cerr << "ERROR: helpex Can't rename file " << sTempFileCopy.GetBuffer() << " to " << sTargetFile.GetBuffer() << " rename rc=" << rc << " filesize=" << aFS.GetSize() << "\n"; + aTmp.Kill(); + aTmp2.Kill(); + if( aFS.GetSize() < 1 ) + aTar.Kill(); + return false; + } + } + aTmp.Kill(); + aTmp2.Kill(); + + return true; +} + +ByteString HelpParser::GetOutpath( const ByteString& rPathX , const ByteString& sCur , const ByteString& rPathY ){ + ByteString testpath = rPathX; + static const ByteString sDelimiter( DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + testpath.EraseTrailingChars( '/' ); + testpath.EraseTrailingChars( '\\' ); + testpath += sDelimiter; + testpath += sCur; + testpath += sDelimiter; + ByteString sRelativePath( rPathY ); + sRelativePath.EraseLeadingChars( '/' ); + sRelativePath.EraseLeadingChars( '\\' ); + testpath += sRelativePath; + testpath += sDelimiter; + return testpath; +} +void HelpParser::MakeDir( const ByteString& sPath ){ + ByteString sTPath( sPath ); + ByteString sDelimiter( DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + sTPath.SearchAndReplaceAll( sDelimiter , '/' ); + USHORT cnt = sTPath.GetTokenCount( '/' ); + ByteString sCreateDir; + for( USHORT i = 0 ; i < cnt ; i++ ) + { + sCreateDir += sTPath.GetToken( i , '/' ); + sCreateDir += sDelimiter; +#ifdef WNT + _mkdir( sCreateDir.GetBuffer() ); +#else + mkdir( sCreateDir.GetBuffer() , S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ); +#endif + } +} + + +/* ProcessHelp Methode: search for en-US entry and replace it with the current language*/ +void HelpParser::ProcessHelp( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ){ + + XMLElement* pXMLElement = NULL; + PFormEntrys *pEntrys = NULL; + XMLData *data = NULL; + XMLParentNode *parent = NULL; + + String sNewdata; + ByteString sLId; + ByteString sGId; + + pEntrys = NULL; + +#ifdef MERGE_SOURCE_LANGUAGES + if( true ){ // Merge en-US! +#else + if( !sCur.EqualsIgnoreCaseAscii("en-US") ){ +#endif + pXMLElement = (*aLangHM)[ "en-US" ]; + if( pXMLElement == NULL ) + { + printf("Error: Can't find en-US entry\n"); + } + if( pXMLElement != NULL ) + { + parent = pXMLElement->GetParent(); + sLId = pXMLElement->GetOldref(); + pResData->sId = sLId; + + pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); + if( pEntrys != NULL) + { + ByteString sNewText; + pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur , true ); + sNewdata = String( sNewText , RTL_TEXTENCODING_UTF8 ); + if ( sNewdata.Len()) + { + if( pXMLElement != NULL ) + { + data = new XMLData( sNewdata , NULL , true ); // Add new one + pXMLElement->RemoveAndDeleteAllChilds(); + pXMLElement->AddChild( data ); + aLangHM->erase( sCur ); + } + } + }else if( pResData == NULL ){fprintf(stdout,"Can't find GID=%s LID=%s TYP=%s\n",pResData->sGId.GetBuffer(),pResData->sId.GetBuffer(),pResData->sResTyp.GetBuffer());} + pXMLElement->ChangeLanguageTag( String( sCur , RTL_TEXTENCODING_ASCII_US) ); + } + + } +} +/* Process() Method merges */ +void HelpParser::Process( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ){ + + XMLElement* pXMLElement = NULL; + PFormEntrys *pEntrys = NULL; + XMLData *data = NULL; + XMLParentNode *parent = NULL; + XMLDefault *xmldefault = NULL; + + short curLang = 0; + String sNewdata; + bool isFallback = false; + ByteString sLId; + ByteString sGId; + + pEntrys = NULL; + +#ifdef MERGE_SOURCE_LANGUAGES + if( true ){ // Merge en-US! +#else + if( !sCur.EqualsIgnoreCaseAscii("en-US") ){ +#endif + pXMLElement = (*aLangHM)[ sCur ]; + if( pXMLElement == NULL ) + { + FillInFallbacks( *aLangHM , sCur ); + pXMLElement = ( *aLangHM )[ sCur ]; + isFallback = true; + } + if( pXMLElement != NULL ) + { + parent = pXMLElement->GetParent(); + sLId = pXMLElement->GetOldref(); + pResData->sId = sLId; + + pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); + if( pEntrys != NULL) + { + ByteString sNewText; + pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur , true ); + sNewdata = String( sNewText , RTL_TEXTENCODING_UTF8 ); + if ( sNewdata.Len()) + { + printf("Entries found\n"); + if( pXMLElement != NULL ) + { + data = new XMLData( sNewdata , NULL , true ); // Add new one + if( pXMLElement->ToOUString().compareTo( OUString(data->GetData()) ) != 0 ) + { + pXMLElement->RemoveAndDeleteAllChilds(); + pXMLElement->AddChild( data ); + } + if( isFallback ) + { + xmldefault = new XMLDefault( String::CreateFromAscii("\n") , NULL ); + int pos = parent->GetPosition( pXMLElement->GetId() ); + if( pos != -1 ){ + parent->AddChild(xmldefault , pos+1 ); + parent->AddChild(pXMLElement , pos+2 ); + } + else fprintf(stdout,"ERROR: Can't find reference Element of id %s language %d\n",pXMLElement->GetId().GetBuffer(),curLang); + } + + aLangHM->erase( sCur ); + } + } + delete pResData; + }else if( pResData == NULL ){fprintf(stdout,"Can't find GID=%s LID=%s TYP=%s\n",pResData->sGId.GetBuffer(),pResData->sId.GetBuffer(),pResData->sResTyp.GetBuffer());} + } + + } +} + diff --git a/l10ntools/source/inireader.cxx b/l10ntools/source/inireader.cxx new file mode 100644 index 000000000000..1ff34fad8e95 --- /dev/null +++ b/l10ntools/source/inireader.cxx @@ -0,0 +1,132 @@ +#include +#include +#include +#include +#include +#include "inireader.hxx" + +using namespace std; +namespace transex3 +{ + +bool INIreader::read( INImap& myMap , string& filename ) +{ + ifstream aFStream( filename.c_str() ); + if( aFStream && aFStream.is_open()) + { + string line; + string section; + string param_key; + string param_value; + stringmap* myvalues = 0; + + while( std::getline( aFStream , line ) ) + { + trim( line ); + if( line.empty() ){ + } + else if( is_section( line , section ) ) + { + //cerr << "[" << section << "]\n"; + myvalues = new stringmap(); + myMap[ section ] = myvalues ; + } + else if ( is_parameter( line , param_key , param_value ) ) + { + //cerr << "" << param_key << " = " << param_value << "\n"; + if( myvalues ) + { + (*myvalues)[ param_key ] = param_value ; + } + else + { + cerr << "ERROR: The INI file " << filename << " appears to be broken ... parameters without a section?!?\n"; + if( aFStream.is_open() ) aFStream.close(); + return false; + } + } + } + + if( aFStream.is_open() ) + aFStream.close(); + + return true; + } + else + { + cerr << "ERROR: Can't open file '" << filename << "'\n"; + } + return false; +} + +bool INIreader::is_section( string& line , string& section_str ) +{ + // Error in regex ? + check_status( section_status ); + UnicodeString target( line.c_str() , line.length() ); + + section_match->reset( target ); + check_status( section_status ); + + if( section_match->find() ) + { + check_status( section_status ); + UnicodeString result( section_match->group( 1 , section_status) ); + check_status( section_status ); + toStlString( result , section_str ); + + return true; + } + return false; +} + +bool INIreader::is_parameter( string& line , string& parameter_key , string& parameter_value ) +{ + // Error in regex ? + check_status( parameter_status ); + UnicodeString target( line.c_str() , line.length() ); + + parameter_match->reset( target ); + check_status( parameter_status ); + + if( parameter_match->find() ) + { + check_status( parameter_status ); + + UnicodeString result1( parameter_match->group( 1 , parameter_status) ); + check_status( parameter_status ); + toStlString( result1 , parameter_key ); + UnicodeString result2( parameter_match->group( 2 , parameter_status) ); + check_status( parameter_status ); + toStlString( result2 , parameter_value ); + + return true; + } + return false; +} + +void INIreader::check_status( UErrorCode status ) +{ + if( U_FAILURE( status) ) + { + cerr << "Error in or while using regex: " << u_errorName( status ) << "\n"; + exit(-1); + } +} + +void INIreader::toStlString( const UnicodeString& str , string& stl_str) +{ + // convert to string + char* buffer = new char[ str.length()*3 ]; + str.extract( 0 , str.length() , buffer ); + stl_str = string( buffer ); + delete[] buffer; +} + +void INIreader::trim( string& str ) +{ + string str1 = str.substr( 0 , str.find_last_not_of(' ') + 1 ); + str = str1.empty() ? str1 : str1.substr( str1.find_first_not_of(' ') ); +} + +} diff --git a/l10ntools/source/lngex.cxx b/l10ntools/source/lngex.cxx new file mode 100644 index 000000000000..67ee34cbdaab --- /dev/null +++ b/l10ntools/source/lngex.cxx @@ -0,0 +1,226 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: lngex.cxx,v $ + * $Revision: 1.18 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include + +// local includes +#include "lngmerge.hxx" + +// defines to parse command line +#define STATE_NON 0x0001 +#define STATE_INPUT 0x0002 +#define STATE_OUTPUT 0x0003 +#define STATE_PRJ 0x0004 +#define STATE_ROOT 0x0005 +#define STATE_MERGESRC 0x0006 +#define STATE_ERRORLOG 0x0007 +#define STATE_BREAKHELP 0x0008 +#define STATE_UNMERGE 0x0009 +#define STATE_UTF8 0x000A +#define STATE_ULF 0x000B +#define STATE_LANGUAGES 0x000C + +// set of global variables +ByteString sInputFile; +BOOL bEnableExport; +BOOL bMergeMode; +BOOL bErrorLog; +BOOL bUTF8; +BOOL bULF; // ULF = Unicode Language File +bool bQuiet; +ByteString sPrj; +ByteString sPrjRoot; +ByteString sOutputFile; +ByteString sMergeSrc; + +/*****************************************************************************/ +BOOL ParseCommandLine( int argc, char* argv[]) +/*****************************************************************************/ +{ + bEnableExport = FALSE; + bMergeMode = FALSE; + bErrorLog = TRUE; + bUTF8 = TRUE; + bULF = FALSE; + bQuiet = false; + sPrj = ""; + sPrjRoot = ""; + Export::sLanguages = ""; + + USHORT nState = STATE_NON; + BOOL bInput = FALSE; + + // parse command line + for( int i = 1; i < argc; i++ ) { + ByteString sSwitch( argv[ i ] ); + sSwitch.ToUpperAscii(); + if ( sSwitch == "-I" ) { + nState = STATE_INPUT; // next tokens specifies source files + } + else if ( sSwitch == "-O" ) { + nState = STATE_OUTPUT; // next token specifies the dest file + } + else if ( sSwitch == "-P" ) { + nState = STATE_PRJ; // next token specifies the cur. project + } + else if ( sSwitch == "-R" ) { + nState = STATE_ROOT; // next token specifies path to project root + } + else if ( sSwitch == "-QQ" ) { + bQuiet = true; + } + else if ( sSwitch == "-M" ) { + nState = STATE_MERGESRC; // next token specifies the merge database + } + else if ( sSwitch == "-E" ) { + nState = STATE_ERRORLOG; + bErrorLog = FALSE; + } + else if ( sSwitch == "-UTF8" ) { + nState = STATE_UTF8; + bUTF8 = TRUE; + } +/* else if ( sSwitch == "-NOUTF8" ) { + nState = STATE_UTF8; + bUTF8 = FALSE; + }*/ +/* else if ( sSwitch == "-ULF" ) { + nState = STATE_ULF; + bULF = TRUE; + }*/ + else if ( sSwitch == "-L" ) { + nState = STATE_LANGUAGES; + } + else { + switch ( nState ) { + case STATE_NON: { + return FALSE; // no valid command line + } + //break; + case STATE_INPUT: { + sInputFile = argv[ i ]; + bInput = TRUE; // source file found + } + break; + case STATE_OUTPUT: { + sOutputFile = argv[ i ]; // the dest. file + } + break; + case STATE_PRJ: { + sPrj = argv[ i ]; +// sPrj.ToLowerAscii(); // the project + } + break; + case STATE_ROOT: { + sPrjRoot = argv[ i ]; // path to project root + } + break; + case STATE_MERGESRC: { + sMergeSrc = argv[ i ]; + bMergeMode = TRUE; // activate merge mode, cause merge database found + } + break; + case STATE_LANGUAGES: { + Export::sLanguages = argv[ i ]; + } + break; + } + } + } + + if ( bInput ) { + // command line is valid + bULF = TRUE; + bEnableExport = TRUE; + return TRUE; + } + + // command line is not valid + return FALSE; +} + + +/*****************************************************************************/ +void Help() +/*****************************************************************************/ +{ + //fprintf( stdout, "Syntax:ULFEX[-p Prj][-r PrjRoot]-i FileIn -o FileOut[-m DataBase][-e][-b][-u][-NOUTF8][-ULF][-L l1,l2,...]\n" ); + fprintf( stdout, "Syntax:ULFEX[-p Prj][-r PrjRoot]-i FileIn -o FileOut[-m DataBase][-L l1,l2,...]\n" ); + fprintf( stdout, " Prj: Project\n" ); + fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); + fprintf( stdout, " FileIn: Source file (*.lng)\n" ); + fprintf( stdout, " FileOut: Destination file (*.*)\n" ); + fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); + fprintf( stdout, " -QQ: quite output\n" ); + //fprintf( stdout, " -NOUTF8: disable UTF8 as language independent encoding\n" ); + //fprintf( stdout, " -ULF: enables Unicode Language File format, leads to UTF8 encoded version of lng files" ); + fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); + fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); + fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); + fprintf( stdout, " Example: -L de,es=en-US\n" ); + fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); +} + +/*****************************************************************************/ +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + if ( !ParseCommandLine( argc, argv )) { + Help(); + return 1; + } + if( !bQuiet ){ + fprintf( stdout, "\nUlfEx 1 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); + fprintf( stdout, "====================================================================\n" ); + fprintf( stdout, "\nProcessing File %s ...\n", sInputFile.GetBuffer()); + }else + { + fprintf(stdout, "."); + fflush( stdout ); + } + + if ( sOutputFile.Len()) { + LngParser aParser( sInputFile, bUTF8, bULF , bQuiet ); + if ( bMergeMode ) + aParser.Merge( sMergeSrc, sOutputFile , sPrj ); + else + aParser.CreateSDF( sOutputFile, sPrj, sPrjRoot ); + } + + if( !bQuiet ) fprintf( stdout, "\n=================================================\n\n" ); + + return 0; +} diff --git a/l10ntools/source/lngmerge.cxx b/l10ntools/source/lngmerge.cxx new file mode 100644 index 000000000000..fcad498128c2 --- /dev/null +++ b/l10ntools/source/lngmerge.cxx @@ -0,0 +1,360 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: lngmerge.cxx,v $ + * $Revision: 1.29 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include + +// local includes +#include "lngmerge.hxx" +#include "utf8conv.hxx" +#include +using namespace std; +// +// class LngParser +// +/*****************************************************************************/ +LngParser::LngParser( const ByteString &rLngFile, BOOL bUTF8, BOOL bULFFormat , bool bQuiet_in ) +/*****************************************************************************/ + : + nError( LNG_OK ), + pLines( NULL ), + sSource( rLngFile ), + bDBIsUTF8( bUTF8 ), + bULF( bULFFormat ), + bQuiet( bQuiet_in ) +{ + pLines = new LngLineList( 100, 100 ); + DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); + if ( aEntry.Exists()) { + SvFileStream aStream( String( sSource, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); + if ( aStream.IsOpen()) { + ByteString sLine; + bool bFirstLine = true; + while ( !aStream.IsEof()) { + aStream.ReadLine( sLine ); + + if( bFirstLine ){ // Always remove UTF8 BOM from the first line + Export::RemoveUTF8ByteOrderMarker( sLine ); + bFirstLine = false; + } + + pLines->Insert( new ByteString( sLine ), LIST_APPEND ); + } + } + else + nError = LNG_COULD_NOT_OPEN; + } + else + nError = LNG_FILE_NOTFOUND; +} + +/*****************************************************************************/ +LngParser::~LngParser() +/*****************************************************************************/ +{ + for ( ULONG i = 0; i < pLines->Count(); i++ ) + delete pLines->GetObject( i ); + delete pLines; +} + +/*****************************************************************************/ +void LngParser::FillInFallbacks( ByteStringHashMap Text ) +/*****************************************************************************/ +{ + ByteString sCur; + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + + if( Export::isAllowed( sCur ) ){ + ByteString sFallbackLang = Export::GetFallbackLanguage( sCur ); + if( sFallbackLang.Len() ){ + Text[ sCur ] = Text[ sFallbackLang ]; + } + } + } +} + +/*****************************************************************************/ +BOOL LngParser::CreateSDF( + const ByteString &rSDFFile, const ByteString &rPrj, + const ByteString &rRoot ) +/*****************************************************************************/ +{ + + Export::InitLanguages( false ); + aLanguages = Export::GetLanguages(); + SvFileStream aSDFStream( String( rSDFFile, RTL_TEXTENCODING_ASCII_US ), + STREAM_STD_WRITE | STREAM_TRUNC ); + if ( !aSDFStream.IsOpen()) { + nError = SDF_COULD_NOT_OPEN; + } + aSDFStream.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); + nError = SDF_OK; + DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + String sFullEntry = aEntry.GetFull(); + aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( rRoot ); + ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); + ByteString sActFileName( + sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); + sActFileName.SearchAndReplaceAll( "/", "\\" ); + + ULONG nPos = 0; + BOOL bStart = true; + ByteString sGroup; + ByteStringHashMap Text; + ByteString sID; + ByteString sLine; + + while( nPos < pLines->Count() ){ + sLine = *pLines->GetObject( nPos++ ); + while( nPos < pLines->Count() && !isNextGroup( sGroup , sLine ) ){ + ReadLine( sLine , Text ); + sID = sGroup; + sLine = *pLines->GetObject( nPos++ ); + }; + if( bStart ){ + bStart = false; + sID = sGroup; + } + else { + + WriteSDF( aSDFStream , Text , rPrj , rRoot , sActFileName , sID ); + } + } + aSDFStream.Close(); + return true; +} + + void LngParser::WriteSDF( SvFileStream &aSDFStream , ByteStringHashMap &rText_inout , + const ByteString &rPrj , const ByteString &rRoot , + const ByteString &sActFileName , const ByteString &sID ) + { + + BOOL bExport = true; + if ( bExport ) { + ByteString sTimeStamp( Export::GetTimeStamp()); + ByteString sCur; + FillInFallbacks( rText_inout ); + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + ByteString sAct = rText_inout[ sCur ]; + if ( !sAct.Len() && sCur.Len() ) + sAct = rText_inout[ ByteString("en-US") ]; + + ByteString sOutput( rPrj ); sOutput += "\t"; + if ( rRoot.Len()) + sOutput += sActFileName; + sOutput += "\t0\t"; + sOutput += "LngText\t"; + sOutput += sID; sOutput += "\t\t\t\t0\t"; + sOutput += sCur; sOutput += "\t"; + sOutput += sAct; sOutput += "\t\t\t\t"; + sOutput += sTimeStamp; + //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( rPrj ) ) ) + aSDFStream.WriteLine( sOutput ); + } + } + } + bool LngParser::isNextGroup( ByteString &sGroup_out , ByteString &sLine_in ){ + sLine_in.EraseLeadingChars( ' ' ); + sLine_in.EraseTrailingChars( ' ' ); + if (( sLine_in.GetChar( 0 ) == '[' ) && + ( sLine_in.GetChar( sLine_in.Len() - 1 ) == ']' )){ + sGroup_out = sLine_in.GetToken( 1, '[' ).GetToken( 0, ']' ); + sGroup_out.EraseLeadingChars( ' ' ); + sGroup_out.EraseTrailingChars( ' ' ); + return true; + } + return false; + } + void LngParser::ReadLine( const ByteString &sLine_in , ByteStringHashMap &rText_inout){ + //printf("sLine -> '%s'\n",sLine_in.GetBuffer()); + ByteString sLang = sLine_in.GetToken( 0, '=' ); + sLang.EraseLeadingChars( ' ' ); + sLang.EraseTrailingChars( ' ' ); + ByteString sText = sLine_in.GetToken( 1, '\"' ).GetToken( 0, '\"' ); + if( sLang.Len() ) + rText_inout[ sLang ] = sText; + } + +/*****************************************************************************/ +BOOL LngParser::Merge( + const ByteString &rSDFFile, const ByteString &rDestinationFile , const ByteString& rPrj ) +/*****************************************************************************/ +{ + (void) rPrj; + Export::InitLanguages( true ); + SvFileStream aDestination( + String( rDestinationFile, RTL_TEXTENCODING_ASCII_US ), + STREAM_STD_WRITE | STREAM_TRUNC ); + if ( !aDestination.IsOpen()) { + nError = LNG_COULD_NOT_OPEN; + } + nError = LNG_OK; +// MergeDataFile( const ByteString &rFileName, const ByteString& rFile , BOOL bErrLog, CharSet aCharSet, BOOL bUTF8 ); + + MergeDataFile aMergeDataFile( rSDFFile, sSource , FALSE, RTL_TEXTENCODING_MS_1252);//, bDBIsUTF8 ); + ByteString sTmp( Export::sLanguages ); + if( sTmp.ToUpperAscii().Equals("ALL") ) + Export::SetLanguages( aMergeDataFile.GetLanguages() ); + aLanguages = Export::GetLanguages(); + + ULONG nPos = 0; + BOOL bGroup = FALSE; + ByteString sGroup; + + // seek to next group + while ( nPos < pLines->Count() && !bGroup ) { + ByteString sLine( *pLines->GetObject( nPos )); + sLine.EraseLeadingChars( ' ' ); + sLine.EraseTrailingChars( ' ' ); + if (( sLine.GetChar( 0 ) == '[' ) && + ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) + { + sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); + sGroup.EraseLeadingChars( ' ' ); + sGroup.EraseTrailingChars( ' ' ); + bGroup = TRUE; + } + nPos ++; + } + + while ( nPos < pLines->Count()) { + ByteStringHashMap Text; + ByteString sID( sGroup ); + ULONG nLastLangPos = 0; + + ResData *pResData = new ResData( "", sID , sSource ); + pResData->sResTyp = "LngText"; + PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); + // read languages + bGroup = FALSE; + + ByteString sLanguagesDone; + + while ( nPos < pLines->Count() && !bGroup ) { + ByteString sLine( *pLines->GetObject( nPos )); + sLine.EraseLeadingChars( ' ' ); + sLine.EraseTrailingChars( ' ' ); + if (( sLine.GetChar( 0 ) == '[' ) && + ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) + { + sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); + sGroup.EraseLeadingChars( ' ' ); + sGroup.EraseTrailingChars( ' ' ); + bGroup = TRUE; + nPos ++; + sLanguagesDone = ""; + } + else if ( sLine.GetTokenCount( '=' ) > 1 ) { + ByteString sLang = sLine.GetToken( 0, '=' ); + sLang.EraseLeadingChars( ' ' ); + sLang.EraseTrailingChars( ' ' ); + + ByteString sSearch( ";" ); + sSearch += sLang; + sSearch += ";"; + + if (( sLanguagesDone.Search( sSearch ) != STRING_NOTFOUND )) { + pLines->Remove( nPos ); + } + if( bULF && pEntrys ) + { + // this is a valid text line + ByteString sText = sLine.GetToken( 1, '\"' ).GetToken( 0, '\"' ); + if( sLang.Len() ){ + ByteString sNewText; + pEntrys->GetText( sNewText, STRING_TYP_TEXT, sLang, TRUE ); + + if ( sNewText.Len()) { + ByteString *pLine = pLines->GetObject( nPos ); + + ByteString sText1( sLang ); + sText1 += " = \""; + sText1 += sNewText; + sText1 += "\""; + *pLine = sText1; + //} + Text[ sLang ] = sNewText; + } + } + nLastLangPos = nPos; + nPos ++; + sLanguagesDone += sSearch; + } + else { + nLastLangPos = nPos; + nPos ++; + sLanguagesDone += sSearch; + } + } + else + nPos++; + } + ByteString sCur; + if ( nLastLangPos ) { + for( unsigned int n = 0; n < aLanguages.size(); n++ ){ + sCur = aLanguages[ n ]; + if( //( !sCur.EqualsIgnoreCaseAscii("de") || + //( sCur.EqualsIgnoreCaseAscii("de") && Export::isMergingGermanAllowed( rPrj ) ) ) + !sCur.EqualsIgnoreCaseAscii("en-US") && !Text[ sCur ].Len() && pEntrys ){ + + ByteString sNewText; + pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur, TRUE ); + if (( sNewText.Len()) && + !(( sCur.Equals("x-comment") ) && ( sNewText == "-" ))) + { + ByteString sLine; + sLine += sCur; + sLine += " = \""; + sLine += sNewText; + sLine += "\""; + + nLastLangPos++; + nPos++; + + pLines->Insert( new ByteString( sLine ), nLastLangPos ); + } + } + } + } + + delete pResData; + } + + for ( ULONG i = 0; i < pLines->Count(); i++ ) + aDestination.WriteLine( *pLines->GetObject( i )); + + aDestination.Close(); + return TRUE; +} diff --git a/l10ntools/source/localize.cxx b/l10ntools/source/localize.cxx new file mode 100644 index 000000000000..b617fdb4cf1e --- /dev/null +++ b/l10ntools/source/localize.cxx @@ -0,0 +1,986 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: localize.cxx,v $ + * $Revision: 1.50 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" + +#include "srciter.hxx" +#include "export.hxx" +#include "treeconfig.hxx" +#include +#include +#include +#include +#include "tools/errcode.hxx" +#include "tools/fsys.hxx" + +#ifndef L10NTOOLS_FILE_HXX +#define L10NTOOLS_FILE_HXX +#include +#endif + +namespace transex3 +{ + +// +// SourceTreeLocalizer +// + +const char *ExeTable[][5] = { + { "src", "transex3", " -UTF8 -e", "negative", "noiso" }, + { "hrc", "transex3", " -UTF8 -e", "positive", "noiso" }, + //{ "src", "transex3", "-UTF8 -e", "negative", "noiso" }, + //{ "hrc", "transex3", "-UTF8 -e", "positive", "noiso" }, + + //{ "lng", "lngex", "-UTF8 -e", "negative", "noiso" }, + { "ulf", "ulfex", " -e", "negative", "noiso" }, + { "xrb", "xmlex", "-UTF8 -e", "negative", "iso" }, + { "xxl", "xmlex", "-UTF8 -e", "negative", "iso" }, + { "xgf", "xmlex", "-UTF8 -e -t:xgf", "negative", "iso" }, + { "xcd", "cfgex", "-UTF8 -e", "negative", "iso" }, + { "xcu", "cfgex", "-UTF8 -e", "negative", "iso" }, + { "xcs", "cfgex", "-UTF8 -e -f", "negative", "iso" }, + { "xrm", "xrmex", "-UTF8 -e", "negative", "iso" }, + { "xhp", "helpex", " -e", "negative", "noiso" }, + { "NULL", "NULL", "NULL", "NULL", "NULL" } +}; + +const char *NegativeList[] = { + "officecfg/data/org.openoffice.Office.Labels.xcd", + "officecfg/data/org/openoffice/Office/Labels.xcd", + "officecfg/data/org/openoffice/Office/SFX.xcd", + "officecfg/data/org/openoffice/Office/Accelerators.xcu", + "hidother.src", + "NULL" +}; + +const char *PositiveList[] = { + "svx/inc/globlmn_tmpl.hrc", + "sw/source/ui/inc/swmn_tmpl.hrc", + "sw/source/ui/inc/swacc_tmpl.hrc", + "sw/source/ui/inc/toolbox_tmpl.hrc", + "offmgr/inc/offmenu_tmpl.hrc", + "offmgr/source/offapp/intro/intro_tmpl.hrc", + "dbaccess/source/ui/inc/toolbox_tmpl.hrc", + "svx/source/intro/intro_tmpl.hrc", + "dbaccess/source/ui/dlg/AutoControls_tmpl.hrc", + "svx/source/unodialogs/textconversiondlgs/chinese_direction_tmpl.hrc", + "chart2/source/controller/dialogs/res_DataLabel_tmpl.hrc", + "chart2/source/controller/dialogs/res_LegendPosition_tmpl.hrc", + "chart2/source/controller/dialogs/res_Statistic_tmpl.hrc", + "chart2/source/controller/dialogs/res_Titlesx_tmpl.hrc", + "chart2/source/controller/dialogs/res_SecondaryAxisCheckBoxes_tmpl.hrc", + "chart2/source/controller/menu/MenuItems_tmpl.hrc", + "chart2/source/controller/dialogs/res_ErrorBar_tmpl.hrc", + "chart2/source/controller/dialogs/res_Trendline_tmpl.hrc", + "svx.link/inc/globlmn_tmpl.hrc", + "sw.link/source/ui/inc/swmn_tmpl.hrc", + "sw.link/source/ui/inc/swacc_tmpl.hrc", + "sw.link/source/ui/inc/toolbox_tmpl.hrc", + "offmgr.link/inc/offmenu_tmpl.hrc", + "offmgr.link/source/offapp/intro/intro_tmpl.hrc", + "dbaccess.link/source/ui/inc/toolbox_tmpl.hrc", + "svx.link/source/intro/intro_tmpl.hrc", + "dbaccess.link/source/ui/dlg/AutoControls_tmpl.hrc", + "svx.link/source/unodialogs/textconversiondlgs/chinese_direction_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_DataLabel_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_LegendPosition_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_Statistic_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_Titlesx_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_SecondaryAxisCheckBoxes_tmpl.hrc", + "chart2.link/source/controller/menu/MenuItems_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_ErrorBar_tmpl.hrc", + "chart2.link/source/controller/dialogs/res_Trendline_tmpl.hrc", + "NULL" +}; + + +const char PRJ_DIR_NAME[] = "prj"; +const char DLIST_NAME[] = "d.lst"; + +#define LOCALIZE_NONE 0x0000 +#define LOCALIZE_EXTRACT 0x0001 +#define LOCALIZE_MERGE 0x0002 + +class SourceTreeLocalizer : public SourceTreeIterator +{ +private: + SvFileStream aSDF; + USHORT nMode; + + ByteString sLanguageRestriction; + + ByteString sOutputFile; + bool bQuiet2; + + int nFileCnt; + + const ByteString GetProjectName( BOOL bAbs = FALSE ); + const ByteString GetProjectRootRel(); + + + BOOL CheckNegativeList( const ByteString &rFileName ); + BOOL CheckPositiveList( const ByteString &rFileName ); + + void WorkOnFile( + const ByteString &rFileName, + const ByteString &rExecutable, + const ByteString &rParameter + ); + + void WorkOnFileType( + const ByteString &rDirectory, + const ByteString &rExtension, + const ByteString &rExecutable, + const ByteString &rParameter, + const ByteString &rCollectMode + ); + void WorkOnDirectory( const ByteString &rDirectory ); + BOOL ExecuteMerge(); + BOOL MergeSingleFile( + const ByteString &rPrj, + const ByteString &rFile, + const ByteString &rSDFFile + ); + +public: + SourceTreeLocalizer( const ByteString &rRoot, const ByteString &rVersion , bool bLocal , bool bQuiet2_in , bool skip_links ); + ~SourceTreeLocalizer(); + + ByteString getSourceLanguages( ByteString sLanguageRestriction , ByteString sCommand ); + + void SetLanguageRestriction( const ByteString& rRestrictions ) + { sLanguageRestriction = rRestrictions; } + int getFileCnt(); + BOOL Extract( const ByteString &rDestinationFile ); + BOOL Merge( const ByteString &rSourceFile , const ByteString &rOutput ); + int GetFileCnt(); + virtual void OnExecuteDirectory( const rtl::OUString &rDirectory ); +}; + +/*****************************************************************************/ +SourceTreeLocalizer::SourceTreeLocalizer( + const ByteString &rRoot, const ByteString &rVersion, bool bLocal_in , bool bQuiet2_in , bool skip_links ) +/*****************************************************************************/ + : SourceTreeIterator( rRoot, rVersion , bLocal_in ), + nMode( LOCALIZE_NONE ), + bQuiet2( bQuiet2_in ), + nFileCnt( 0 ) +{ + bSkipLinks = skip_links ; +} + +/*****************************************************************************/ +SourceTreeLocalizer::~SourceTreeLocalizer() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +const ByteString SourceTreeLocalizer::GetProjectName( BOOL bAbs ) +/*****************************************************************************/ +{ + BOOL bFound = FALSE; + DirEntry aCur; + aCur.ToAbs(); + + for ( ; ! bFound && aCur.Level() > 1; aCur.CutName() ) + { + DirEntry aTest = aCur + DirEntry(PRJ_DIR_NAME) + DirEntry(DLIST_NAME); + if ( aTest.Exists() ) + { + if ( bAbs ) + return ByteString( aCur.GetFull(), RTL_TEXTENCODING_ASCII_US ); + else + return ByteString( aCur.GetName(), RTL_TEXTENCODING_ASCII_US ); + } + } + + return ""; +} +/*****************************************************************************/ +int SourceTreeLocalizer::GetFileCnt(){ +/*****************************************************************************/ + return nFileCnt; +} + +/*****************************************************************************/ +const ByteString SourceTreeLocalizer::GetProjectRootRel() +/*****************************************************************************/ +{ + ByteString sProjectRoot( GetProjectName( TRUE )); + DirEntry aCur; + aCur.ToAbs(); + ByteString sCur( aCur.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + if( sCur.SearchAndReplace( sProjectRoot, "" ) == STRING_NOTFOUND ) + return ""; + + ByteString sDelimiter( + DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + + sCur.SearchAndReplaceAll( sDelimiter, "/" ); + sCur.EraseLeadingChars( '/' ); + ULONG nCount = sCur.GetTokenCount( '/' ); + + ByteString sProjectRootRel; + for ( ULONG i = 0; i < nCount; i++ ) { + if ( sProjectRootRel.Len()) + sProjectRootRel += sDelimiter; + sProjectRootRel += ".."; + } + if ( sProjectRootRel.Len()) + return sProjectRootRel; + + return "."; +} + +bool skipProject( ByteString sPrj ) +{ + static const ByteString READLICENSE( "readlicense" ); + return sPrj.EqualsIgnoreCaseAscii( READLICENSE ); +} + +/*****************************************************************************/ +void SourceTreeLocalizer::WorkOnFile( + const ByteString &rFileName, const ByteString &rExecutable, + const ByteString &rParameter ) +/*****************************************************************************/ +{ + String sFull( rFileName, RTL_TEXTENCODING_ASCII_US ); + DirEntry aEntry( sFull ); + ByteString sFileName( aEntry.GetName(), RTL_TEXTENCODING_ASCII_US ); + + // set current working directory + DirEntry aPath( aEntry.GetPath()); + DirEntry aOldCWD; + aPath.SetCWD(); + + ByteString sPrj( GetProjectName()); + if ( sPrj.Len() && !skipProject( sPrj ) ) + { + ByteString sRoot( GetProjectRootRel()); + + DirEntry aTemp( Export::GetTempFile()); + ByteString sTempFile( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + ByteString sDel; +#if defined(WNT) || defined(OS2) + sDel=ByteString("\\"); +#else + sDel=ByteString("/"); +#endif + ByteString sPath1( Export::GetEnv("SOLARVER") ); + ByteString sPath2( Export::GetEnv("INPATH") ); + ByteString sPath3( "bin" ); + ByteString sPath4( Export::GetEnv("UPDMINOREXT") ); + ByteString sExecutable( sPath1 ); + sExecutable += sDel ; + sExecutable += sPath2 ; + sExecutable += sDel; + sExecutable += sPath3 ; + sExecutable += sPath4 ; + sExecutable += sDel ; + sExecutable += rExecutable ; + + + ByteString sCommand( sExecutable ); + sCommand += " "; + sCommand += rParameter; + sCommand += " -p "; + sCommand += sPrj; + sCommand += " -r "; + sCommand += sRoot; + sCommand += " -i "; + sCommand += sFileName; + sCommand += " -o "; + sCommand += sTempFile; + if ( sLanguageRestriction.Len()) { + sCommand += " -l "; + sCommand += getSourceLanguages( sLanguageRestriction , sCommand ); + } + + if( bQuiet2 ){ + sCommand +=" -QQ "; + } + //printf("DBG: %s\n",sCommand.GetBuffer()); + if (system(sCommand.GetBuffer()) == -1) + fprintf(stderr, "%s failed\n", sCommand.GetBuffer()); + nFileCnt++; + printf("."); + fflush( stdout ); + + SvFileStream aSDFIn( aTemp.GetFull(), STREAM_READ ); + ByteString sLine; + while ( aSDFIn.IsOpen() && !aSDFIn.IsEof()) { + aSDFIn.ReadLine( sLine ); + if ( sLine.Len()) { + aSDF.WriteLine( sLine ); + } + } + aSDFIn.Close(); + + aTemp.Kill(); + + } + // reset current working directory + aOldCWD.SetCWD(); +} + +ByteString SourceTreeLocalizer::getSourceLanguages( ByteString sLanguageRestriction_inout , ByteString sCommand ) +{ + // Source languages in helpcontent2 and macromigration en-US only! + if( sCommand.Search("helpex") != STRING_NOTFOUND ) { + sLanguageRestriction_inout.Assign( ByteString("en-US") ); + } + else if( sCommand.Search("xmlex") != STRING_NOTFOUND ){ + sLanguageRestriction_inout.Assign( ByteString("en-US") ); + } + return sLanguageRestriction_inout; +} + +/*****************************************************************************/ +BOOL SourceTreeLocalizer::CheckNegativeList( const ByteString &rFileName ) +/*****************************************************************************/ +{ + ULONG nIndex = 0; + BOOL bReturn = TRUE; + + ByteString sDelimiter( + DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + + ByteString sFileName( rFileName ); + sFileName.ToLowerAscii(); + + ByteString sNegative( NegativeList[ nIndex ] ); + while( !sNegative.Equals( "NULL" ) && bReturn ) { + sNegative.SearchAndReplaceAll( "\\", sDelimiter ); + sNegative.SearchAndReplaceAll( "/", sDelimiter ); + sNegative.ToLowerAscii(); + + if( sFileName.Search( sNegative ) == sFileName.Len() - sNegative.Len()) + bReturn = FALSE; + + nIndex++; + sNegative = NegativeList[ nIndex ]; + } + + return bReturn; +} + +/*****************************************************************************/ +BOOL SourceTreeLocalizer::CheckPositiveList( const ByteString &rFileName ) +/*****************************************************************************/ +{ + ULONG nIndex = 0; + BOOL bReturn = FALSE; + + ByteString sDelimiter( + DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + + ByteString sFileName( rFileName ); + sFileName.ToLowerAscii(); + + ByteString sNegative( PositiveList[ nIndex ] ); + while( !sNegative.Equals( "NULL" ) && !bReturn ) { + sNegative.SearchAndReplaceAll( "\\", sDelimiter ); + sNegative.SearchAndReplaceAll( "/", sDelimiter ); + sNegative.ToLowerAscii(); + + if( sFileName.Search( sNegative ) == sFileName.Len() - sNegative.Len()) + bReturn = TRUE; + + nIndex++; + sNegative = PositiveList[ nIndex ]; + } + + return bReturn; +} + +/*****************************************************************************/ +void SourceTreeLocalizer::WorkOnFileType( + const ByteString &rDirectory, const ByteString &rExtension, + const ByteString &rExecutable, const ByteString &rParameter, + const ByteString &rCollectMode +) +/*****************************************************************************/ +{ + String sWild( rDirectory, RTL_TEXTENCODING_ASCII_US ); + sWild += DirEntry::GetAccessDelimiter(); + sWild += String::CreateFromAscii( "*." ); + sWild += String( rExtension, RTL_TEXTENCODING_ASCII_US ); + + DirEntry aEntry( sWild ); + Dir aDir( sWild, FSYS_KIND_FILE ); + + for ( USHORT i = 0; i < aDir.Count(); i++ ) { + DirEntry aFile( aDir[ i ] ); + ByteString sFile( aFile.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + BOOL bAllowed = TRUE; + + if ( rCollectMode.Equals( "negative" )) + bAllowed = CheckNegativeList( sFile ); + else if ( rCollectMode.Equals( "positive" )) + bAllowed = CheckPositiveList( sFile ); + + if ( bAllowed ) + WorkOnFile( sFile, rExecutable, rParameter ); + } +} + +/*****************************************************************************/ +void SourceTreeLocalizer::WorkOnDirectory( const ByteString &rDirectory ) +/*****************************************************************************/ +{ + //printf("Working on Directory %s\n",rDirectory.GetBuffer()); + ULONG nIndex = 0; + ByteString sExtension( ExeTable[ nIndex ][ 0 ] ); + ByteString sExecutable( ExeTable[ nIndex ][ 1 ] ); + ByteString sParameter( ExeTable[ nIndex ][ 2 ] ); + ByteString sCollectMode( ExeTable[ nIndex ][ 3 ] ); + + while( !sExtension.Equals( "NULL" )) { + WorkOnFileType( + rDirectory, + sExtension, + sExecutable, + sParameter, + sCollectMode + ); + + nIndex++; + + sExtension = ExeTable[ nIndex ][ 0 ]; + sExecutable = ExeTable[ nIndex ][ 1 ]; + sParameter = ExeTable[ nIndex ][ 2 ]; + sCollectMode = ExeTable[ nIndex ][ 3 ]; + } +} + +void SourceTreeLocalizer::OnExecuteDirectory( const rtl::OUString &aDirectory ) +{ + ByteString rDirectory( rtl::OUStringToOString( aDirectory , RTL_TEXTENCODING_UTF8 , aDirectory.getLength() ) ) ; + if ( nMode == LOCALIZE_NONE ){ + if( !bQuiet2 ) fprintf( stdout, "%s\n", rDirectory.GetBuffer()); + } + else + WorkOnDirectory( rDirectory ); +} + +/*****************************************************************************/ +BOOL SourceTreeLocalizer::Extract( const ByteString &rDestinationFile ) +/*****************************************************************************/ +{ + nMode = LOCALIZE_EXTRACT; + + aSDF.Open( String( rDestinationFile , RTL_TEXTENCODING_ASCII_US ) , STREAM_STD_WRITE ); + aSDF.SetLineDelimiter( LINEEND_CRLF ); + + BOOL bReturn = aSDF.IsOpen(); + if ( bReturn ) { + aSDF.Seek( STREAM_SEEK_TO_END ); + bReturn = StartExecute(); + aSDF.Close(); + } + else{ + printf("ERROR: Can't create file %s\n", rDestinationFile.GetBuffer() ); + } + nMode = LOCALIZE_NONE; + aSDF.Close(); + return bReturn; +} + +/*****************************************************************************/ +BOOL SourceTreeLocalizer::MergeSingleFile( + const ByteString &rPrj, + const ByteString &rFile, + const ByteString &rSDFFile +) +/*****************************************************************************/ +{ + //printf("MergeSingleFile(%s,%s,%s)",rPrj.GetBuffer(),rFile.GetBuffer(),rSDFFile.GetBuffer()); + if ( !rFile.Len()) + return TRUE; + + ByteString sRoot( Export::GetEnv( "SRC_ROOT" )); + DirEntry aEntry( String( sRoot, RTL_TEXTENCODING_ASCII_US )); + aEntry += DirEntry( String( rPrj, RTL_TEXTENCODING_ASCII_US )); + + ByteString sDelimiter( + DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); + + ByteString sCur( rFile ); + sCur.SearchAndReplaceAll( "\\", sDelimiter ); + sCur.SearchAndReplaceAll( "/", sDelimiter ); + + aEntry += DirEntry( String( sCur, RTL_TEXTENCODING_ASCII_US )); + ByteString sFile( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + + ByteString sBCur( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); + if( !bQuiet2 ) fprintf( stdout, "##### %s #####\n", sBCur.GetBuffer()); + + ULONG nIndex = 0; + ByteString sExtension( aEntry.GetExtension(), RTL_TEXTENCODING_ASCII_US ); + ByteString sCandidate( ExeTable[ nIndex ][ 0 ] ); + + while( !sCandidate.Equals ("NULL") && !sCandidate.Equals(sExtension) ) + sCandidate = ExeTable[ ++nIndex ][ 0 ]; + + if ( !sCandidate.Equals( "NULL" ) ) { + if( !aEntry.Exists()) { + DirEntryKind theDir=FSYS_KIND_FILE; + Dir myDir( aEntry.GetPath(), theDir); + DirEntry current; + BOOL found=FALSE; + for( USHORT x=0; x < myDir.Count() && !found;){ + current=myDir[x++]; + StringCompare result=current.GetName().CompareIgnoreCaseToAscii( aEntry.GetName() ); + if( result==COMPARE_EQUAL ){ + fprintf(stderr,"WARNING: %s not found\n", ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US).GetBuffer() ); + fprintf(stderr,"but use %s instead \n" , ByteString(current.GetFull(), RTL_TEXTENCODING_ASCII_US).GetBuffer() ); + aEntry=current; + found=TRUE; + } + } + if(!found) return TRUE; + + } + + DirEntry aOut( Export::GetTempFile() ); + ByteString sOutput; + if( sOutputFile.Len() == 0 ) + sOutput = ByteString ( aOut.GetFull(), RTL_TEXTENCODING_ASCII_US ); + else + sOutput = sOutputFile; + ByteString sCommand( ExeTable[ nIndex ][ 1 ] ); + sCommand += " -i "; + sCommand += ByteString( aEntry.GetName(), RTL_TEXTENCODING_ASCII_US ); + sCommand += " -m "; + sCommand += rSDFFile; + sCommand += " -o "; + sCommand += sOutput; + sCommand += " "; + sCommand += ByteString( ExeTable[ nIndex ][ 2 ] ); + if ( sLanguageRestriction.Len()) { + sCommand += " -l "; + sCommand += sLanguageRestriction; + } + if( bQuiet2 ){ + sCommand +=" -QQ "; + } + + DirEntry aPath( aEntry.GetPath()); + DirEntry aOldCWD; + aPath.SetCWD(); + + if (system(sCommand.GetBuffer()) == -1) + fprintf(stderr, "%s failed\n", sCommand.GetBuffer()); + nFileCnt++; + printf("."); + //if( bQuiet2 ){ printf("."); } + SvFileStream aInStream( aOut.GetFull(), STREAM_READ ); + if ( !aInStream.IsOpen()) { + fprintf( stderr, + "ERROR: Unable to open file %s for reading!\n", + sOutput.GetBuffer()); + } + else { + FileStat::SetReadOnlyFlag( aEntry, FALSE ); + String myStr2(aEntry.GetFull()); + String aTemp22 = String::CreateFromAscii("_tmp"); + myStr2.Append(aTemp22); + + ByteString test(myStr2,RTL_TEXTENCODING_ASCII_US); + SvFileStream aOutStream( myStr2, STREAM_STD_WRITE | STREAM_TRUNC ); + if ( !aOutStream.IsOpen()) { + ByteString test2(myStr2,RTL_TEXTENCODING_ASCII_US); + fprintf( stderr,"ERROR: Unable to open file %s for modification!\n", test2.GetBuffer()); + aInStream.Close(); + } + + else { + ByteString sLine; + aOutStream.SetLineDelimiter( LINEEND_LF ); + + aInStream.ReadLine( sLine ); + while ( !aInStream.IsEof()) { + aOutStream.WriteLine( sLine ); + aInStream.ReadLine( sLine ); + } + aInStream.Close(); + aOutStream.Close(); + + + DirEntry myTempFile(ByteString(myStr2,RTL_TEXTENCODING_ASCII_US)); // xxx_tmp -> + DirEntry myFile(ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US));// xxx + + DirEntry oldFile(ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US)); + + if(oldFile.Kill()==ERRCODE_NONE){ + if(myTempFile.MoveTo(myFile)!=ERRCODE_NONE){ + fprintf( stderr, "ERROR: Can't rename file %s\n",ByteString(myStr2,RTL_TEXTENCODING_ASCII_US).GetBuffer()); + } + } + else{ + fprintf( stderr, "ERROR: Can't remove file %s\n",ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US).GetBuffer()); + } + } // else + + aOldCWD.SetCWD(); + aOut.Kill(); + } // else + } + return TRUE; +} +/*****************************************************************************/ +BOOL SourceTreeLocalizer::ExecuteMerge( ) +/*****************************************************************************/ +{ + DirEntry aEntry( Export::GetTempFile()); + BOOL bReturn = TRUE; + bool bMerged = false; + + ByteString sFileName; + ByteString sCurFile; + ByteString sLine; + ByteString sFileKey; + + SvFileStream aFile; + + ByteString sOutputFileName = sOutputFile; + ByteString sInpath("."); + sInpath += Export::GetEnv("INPATH"); + ByteString sBlank(""); + + sOutputFileName.SearchAndReplaceAll( sInpath , sBlank ); + + String sDel = DirEntry::GetAccessDelimiter(); + ByteString sBDel( sDel.GetBuffer() , sDel.Len() , RTL_TEXTENCODING_UTF8 ); + if( bLocal ){ + xub_StrLen nPos = sOutputFileName.SearchBackward( sBDel.GetChar(0) ); + sOutputFileName = sOutputFileName.Copy( nPos+1 , sOutputFileName.Len()-nPos-1 ); + } + ByteStringBoolHashMap aFileHM; + // Read all possible files + while ( !aSDF.IsEof()) { + aSDF.ReadLine( sLine ); + sFileName = sLine.GetToken( 0, '\t' ); + sFileName += "#"; + sFileName += sLine.GetToken( 1, '\t' ); + aFileHM[sFileName]=true; + } + + for( ByteStringBoolHashMap::iterator iter = aFileHM.begin(); iter != aFileHM.end(); ++iter ){ + sFileKey = iter->first; + aSDF.Seek( 0 ); + aFile.Open( aEntry.GetFull(), STREAM_STD_WRITE |STREAM_TRUNC ); + + while ( !aSDF.IsEof()) { + aSDF.ReadLine( sLine ); + sFileName = sLine.GetToken( 0, '\t' ); + sFileName += "#"; + sFileName += sLine.GetToken( 1, '\t' ); + if( sFileName.Len() && ( sFileName.CompareTo(sFileKey) == COMPARE_EQUAL ) ){ + if ( aFile.IsOpen() && sLine.Len()) + aFile.WriteLine( sLine ); + } + } + if ( aFile.IsOpen()) + aFile.Close(); + + ByteString sPrj( sFileKey.GetToken( 0, '#' )); + ByteString sFile( sFileKey.GetToken( 1, '#' )); + ByteString sSDFFile( aFile.GetFileName(), RTL_TEXTENCODING_ASCII_US ); + + //printf("localize test sPrj = %s , sFile = %s , sSDFFile = %s sOutputFileName = %s\n",sPrj.GetBuffer(), sFile.GetBuffer() , sSDFFile.GetBuffer() , sOutputFileName.GetBuffer() ); + + // Test + bLocal = true; + // Test + + if( bLocal ){ + USHORT nPos = sFile.SearchBackward( '\\' ); + ByteString sTmp = sFile.Copy( nPos+1 , sFile.Len()-nPos-1 ); + //printf("'%s'='%s'\n",sTmp.GetBuffer(), sOutputFileName.GetBuffer()); + if( sTmp.CompareTo(sOutputFileName) == COMPARE_EQUAL ){ + bMerged = true; + if ( !MergeSingleFile( sPrj, sFile, sSDFFile )) + bReturn = FALSE; + }else{ + bMerged = true; + //printf("MergeSingleFile('%s','%s','%s')\n",sPrj.GetBuffer(),sFile.GetBuffer(),sSDFFile.GetBuffer()); + if ( !MergeSingleFile( sPrj, sFile, sSDFFile )) + bReturn = FALSE; + } + } + } + aEntry.Kill(); + // If Outputfile not included in the SDF file copy it without merge + + if( bLocal && !bMerged ){ + DirEntry aSourceFile( sOutputFileName.GetBuffer() ); + FSysError aErr = aSourceFile.CopyTo( DirEntry ( sOutputFile.GetBuffer() ) , FSYS_ACTION_COPYFILE ); + if( aErr != FSYS_ERR_OK ){ + printf("ERROR: Can't copy file '%s' to '%s' %d\n",sOutputFileName.GetBuffer(),sOutputFile.GetBuffer(),sal::static_int_cast(aErr)); + } + } + return bReturn; + +} + +/*****************************************************************************/ +BOOL SourceTreeLocalizer::Merge( const ByteString &rSourceFile , const ByteString &rOutput ) +/*****************************************************************************/ +{ + sOutputFile = rOutput; + nMode = LOCALIZE_MERGE; + aSDF.Open( String( rSourceFile, RTL_TEXTENCODING_ASCII_US ), + STREAM_STD_READ ); + + BOOL bReturn = aSDF.IsOpen(); + if ( bReturn ) { + bReturn = ExecuteMerge(); +// aSDF.Close(); + } + aSDF.Close(); + nMode = LOCALIZE_NONE; + return bReturn; +} + +} +using namespace transex3; + +#define STATE_NONE 0x0000 +#define STATE_EXPORT 0x0001 +#define STATE_MERGE 0x0002 +#define STATE_ISOCODE 0x0003 +#define STATE_LANGUAGES 0x0004 +#define STATE_FILENAME 0x0005 +#define STATE_OUTPUT 0x0006 + +/*****************************************************************************/ +void Help() +/*****************************************************************************/ +{ + fprintf( stdout, + "localize (c)2001 by Sun Microsystems\n" + "====================================\n" ); + fprintf( stdout, + "As part of the L10N framework, localize extracts and merges translations\n" + "out of and into the whole source tree.\n\n" + "Syntax: localize -e -l en-US -f FileName [-QQ]\n" + "Parameter:\n" + "\t-e: Extract mode\n" + "\tFileName: Output file when extract mode, input file when merge mode\n" + "\tl1...ln: supported languages (\"all\" for all languages).\n" + "\tQQ: quiet output)" + ); + + fprintf( stdout, + "Valid language codes for l1...ln and f1...fn are:\n" ); + fprintf( stdout, + "\nExample 1:\n" + "==========\n" + "localize -e -l en-US -f MyFile\n\n" + "All strings will be extracted for language de and language en-US.\n" + ); +} + +/*****************************************************************************/ +int Error() +/*****************************************************************************/ +{ + Help(); + return 1; +} + +/*****************************************************************************/ +BOOL CheckLanguages( ByteString &rLanguages ) +/*****************************************************************************/ +{ + ByteString sTmp( rLanguages ); + return true; +} + +/*****************************************************************************/ +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + String sTempBase( String::CreateFromAscii( "loc" )); + DirEntry::SetTempNameBase( sTempBase ); + USHORT nState = STATE_NONE; + + BOOL bExport = FALSE; + BOOL bMerge = FALSE; + bool bQuiet = false; + bool bQuiet2 = false; + bool bSkipLinks = false; + + ByteString sLanguages; + ByteString sFileName; + ByteString sOutput; + + bQuiet2 = true; + bExport = TRUE; + + for( int i = 1; i < argc; i++ ) { + ByteString sSwitch( argv[ i ] ); + sSwitch.ToUpperAscii(); + + if ( sSwitch.Equals( "-E" )) { + nState = STATE_EXPORT; + if ( bMerge ) + return Error(); + bExport = TRUE; + } + else if( sSwitch.Equals( "-Q" )) { + bQuiet = true; + } + else if ( sSwitch.Equals( "-I" ) ) + nState = STATE_ISOCODE; + else if ( sSwitch.Equals( "-L" ) ) + nState = STATE_LANGUAGES; + else if ( sSwitch.Equals( "-F" ) ) + nState = STATE_FILENAME; + else if ( sSwitch.Equals( "-QQ" )) + bQuiet2 = true; + else if ( ByteString( argv[ i ]).ToUpperAscii().Equals( "-O" ) ) + nState = STATE_OUTPUT; + else { + switch ( nState ) { + case STATE_NONE: + return Error(); + case STATE_OUTPUT: + if ( sOutput.Len()) + return Error(); + sOutput = ByteString( argv[ i ] ); + nState = STATE_NONE; + break; + case STATE_LANGUAGES: + if ( sLanguages.Len()) + return Error(); + sLanguages = ByteString( argv[ i ] ); + nState = STATE_NONE; + break; + case STATE_FILENAME: + if ( sFileName.Len()) + return Error(); + sFileName = ByteString( argv[ i ] ); + nState = STATE_NONE; + break; + default: + return Error(); + } + } + } + if ( !bMerge && !bExport ) { + Help(); + return 1; + } + + ByteString sSolarVer( Export::GetEnv( "WORK_STAMP" )); + ByteString sVersion( Export::GetEnv( "WORK_STAMP" )); + + if ( !sSolarVer.Len() || !sVersion.Len()) { + fprintf( stderr, "ERROR: No environment set!\n" ); + return 1; + } + + if ( !CheckLanguages( sLanguages )) + return 2; + + if ( !sFileName.Len()) { + fprintf( stderr, "ERROR: No filename given\n" ); + return 3; + } + + DirEntry aEntry( String( sFileName , RTL_TEXTENCODING_ASCII_US )); + aEntry.ToAbs(); + String sFullEntry = aEntry.GetFull(); + ByteString sFileABS( aEntry.GetFull(), gsl_getSystemTextEncoding()); + //printf("B %s\nA %s\n",rDestinationFile.GetBuffer(), sFile.GetBuffer()); + sFileName = sFileABS; + + Treeconfig treeconfig; + vector repos; + bool hasPwd = treeconfig.getActiveRepositories( repos ); + if( hasPwd ) cout << "Found special path!\n"; + + string minor_ext; + bool has_minor_ext; + + if( Export::GetEnv("UPDMINOREXT") != NULL ) + { + minor_ext = string( Export::GetEnv("UPDMINOREXT") ); + has_minor_ext = minor_ext.size(); + } + else + has_minor_ext = false; + + // localize through all repositories + for( vector::iterator iter = repos.begin(); iter != repos.end() ; ++iter ) + { + string curRepository; + if( has_minor_ext ) + curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter + minor_ext; + else + curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter; + cout << "Localizing repository " << curRepository << "\n"; + SourceTreeLocalizer aIter( ByteString( curRepository.c_str() ) , sVersion , (sOutput.Len() > 0) , bQuiet2 , bSkipLinks ); + aIter.SetLanguageRestriction( sLanguages ); + if ( bExport ){ + if( bQuiet2 ){ /*printf("");*/fflush( stdout );} + aIter.Extract( sFileName ); + if( bQuiet2 ){ printf("\n %d files found!\n",aIter.GetFileCnt());} + } + } + if( hasPwd ) + { + string pwd; + Export::getCurrentDir( pwd ); + cout << "Localizing repository " << pwd << "\n"; + SourceTreeLocalizer aIter( ByteString( pwd.c_str() ) , sVersion , (sOutput.Len() > 0) , bQuiet2 , bSkipLinks ); + aIter.SetLanguageRestriction( sLanguages ); + if ( bExport ){ + if( bQuiet2 ){ /*printf("");*/fflush( stdout );} + aIter.Extract( sFileName ); + if( bQuiet2 ){ printf("\n %d files found!\n",aIter.GetFileCnt());} + } + + } + + return 0; +} + diff --git a/l10ntools/source/makefile.mk b/l10ntools/source/makefile.mk new file mode 100644 index 000000000000..fe4ecc919179 --- /dev/null +++ b/l10ntools/source/makefile.mk @@ -0,0 +1,210 @@ +#************************************************************************* +# +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# Copyright 2008 by Sun Microsystems, Inc. +# +# OpenOffice.org - a multi-platform office productivity suite +# +# $RCSfile: makefile.mk,v $ +# +# $Revision: 1.46 $ +# +# This file is part of OpenOffice.org. +# +# OpenOffice.org is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 +# only, as published by the Free Software Foundation. +# +# OpenOffice.org is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License version 3 for more details +# (a copy is included in the LICENSE file that accompanied this code). +# +# You should have received a copy of the GNU Lesser General Public License +# version 3 along with OpenOffice.org. If not, see +# +# for a copy of the LGPLv3 License. +# +#************************************************************************* + +PRJ=.. + +INCPRE=$(MISC) + +PRJNAME=l10ntools +TARGET=transex +TARGETTYPE=CUI +LIBTARGET=no +# --- Settings ----------------------------------------------------- +ENABLE_EXCEPTIONS=TRUE + +.INCLUDE : settings.mk +CDEFS+= -DYY_NEVER_INTERACTIVE=1 +#CDEFS+= -pg + +.IF "$(SYSTEM_EXPAT)" == "YES" +CFLAGS+=-DSYSTEM_EXPAT +.ENDIF + + +# --- Files -------------------------------------------------------- + +OBJFILES= \ + $(OBJ)$/export.obj \ + $(OBJ)$/export2.obj \ + $(OBJ)$/merge.obj \ + $(OBJ)$/srciter.obj \ + $(OBJ)$/utf8conv.obj \ + $(OBJ)$/xmlparse.obj \ + $(OBJ)$/helpmerge.obj \ + $(OBJ)$/helpex.obj \ + $(OBJ)$/file.obj \ + $(OBJ)$/directory.obj + + +LIB1TARGET= $(LB)$/$(TARGET).lib +LIB1ARCHIV= $(LB)$/libtransex.a +#LIB1FILES= $(LB)$/transex3.lib +LIB1OBJFILES= $(OBJ)$/export.obj \ + $(OBJ)$/export2.obj \ + $(OBJ)$/merge.obj \ + $(OBJ)$/srciter.obj \ + $(OBJ)$/file.obj \ + $(OBJ)$/directory.obj \ + $(OBJ)$/utf8conv.obj + + +APP1VERSIONMAP=exports.map + +# extractor and merger for *.src and *.hrc +APP1TARGET= transex3 +#APP1OBJS= $(OBJ)$/src_yy.obj +APP1OBJS= $(OBJ)$/src_yy_wrapper.obj + +APP1STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) + +.IF "$(OS)"=="MACOSX" +# static libs at end for OS X +.ENDIF + +APP1LIBS+= $(LB)$/$(TARGET).lib +APP1DEPN= $(OBJ)$/src_yy_wrapper.obj $(LB)$/$(TARGET).lib + +APP2TARGET= helpex +APP2OBJS= $(OBJ)$/helpmerge.obj $(OBJ)$/xmlparse.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj $(OBJ)$/merge.obj $(OBJ)$/helpex.obj +APP2RPATH= NONE + +.IF "$(OS)"!="MACOSX" +.ENDIF + +APP2STDLIBS+=$(SALLIB) $(EXPATASCII3RDLIB) $(TOOLSLIB) $(VOSLIB) + +.IF "$(OS)"=="MACOSX" +# static libs at end for OS X +.ENDIF + +# extractor and merger for *.lng and *.lng +APP3TARGET= ulfex +APP3OBJS= $(OBJ)$/lngmerge.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/lngex.obj $(OBJ)$/utf8conv.obj +APP3RPATH= NONE + +.IF "$(OS)"!="MACOSX" +#APP3STDLIBS+= $(BTSTRPLIB) +.ENDIF +APP3STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) +.IF "$(OS)"=="MACOSX" +# static libs at end for OS X +.ENDIF + +# encoding converter for *.gsi +APP4TARGET= gsiconv +APP4OBJS= $(OBJ)$/utf8conv.obj $(OBJ)$/gsiconv.obj +APP4STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) + +# tag checker for *.gsi +APP5TARGET= gsicheck +APP5OBJS= $(OBJ)$/gsicheck.obj $(OBJ)$/tagtest.obj +APP5STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) + +# extractor and merger for *.cfg +APP6TARGET= cfgex +APP6OBJS= $(OBJ)$/cfgmerge.obj $(OBJ)$/cfg_yy_wrapper.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj + +.IF "$(OS)"!="MACOSX" +#APP6STDLIBS+= $(BTSTRPLIB) +.ENDIF + +APP6STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) + +.IF "$(OS)"=="MACOSX" +# static libs at end for OS X +.ENDIF + +# extractor and merger for *.xrm +APP7TARGET= xrmex +APP7OBJS= $(OBJ)$/xrmmerge.obj $(OBJ)$/xrm_yy_wrapper.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj +APP7RPATH= NONE + +.IF "$(OS)"!="MACOSX" +.ENDIF + +APP7STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(SALLIB) + +.IF "$(OS)"=="MACOSX" +# static libs at end for OS X +.ENDIF + +# +#APP8TARGET= treeconfig +#APP8OBJS= $(OBJ)$/treeconfig.obj $(OBJ)$/inireader.obj $(OBJ)$/export2.obj +#APP8STDLIBS=$(TOOLSLIB) $(SALLIB) $(VOSLIB) $(ICUINLIB) $(STLPORT) + +# localizer for l10n framework +APP9TARGET= localize_sl +EXCEPTIONSFILES= \ + $(OBJ)$/localize.obj +APP9OBJS= $(OBJ)$/localize.obj $(OBJ)$/utf8conv.obj $(OBJ)$/srciter.obj $(OBJ)$/export2.obj $(OBJ)$/file.obj $(OBJ)$/directory.obj $(OBJ)$/treeconfig.obj $(OBJ)$/inireader.obj + +APP9STDLIBS+= \ + $(TOOLSLIB) \ + $(VOSLIB) \ + $(ICUINLIB) \ + $(ICUUCLIB) \ + $(STLPORTLIB) \ + $(SALLIB) + +DEPOBJFILES=$(APP1OBJS) $(APP2OBJS) $(APP3OBJS) $(APP4OBJS) $(APP5OBJS) $(APP6OBJS) $(APP7OBJS) $(APP8OBJS) $(APP9OBJS) + +# --- Targets ------------------------------------------------------ + +.INCLUDE : target.mk + +$(MISC)$/%_yy.c : %lex.l + flex -l -w -8 -o$@ $< + +# Helper to suppress warnings in lex generated c code, see #i57362# + +$(OBJ)$/src_yy_wrapper.obj: $(MISC)$/src_yy.c +$(OBJ)$/cfg_yy_wrapper.obj: $(MISC)$/cfg_yy.c +$(OBJ)$/xrm_yy_wrapper.obj: $(MISC)$/xrm_yy.c + diff --git a/l10ntools/source/merge.cxx b/l10ntools/source/merge.cxx new file mode 100644 index 000000000000..42f539065651 --- /dev/null +++ b/l10ntools/source/merge.cxx @@ -0,0 +1,445 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: merge.cxx,v $ + * $Revision: 1.27.36.3 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include +#include "export.hxx" +#include "utf8conv.hxx" +#include + +using namespace std; + +extern void ConvertHalfwitdhToFullwidth( String& rString ); + +// +// class PFormEntrys +// + +ByteString PFormEntrys::Dump(){ + ByteString sRet( "PFormEntrys\n" ); + //sRet.Append( Export::DumpMap( ByteString("sText") , sText ) ); + //sRet.Append("\n"); + ByteString a("sText"); + if ( sText.size() ) Export::DumpMap( a , sText ); + return sRet; +} + +/*****************************************************************************/ +BOOL PFormEntrys::GetText( ByteString &rReturn, + USHORT nTyp, const ByteString &nLangIndex, BOOL bDel ) +/*****************************************************************************/ +{ + + /*printf("DBG: PFormEntrys::GetText(nId=%s)\n",nLangIndex.GetBuffer() ); + + // DEBUG****************** + ByteStringHashMap::const_iterator idbg; + std::cout << "HASHKEYS : \n"; + for( idbg = sText.begin() ; idbg != sText.end(); ++idbg ) + std::cout << (idbg->first).GetBuffer() << "\n"; + std::cout << "\n\n"; + std::cout << "String sText[ nLangIndex ] = " << sText[ nLangIndex ].GetBuffer() << "\n"; + // DEBUG****************** +*/ + + BOOL bReturn=TRUE; + switch ( nTyp ) { + case STRING_TYP_TEXT : + rReturn = sText[ nLangIndex ]; + if ( bDel ) + sText[ nLangIndex ] = ""; + bReturn = bTextFirst[ nLangIndex ]; + bTextFirst[ nLangIndex ] = FALSE; + break; + case STRING_TYP_HELPTEXT : + rReturn = sHelpText; + break; + case STRING_TYP_QUICKHELPTEXT : + rReturn = sQuickHelpText[ nLangIndex ]; + if ( bDel ) + sQuickHelpText[ nLangIndex ] = ""; + bReturn = bQuickHelpTextFirst[ nLangIndex ]; + bQuickHelpTextFirst[ nLangIndex ] = FALSE; + break; + case STRING_TYP_TITLE : + rReturn = sTitle[ nLangIndex ]; + if ( bDel ) + sTitle[ nLangIndex ] = ""; + bReturn = bTitleFirst[ nLangIndex ]; + bTitleFirst[ nLangIndex ] = FALSE; + break; + } + //printf("Returning '%s'\n",rReturn.GetBuffer()); + return bReturn; +} + + +// +// class MergeData +// + +/*****************************************************************************/ +MergeData::~MergeData() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +PFormEntrys* MergeData::GetPFormEntrys( ResData *pResData ) +/*****************************************************************************/ +{ + + (void) pResData; // FIXME + if( aMap.find( ByteString("HACK") ) != aMap.end() ){ + return aMap[ ByteString("HACK") ]; + } + else{ + return 0; + } +} + +void MergeData::Insert( const ByteString& rPFO , PFormEntrys* pfEntrys ){ + (void) rPFO; // FIXME + aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) ); + +} +ByteString MergeData::Dump(){ + ByteString sRet( "MergeData\n" ); + + printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",sTyp.GetBuffer(),sGID.GetBuffer(),sLID.GetBuffer(), sFilename.GetBuffer() ); + + PFormEntrysHashMap::const_iterator idbg; + for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ + printf("aMap[ %s ] = " ,idbg->first.GetBuffer()); + ( (PFormEntrys*)(idbg->second) )->Dump(); + printf("\n") ; + } + printf("\n") ; + return sRet; +} + +PFormEntrys* MergeData::GetPFObject( const ByteString& rPFO ){ + if( aMap.find( ByteString("HACK") ) != aMap.end() ){ + return aMap[ rPFO ]; + } + else{ + return 0; + } +} + + +/*****************************************************************************/ +PFormEntrys *MergeData::InsertEntry( const ByteString &rPForm ) +/*****************************************************************************/ +{ + PFormEntrys* pFEntrys = new PFormEntrys( rPForm ); + aMap.insert( PFormEntrysHashMap::value_type( rPForm , pFEntrys ) ); + return pFEntrys; +} + +/*****************************************************************************/ +BOOL MergeData::operator==( ResData *pData ) +/*****************************************************************************/ +{ + ByteString sResTyp_upper( pData->sResTyp ); + sResTyp_upper.ToUpperAscii(); + ByteString sTyp_upper( sTyp ); + sTyp_upper.ToUpperAscii(); + + return (( pData->sId == sLID ) && + ( pData->sGId == sGID ) && + ( sResTyp_upper == sTyp_upper ) + ); +} + +// +// class MergeDataFile +// + +#define FFORMAT_UNKNOWN 0x0000 +#define FFORMAT_NEW 0x0001 +#define FFORMAT_OLD 0x0002 + +/*****************************************************************************/ +MergeDataFile::MergeDataFile( const ByteString &rFileName, const ByteString& sFile ,BOOL bErrLog, +// CharSet aCharSet, BOOL bUTF8 , bool bCaseSensitive ) + CharSet aCharSet, bool bCaseSensitive ) + +/*****************************************************************************/ + : bErrorLog( bErrLog ) +{ + + SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); + aInputStream.SetStreamCharSet( aCharSet ); + ByteString sLine; +// printf("\nReading localize.sdf ...\n"); + ByteString sTYP; + ByteString sGID; + ByteString sLID; + ByteString sPFO; + ByteString nLANG; + ByteString sTEXT; + ByteString sQHTEXT; + ByteString sTITLE; + ByteString sHACK("HACK"); + + const ByteString sEmpty(""); + + if( !aInputStream.IsOpen() ) { + printf("Warning : Can't open %s\n", rFileName.GetBuffer()); + //exit( -1 ); + return; + } + while ( !aInputStream.IsEof()) { + xub_StrLen nToks; + aInputStream.ReadLine( sLine ); + sLine = sLine.Convert( RTL_TEXTENCODING_MS_1252, aCharSet ); + + nToks = sLine.GetTokenCount( '\t' ); + if ( nToks == 15 ) { + // Skip all wrong filenames + ByteString filename = sLine.GetToken( 1 , '\t' ); + filename = filename.Copy( filename.SearchCharBackward( "\\" )+1 , filename.Len() ); + + if( sFile.Equals( sEmpty ) || ( !sFile.Equals( sEmpty ) && filename.Equals( sFile ) ) ) + { + xub_StrLen rIdx = 0; + sTYP = sLine.GetToken( 3, '\t', rIdx ); + sGID = sLine.GetToken( 0, '\t', rIdx ); // 4 + sLID = sLine.GetToken( 0, '\t', rIdx ); // 5 + sPFO = sLine.GetToken( 1, '\t', rIdx ); // 7 + sPFO = sHACK; + nLANG = sLine.GetToken( 1, '\t', rIdx ); // 9 + sTEXT = sLine.GetToken( 0, '\t', rIdx ); // 10 + + sQHTEXT = sLine.GetToken( 1, '\t', rIdx ); // 12 + sTITLE = sLine.GetToken( 0, '\t', rIdx ); // 13 + + nLANG.EraseLeadingAndTrailingChars(); + +#ifdef MERGE_SOURCE_LANGUAGES + if( true ){ +#else + if ( !nLANG.EqualsIgnoreCaseAscii("en-US") ){ +#endif + ByteStringHashMap::const_iterator lit; + lit = aLanguageMap.find (nLANG); + ByteString aLANG; + if (lit == aLanguageMap.end()) { + aLANG = nLANG; + aLanguageMap.insert( ByteStringHashMap::value_type( aLANG, aLANG ) ); + // Remember read languages for -l all switch + aLanguageList.push_back( nLANG ); + } else + aLANG = lit->first; + + InsertEntry( sTYP, sGID, sLID, sPFO, aLANG, sTEXT, sQHTEXT, sTITLE , filename , bCaseSensitive ); + } + } + } + else if ( nToks == 10 ) { + printf("ERROR: File format is obsolete and no longer supported!\n"); + } + } + aInputStream.Close(); +} +/*****************************************************************************/ +MergeDataFile::~MergeDataFile() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +//void MergeDataFile::WriteErrorLog( const ByteString &rFileName ) +/*****************************************************************************/ +//{ +// DEAD +//} + +ByteString MergeDataFile::Dump(){ + ByteString sRet( "MergeDataFile\n" ); + + //sRet.Append( Export::DumpMap( "aLanguageSet" , aLanguageSet ) ); + //sRet.Append( Export::DumpMap( "aLanguageList" , aLanguageList ) ); + printf("MergeDataFile\n"); + MergeDataHashMap::const_iterator idbg; + for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ + /*sRet.Append( "aMap[" ); + sRet.Append( idbg->first ); + sRet.Append( "]= " ); + sRet.Append( ((MergeData*) (idbg->second))->Dump() ); + sRet.Append("\n");*/ + + printf("aMap[ %s ] = ",idbg->first.GetBuffer()); + ((MergeData*) (idbg->second))->Dump(); + printf("\n"); + } + printf("\n"); + //sRet.Append("\n"); + return sRet; +} + +/*****************************************************************************/ +void MergeDataFile::WriteError( const ByteString &rLine ) +/*****************************************************************************/ +{ + if ( bErrorLog ) { + if ( !aErrLog.IsOpen()) + aErrLog.Open( String( sErrorLog, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); + aErrLog.WriteLine( rLine ); + } + else + fprintf( stderr, "%s\n", rLine.GetBuffer()); +} +std::vector MergeDataFile::GetLanguages(){ + return aLanguageList; +} + +/*****************************************************************************/ +MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive ) +/*****************************************************************************/ +{ + ByteString sOldG = pResData->sGId; + ByteString sOldL = pResData->sId; + ByteString sGID = pResData->sGId; + ByteString sLID; + if ( !sGID.Len()) + sGID = pResData->sId; + else + sLID = pResData->sId; + pResData->sGId = sGID; + pResData->sId = sLID; + + ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive ); + + //printf("DBG: Searching [%s]\n",sKey.GetBuffer()); + if( aMap.find( sKey ) != aMap.end() ){ + pResData->sGId = sOldG; + pResData->sId = sOldL; + //printf("DBG: Found[%s]\n",sKey.GetBuffer()); + return aMap[ sKey ]; + } + pResData->sGId = sOldG; + pResData->sId = sOldL; + //printf("DBG: Found[%s]\n",sKey.GetBuffer()); + return NULL; +} + + +/*****************************************************************************/ +PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData ) +/*****************************************************************************/ +{ + // search for requested PFormEntrys + MergeData *pData = GetMergeData( pResData ); + if ( pData ) + return pData->GetPFormEntrys( pResData ); + return NULL; +} + +/*****************************************************************************/ +PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData ) +/*****************************************************************************/ +{ + // search for requested PFormEntrys + MergeData *pData = GetMergeData( pResData , true ); + if ( pData ) + return pData->GetPFormEntrys( pResData ); + return NULL; +} +/*****************************************************************************/ +void MergeDataFile::InsertEntry( + const ByteString &rTYP, const ByteString &rGID, + const ByteString &rLID, const ByteString &rPFO, + const ByteString &nLANG, const ByteString &rTEXT, + const ByteString &rQHTEXT, const ByteString &rTITLE , + const ByteString &rInFilename , bool bCaseSensitive + ) +/*****************************************************************************/ +{ + MergeData *pData; + BOOL bFound = FALSE; + + // uniquify the filename to save memory. + ByteStringHashMap::const_iterator fit = aFilenames.find (rInFilename); + ByteString aFilename; + if (fit == aFilenames.end()) { + aFilename = rInFilename; + aFilenames.insert (ByteStringHashMap::value_type (aFilename, aFilename)); + } else + aFilename = fit->first; + + // search for MergeData + + ByteString sKey = CreateKey( rTYP , rGID , rLID , aFilename , bCaseSensitive ); + MergeDataHashMap::const_iterator mit; + mit = aMap.find( sKey ); + if( mit != aMap.end() ){ + pData = mit->second; + }else{ + pData = new MergeData( rTYP, rGID, rLID, aFilename ); + aMap.insert( MergeDataHashMap::value_type( sKey, pData ) ); + } + + bFound = FALSE; + PFormEntrys *pFEntrys = 0; + + // search for PFormEntrys + + pFEntrys = pData->GetPFObject( rPFO ); + if( !pFEntrys ){ + // create new PFormEntrys, cause no one exists with current properties + pFEntrys = new PFormEntrys( rPFO ); + pData->Insert( rPFO , pFEntrys ); + } + + // finaly insert the cur string + + pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE ); + + //printf("DBG: MergeDataFile::Insert[]=( sKey=%s,nLang=%s,rTEXT=%s)\n",sKey2.GetBuffer(),nLANG.GetBuffer(),rTEXT.GetBuffer()); +} +ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive ){ + + ByteString sKey( rTYP ); + sKey.Append( '-' ); + sKey.Append( rGID ); + sKey.Append( '-' ); + sKey.Append( rLID ); + sKey.Append( '-' ); + sKey.Append( rFilename ); + + if( bCaseSensitive ) return sKey; // officecfg case sensitive identifier + else return sKey.ToUpperAscii(); +} + + diff --git a/l10ntools/source/src_yy_wrapper.c b/l10ntools/source/src_yy_wrapper.c new file mode 100644 index 000000000000..d326b9a94e86 --- /dev/null +++ b/l10ntools/source/src_yy_wrapper.c @@ -0,0 +1,2 @@ +// Helper to suppress warnings in lex generated c code, see #i57362# +#include "src_yy.c" diff --git a/l10ntools/source/srciter.cxx b/l10ntools/source/srciter.cxx new file mode 100644 index 000000000000..cf04de4bf3fa --- /dev/null +++ b/l10ntools/source/srciter.cxx @@ -0,0 +1,141 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: srciter.cxx,v $ + * $Revision: 1.14 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" + +#include "srciter.hxx" +#include +#include + +// +// class SourceTreeIterator +// + +/*****************************************************************************/ +SourceTreeIterator::SourceTreeIterator( + const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in ) +/*****************************************************************************/ + : bInExecute( FALSE ) , bLocal( bLocal_in ) +{ + (void) rVersion ; + + if(!bLocal){ + rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 ); + aRootDirectory = transex::Directory( sRootDirectory ); + } +} + +/*****************************************************************************/ +SourceTreeIterator::~SourceTreeIterator() +/*****************************************************************************/ +{ +} + +/*****************************************************************************/ +void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory ) +/*****************************************************************************/ +{ + if ( bInExecute ) { + rtl::OUString sDirName = aDirectory.getDirectoryName(); + + static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) ); + static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) ); + static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) ); + static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) ); + static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) ); + static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) ); + static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) ); + + + if( sDirName.indexOf( WCARD1 , 0 ) > -1 || + sDirName.indexOf( WCARD2 , 0 ) > -1 || + sDirName.indexOf( WCARD3 , 0 ) > -1 || + sDirName.indexOf( WCARD4 , 0 ) > -1 || + sDirName.indexOf( WCARD5 , 0 ) > -1 || + sDirName.indexOf( WCARD6 , 0 ) > -1 || + sDirName.indexOf( WCARD7 , 0 ) > -1 + ) return; + //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); + + rtl::OUString sDirNameTmp = aDirectory.getFullName(); + ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); + +#ifdef WNT + sDirNameTmpB.Append( ByteString("\\no_localization") ); +#else + sDirNameTmpB.Append( ByteString("/no_localization") ); +#endif + //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); + + DirEntry aDE( sDirNameTmpB.GetBuffer() ); + if( aDE.Exists() ) + { + //printf("#### no_localization file found ... skipping"); + return; + } + + aDirectory.setSkipLinks( bSkipLinks ); + aDirectory.readDirectory(); + OnExecuteDirectory( aDirectory.getFullName() ); + if ( aDirectory.getSubDirectories().size() ) + for ( ULONG i=0;i < aDirectory.getSubDirectories().size();i++ ) + ExecuteDirectory( aDirectory.getSubDirectories()[ i ] ); + } +} + +/*****************************************************************************/ +BOOL SourceTreeIterator::StartExecute() +/*****************************************************************************/ +{ + + bInExecute = TRUE; // FIXME + ExecuteDirectory( aRootDirectory ); + + if ( bInExecute ) { // FIXME + bInExecute = FALSE; + return TRUE; + } + return FALSE; +} + +/*****************************************************************************/ +void SourceTreeIterator::EndExecute() +/*****************************************************************************/ +{ + bInExecute = FALSE; +} + +/*****************************************************************************/ +void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory ) +/*****************************************************************************/ +{ + fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() ); +} diff --git a/l10ntools/source/srclex.l b/l10ntools/source/srclex.l new file mode 100644 index 000000000000..fef251e47224 --- /dev/null +++ b/l10ntools/source/srclex.l @@ -0,0 +1,308 @@ + +%{ +/* + * lexer for parsing ressource source files (*.src) + * + */ + + +/* enlarge token buffer to tokenize whole strings */ +#undef YYLMAX +#define YYLMAX 64000 + +/* to enable debug output define LEXDEBUG */ +#define LEXDEBUG 1 +#ifdef LEXDEBUG +#define OUTPUT fprintf +#else +#define OUTPUT(Par1,Par2); +#endif + +/* table of possible token ids */ +#include "tokens.h" +#include +#include + +#if defined __GNUC__ +#pragma GCC system_header +#elif defined __SINPRO_CC +#pragma disable_warn +#elif defined _MSC_VER +#pragma warning(push, 1) +#endif + +/* external functions (C++ code, declared as extren "C" */ +extern int WorkOnTokenSet( int, char* ); +extern int InitExport( char * , char * ); +extern int Parse( int nTyp, char *pTokenText ); +extern int EndExport(); +extern int SetError(); +extern int GetError(); +extern char *GetOutputFile( int argc, char* argv[]); +extern FILE *GetNextFile(); +extern int isQuiet(); +extern void Close(); +extern char* getFilename(); + +/* forwards */ +void YYWarning(); +%} + +%p 24000 +%e 1200 +%n 500 + +%% + +^[\t ]*"#pragma".* { + WorkOnTokenSet( PRAGMA, yytext ); +} + +^[ \t]*\n { + WorkOnTokenSet( EMPTYLINE, yytext ); +} + +[\t ]+ | +^[\t ]*"#include".* | +^[\t ]*"#undef".* | +"//".* | +";" | +"<" | +">" | +\n { + WorkOnTokenSet( IGNOREDTOKENS, yytext ); +} +"/*" { + char c1 = 0, c2 = input(); + char pChar[2]; + pChar[1] = 0x00; + pChar[0] = c2; + + WorkOnTokenSet( COMMEND, yytext ); + WorkOnTokenSet( COMMEND, pChar ); + for(;;) { + if ( c2 == EOF ) + break; + if ( c1 == '*' && c2 == '/' ) + break; + c1 = c2; + c2 = input(); + pChar[0] = c2; + WorkOnTokenSet( COMMEND, pChar ); + } +} + +^[\t ]*"#ifndef".+$ | +^[\t ]*"#ifdef".+$ | +^[\t ]*"#if".+$ | +^[\t ]*"#elif".*$ | +^[\t ]*"#else".*$ | +^[\t ]*"#endif".*$ { + WorkOnTokenSet( CONDITION, yytext ); +} + +[a-zA-Z]+[\t ]+[^={\n]+[\t ] { +/* defined Res */ + WorkOnTokenSet( DEFINEDRES, yytext ); +} + +[a-zA-Z]+[ \t]+[^={;\n]+\n[ \t]*"#".*\n[ \t]*"{" | +[a-zA-Z]+[ \t]+[^={;\n]+\n?([ \t]*"//".*\n)*[ \t]*"{" { +/* RESSOURCE // String TTT_XX ... */ + WorkOnTokenSet( RESSOURCE, yytext ); +} + +^[\t ]*[a-zA-Z_]+[\t ]*"\\"?[\t ]*\n?[ \t]*"{"[\t ]*"\\"? { +/* SMALRESSOURCE // String ... */ + WorkOnTokenSet( SMALRESSOURCE, yytext ); +} + +[\t ]*[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?=[ \t]*L?\".*\".*\n? { +/* TEXTLINE // TextTyp = "A Text" */ + WorkOnTokenSet( TEXTLINE, yytext ); +} + +[\t ]*[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?(\n[ \t]*)?=([ \t]*\n)?(([a-zA-Z0-9_]+)|(\".*\")|([ \t\n]*))*\".*\"(([a-zA-Z0-9_]+)|(\".*\")|([ \t\n]*))*; { +/* LONGTEXTLINE // TextTyp = "A Text" HHH_XXX "A Text" ZZZ_TTT ... */ + WorkOnTokenSet( LONGTEXTLINE, yytext ); +} + +\".*\" { +/* TEXT // "A Text" */ + WorkOnTokenSet( TEXT, yytext ); +} + +"{"[ \t]*\\? { +/* LEVELUP */ + WorkOnTokenSet( LEVELUP, yytext ); +} + +"}"[ \t]*;([ \t]*\\)? { +/* LEVELDOWN */ + WorkOnTokenSet( LEVELDOWN, yytext ); +} + +[a-zA-Z0-9_]+[ \t]*"="[ \t]*"MAP_APPFONT"[ \t]*"(".+")".* { +/* APPFONTMAPPING Typ = MAP_APPFONT( ... ) */ + WorkOnTokenSet( APPFONTMAPPING, yytext ); +} + +[ \t]*[a-zA-Z0-9_]+[ \t]*=[ \t]*[0123456789]{1,5}[ \t]*";"?\\? { +/* TEXTREFID // TextTyp = 12345 */ + WorkOnTokenSet( TEXTREFID, yytext ); +} + +[a-zA-Z0-9_]+[ \t]*"="[\t ]*([ \t]*"//".*\n)*.* | +[a-zA-Z0-9_]+[ \t]*"=".* { +/* ASSIGNMENT Typ = ... */ + WorkOnTokenSet( ASSIGNMENT, yytext ); +} + + + +[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{"[ \t]*(\\[ \t]*)?\n?[ \t]*"<" { +/* LISTASSIGNMENT Typ [ ... ] = ... */ + WorkOnTokenSet( LISTASSIGNMENT, yytext ); +} + +"StringList"+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{"[ \t]*(\\[ \t]*)?\n?[ \t]* { +/* LISTASSIGNMENT Typ [ ... ] = ... */ + WorkOnTokenSet( LISTASSIGNMENT, yytext ); +} + +"UIEntries"[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{" { +/* UIENTRIES */ + WorkOnTokenSet( UIENTRIES, yytext ); +} + +"<"?[ \t]*L?\".*\".*">" { +/* LISTTEXT */ + WorkOnTokenSet( LISTTEXT, yytext ); +} + +[ \t]*"#define"[ \t]+[a-zA-Z0-9_]+.*"\\" { +/* RSCDEFINE #define ... */ + WorkOnTokenSet( RSCDEFINE, yytext ); +} + +[ \t]*"#define"[ \t]+[a-zA-Z0-9_]+.+ { +/* #define ... */ + WorkOnTokenSet( NORMDEFINE, yytext ); +} + +"\\" { +/* RSCDEFINELEND */ + WorkOnTokenSet( RSCDEFINELEND, yytext ); +} + +[a-zA-Z0-9_]+[ \t]*; { +/* allowed other tokens like "49 ;" or "SFX_... ;" */ + WorkOnTokenSet( ANYTOKEN, yytext ); +} + +. { + WorkOnTokenSet( UNKNOWNCHAR, yytext ); +/* YYWarning( "Unknown Char" ); */ +} + +"{"?[ \t]*\".*\"[ \t]*";"[ \t]*"}" { +/* _LISTTEXT */ + WorkOnTokenSet( _LISTTEXT, yytext ); +} + +%% + +/*****************************************************************************/ +int yywrap(void) +/*****************************************************************************/ +{ + FILE *pFile; + pFile = GetNextFile(); + if ( pFile ) { + yyin = pFile; + yylineno = 0; + return 0; + } + + /* end of input reached */ + return 1; +} + +/*****************************************************************************/ +void YYWarning( char *s ) +/*****************************************************************************/ +{ + /* write warning to stderr */ + fprintf( stderr, "Warning: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); +} + +/*****************************************************************************/ +void yyerror( char *s ) +/*****************************************************************************/ +{ + /* write error to stderr */ + fprintf( stderr, "Error: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); + SetError(); +} + +/*****************************************************************************/ +int +#ifdef WNT +_cdecl +#endif +main( int argc, char* argv[]) +/*****************************************************************************/ +{ + /* error level */ + int nRetValue = 0; + char *pOutput; + FILE *pFile; + + pOutput = GetOutputFile( argc, argv ); + if( !isQuiet() ){ + fprintf( stdout, "\nTransEx 3.1 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); + fprintf( stdout, "========================================================================\n" ); + } + + if ( !pOutput ) { + fprintf( stdout, "Syntax:TRANSEX[-p Prj][-r PrjRoot]-i FileIn...[-o FileOut][-m DataBase][-e][-b][-u][-L l1,l2,...]\n" ); + fprintf( stdout, " Prj: Project\n" ); + fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); + fprintf( stdout, " FileIn: Source files (*.src)\n" ); + fprintf( stdout, " FileOut: Destination file (*.*)\n" ); + fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); + fprintf( stdout, " -QQ: quiet output\n" ); + fprintf( stdout, " -e: Disable writing errorlog\n" ); + fprintf( stdout, " -b: Break when Token \"HelpText\" found in source\n" ); + fprintf( stdout, " -u: [english] and [german] are allowed, Id is Taken from DataBase \n" ); + fprintf( stdout, " -NOUTF8: disable UTF8 as language independent encoding\n" ); + fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); + fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); + fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); + fprintf( stdout, " Example: -L de,es=en-US\n" ); + fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); + return 1; + } + + InitExport( pOutput , getFilename() ); + pFile = GetNextFile(); + if ( !pFile ) + return 1; + + yyin = pFile; + + /* create global instance of class Export */ + + /* start parser */ + yylex(); + Close(); + + /* get error info. and end export */ + nRetValue = GetError(); + EndExport(); + + if( !isQuiet() ) fprintf( stdout, "\n===================================\n\n" ); + + /* return error level */ + return nRetValue; +} diff --git a/l10ntools/source/tagtest.cxx b/l10ntools/source/tagtest.cxx new file mode 100644 index 000000000000..7896915ede0c --- /dev/null +++ b/l10ntools/source/tagtest.cxx @@ -0,0 +1,1577 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: tagtest.cxx,v $ + * $Revision: 1.20 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include +#include "tagtest.hxx" + +#if OSL_DEBUG_LEVEL > 1 +#include +#endif + +#include "gsicheck.hxx" + +#define HAS_FLAG( nFlags, nFlag ) ( ( nFlags & nFlag ) != 0 ) +#define SET_FLAG( nFlags, nFlag ) ( nFlags |= nFlag ) +#define RESET_FLAG( nFlags, nFlag ) ( nFlags &= ~nFlag ) // ~ = Bitweises NOT + + + +TokenInfo::TokenInfo( TokenId pnId, USHORT nP, String paStr, ParserMessageList &rErrorList ) +: bClosed(FALSE) +, bCloseTag(FALSE) +, bIsBroken(FALSE) +, bHasBeenFixed(FALSE) +, bDone(FALSE) +, aTokenString( paStr ) +, nId( pnId ) +, nPos(nP) +{ + if ( nId == TAG_COMMONSTART || nId == TAG_COMMONEND ) + SplitTag( rErrorList ); +} + +enum tagcheck { TC_START, TC_HAS_TAG_NAME, TC_HAS_PROP_NAME_EQ, TC_HAS_PROP_NAME_EQ_SP, TC_HAS_PROP_NAME_SP, TC_INSIDE_STRING, TC_PROP_FINISHED, TC_CLOSED, TC_CLOSED_SPACE, TC_CLOSETAG, TC_CLOSETAG_HAS_TAG_NAME, TC_FINISHED, TC_ERROR }; + +/* + \< link href = \"text\" name = \"C\" \> +START ' ' -> HAS_TAG_NAME +START '/' -> CLOSED +START '/' -> CLOSETAG - no Portion (starting with /) +START '>' -> FINISHED +HAS_TAG_NAME '=' -> HAS_PROP_NAME_EQ +HAS_TAG_NAME ' ' -> HAS_PROP_NAME_SP +HAS_TAG_NAME '/' -> CLOSED +HAS_TAG_NAME '>' -> FINISHED +HAS_PROP_NAME_SP '=' -> HAS_PROP_NAME_EQ +HAS_PROP_NAME_EQ ' ' -> HAS_PROP_NAME_EQ_SP +HAS_PROP_NAME_EQ '"' -> INSIDE_STRING +HAS_PROP_NAME_EQ_SP '"' -> INSIDE_STRING +INSIDE_STRING ' ' -> INSIDE_STRING +INSIDE_STRING '=' -> INSIDE_STRING +INSIDE_STRING '>' -> INSIDE_STRING +INSIDE_STRING '"' -> PROP_FINISHED +PROP_FINISHED ' ' -> HAS_TAG_NAME +PROP_FINISHED '/' -> CLOSED +PROP_FINISHED '>' -> FINISHED +CLOSED ' ' -> CLOSED_SPACE +CLOSED '>' -> FINISHED +CLOSED_SPACE '>' -> FINISHED + +CLOSETAG ' ' -> CLOSETAG_HAS_TAG_NAME +CLOSETAG '>' -> FINISHED +CLOSETAG_HAS_TAG_NAME '>' -> FINISHED + +*/ +void TokenInfo::SplitTag( ParserMessageList &rErrorList ) +{ + USHORT nLastPos = 2; // skip initial \< + USHORT nCheckPos = nLastPos; + String aDelims( String::CreateFromAscii( " \\=>/" ) ); + String aPortion; + String aValue; // store the value of a property + ByteString aName; // store the name of a property/tag + BOOL bCheckName = FALSE; + BOOL bCheckEmpty = FALSE; + sal_Unicode cDelim; + tagcheck aState = TC_START; + + // skip blanks + while ( nLastPos < aTokenString.Len() && aTokenString.GetChar( nLastPos ) == ' ') + nLastPos++; + + nCheckPos = aTokenString.SearchChar( aDelims.GetBuffer(), nLastPos ); + while ( nCheckPos != STRING_NOTFOUND && !( aState == TC_FINISHED || aState == TC_ERROR ) ) + { + aPortion = aTokenString.Copy( nLastPos, nCheckPos-nLastPos ); + + if ( aTokenString.GetChar( nCheckPos ) == '\\' ) + nCheckPos++; + + cDelim = aTokenString.GetChar( nCheckPos ); + nCheckPos++; + + switch ( aState ) + { +// START ' ' -> HAS_TAG_NAME +// START '/' -> CLOSED +// START '>' -> FINISHED + case TC_START: + aTagName = aPortion; + switch ( cDelim ) + { + case ' ': aState = TC_HAS_TAG_NAME; + bCheckName = TRUE; + break; + case '/': + { + if ( aPortion.Len() == 0 ) + { + aState = TC_CLOSETAG; + } + else + { + aState = TC_CLOSED; + bCheckName = TRUE; + } + } + break; + case '>': aState = TC_FINISHED; + bCheckName = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// HAS_TAG_NAME '=' -> HAS_PROP_NAME_EQ +// HAS_TAG_NAME ' ' -> HAS_PROP_NAME_SP +// HAS_TAG_NAME '/' -> CLOSED +// HAS_TAG_NAME '>' -> FINISHED + case TC_HAS_TAG_NAME: + switch ( cDelim ) + { + case '=': aState = TC_HAS_PROP_NAME_EQ; + bCheckName = TRUE; + break; + case ' ': aState = TC_HAS_PROP_NAME_SP; + bCheckName = TRUE; + break; + case '/': aState = TC_CLOSED; + bCheckEmpty = TRUE; + break; + case '>': aState = TC_FINISHED; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// HAS_PROP_NAME_SP '=' -> HAS_PROP_NAME_EQ + case TC_HAS_PROP_NAME_SP: + switch ( cDelim ) + { + case '=': aState = TC_HAS_PROP_NAME_EQ; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// HAS_PROP_NAME_EQ ' ' -> HAS_PROP_NAME_EQ_SP +// HAS_PROP_NAME_EQ '"' -> INSIDE_STRING + case TC_HAS_PROP_NAME_EQ: + switch ( cDelim ) + { + case ' ': aState = TC_HAS_PROP_NAME_EQ_SP; + bCheckEmpty = TRUE; + break; + case '\"': aState = TC_INSIDE_STRING; + bCheckEmpty = TRUE; + aValue.Erase(); + break; + default: aState = TC_ERROR; + } + break; + +// HAS_PROP_NAME_EQ_SP '"' -> INSIDE_STRING + case TC_HAS_PROP_NAME_EQ_SP: + switch ( cDelim ) + { + case '\"': aState = TC_INSIDE_STRING; + bCheckEmpty = TRUE; + aValue.Erase(); + break; + default: aState = TC_ERROR; + } + break; + +// INSIDE_STRING * -> INSIDE_STRING +// INSIDE_STRING '"' -> PROP_FINISHED + case TC_INSIDE_STRING: + switch ( cDelim ) + { + case '\"': + { + aState = TC_PROP_FINISHED; + aValue += aPortion; + if ( aProperties.find( aName ) == aProperties.end() ) + { + if ( !IsPropertyValueValid( aName, aValue ) ) + { + rErrorList.AddError( 25, ByteString("Property '").Append(aName).Append("' has invalid value '").Append(ByteString( aValue, RTL_TEXTENCODING_UTF8 )).Append("' "), *this ); + bIsBroken = TRUE; + } + aProperties[ aName ] = aValue; + } + else + { + rErrorList.AddError( 25, ByteString("Property '").Append(aName).Append("' defined twice "), *this ); + bIsBroken = TRUE; + } + } + break; + default: + { + aState = TC_INSIDE_STRING; + aValue += aPortion; + aValue += cDelim; + } + } + break; + +// PROP_FINISHED ' ' -> HAS_TAG_NAME +// PROP_FINISHED '/' -> CLOSED +// PROP_FINISHED '>' -> FINISHED + case TC_PROP_FINISHED: + switch ( cDelim ) + { + case ' ': aState = TC_HAS_TAG_NAME; + bCheckEmpty = TRUE; + break; + case '/': aState = TC_CLOSED; + bCheckEmpty = TRUE; + break; + case '>': aState = TC_FINISHED; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// CLOSED ' ' -> CLOSED_SPACE +// CLOSED '>' -> FINISHED + case TC_CLOSED: + switch ( cDelim ) + { + case ' ': aState = TC_CLOSED_SPACE; + bCheckEmpty = TRUE; + bClosed = TRUE; + break; + case '>': aState = TC_FINISHED; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// CLOSED_SPACE '>' -> FINISHED + case TC_CLOSED_SPACE: + switch ( cDelim ) + { + case '>': aState = TC_FINISHED; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// CLOSETAG ' ' -> CLOSETAG_HAS_TAG_NAME +// CLOSETAG '>' -> FINISHED + case TC_CLOSETAG: + bCloseTag = TRUE; + switch ( cDelim ) + { + case ' ': aState = TC_CLOSETAG_HAS_TAG_NAME; + aTagName = aPortion; + bCheckName = TRUE; + break; + case '>': aState = TC_FINISHED; + aTagName = aPortion; + bCheckName = TRUE; + break; + default: aState = TC_ERROR; + } + break; + +// CLOSETAG_HAS_TAG_NAME '>' -> FINISHED + case TC_CLOSETAG_HAS_TAG_NAME: + switch ( cDelim ) + { + case '>': aState = TC_FINISHED; + bCheckEmpty = TRUE; + break; + default: aState = TC_ERROR; + } + break; + + + default: rErrorList.AddError( 99, "Internal error Parsing Tag ", *this ); + bIsBroken = TRUE; + + } + + if ( bCheckName ) + { + if ( aPortion.Len() == 0 ) + { + rErrorList.AddError( 25, "Tag/Property name missing ", *this ); + bIsBroken = TRUE; + } + else + { + aName = ByteString( aPortion, RTL_TEXTENCODING_UTF8 ); + // "a-zA-Z_-.0-9" + xub_StrLen nCount; + BOOL bBroken = FALSE; + const sal_Char* aBuf = aName.GetBuffer(); + for ( nCount = 0 ; !bBroken && nCount < aName.Len() ; nCount++ ) + { + bBroken = ! ( ( aBuf[nCount] >= 'a' && aBuf[nCount] <= 'z' ) + ||( aBuf[nCount] >= 'A' && aBuf[nCount] <= 'Z' ) + ||( aBuf[nCount] >= '0' && aBuf[nCount] <= '9' ) + ||( aBuf[nCount] == '_' ) + ||( aBuf[nCount] == '-' ) + ||( aBuf[nCount] == '.' ) + ); + } + + if ( bBroken ) + { + rErrorList.AddError( 25, "Found illegal character in Tag/Property name ", *this ); + bIsBroken = TRUE; + } + } + + bCheckName = FALSE; + } + + if ( bCheckEmpty ) + { + if ( aPortion.Len() ) + { + rErrorList.AddError( 25, ByteString("Found displaced characters '").Append(ByteString( aPortion, RTL_TEXTENCODING_UTF8 )).Append("' in Tag "), *this ); + bIsBroken = TRUE; + } + bCheckEmpty = FALSE; + } + + + nLastPos = nCheckPos; + + // skip further blanks + if ( cDelim == ' ' && aState != TC_INSIDE_STRING ) + while ( nLastPos < aTokenString.Len() && aTokenString.GetChar( nLastPos ) == ' ') + nLastPos++; + + nCheckPos = aTokenString.SearchChar( aDelims.GetBuffer(), nLastPos ); + } + if ( aState != TC_FINISHED ) + { + rErrorList.AddError( 25, "Parsing error in Tag ", *this ); + bIsBroken = TRUE; + } +} + +BOOL TokenInfo::IsPropertyRelevant( const ByteString &aName, const String &aValue ) const +{ + if ( aTagName.EqualsAscii( "alt" ) && aName.Equals( "xml-lang" ) ) + return FALSE; + if ( aTagName.EqualsAscii( "ahelp" ) && aName.Equals( "visibility" ) && aValue.EqualsAscii("visible") ) + return FALSE; + if ( aTagName.EqualsAscii( "image" ) && (aName.Equals( "width" ) || aName.Equals( "height" )) ) + return FALSE; + + return TRUE; +} + +BOOL TokenInfo::IsPropertyValueValid( const ByteString &aName, const String &aValue ) const +{ +/* removed due to i56740 + if ( aTagName.EqualsAscii( "switchinline" ) && aName.Equals( "select" ) ) + { + return aValue.EqualsAscii("sys") || + aValue.EqualsAscii("appl") || + aValue.EqualsAscii("distrib"); + } */ + if ( aTagName.EqualsAscii( "caseinline" ) && aName.Equals( "select" ) ) + { + return /*!aValue.EqualsAscii("OS2") && removed due to i56740 */ + !aValue.EqualsAscii(""); + } + + // we don't know any better so we assume it to be OK + return TRUE; +} + +BOOL TokenInfo::IsPropertyInvariant( const ByteString &aName, const String &aValue ) const +{ + if ( aTagName.EqualsAscii( "link" ) && aName.Equals( "name" ) ) + return FALSE; + if ( aTagName.EqualsAscii( "link" ) && aName.Equals( "href" ) ) + { // check for external reference + if ( aValue.Copy( 0, 5 ).EqualsIgnoreCaseAscii( "http:" ) + || aValue.Copy( 0, 6 ).EqualsIgnoreCaseAscii( "https:" ) + || aValue.Copy( 0, 4 ).EqualsIgnoreCaseAscii( "ftp:" ) ) + return FALSE; + else + return TRUE; + } + return TRUE; +} + +BOOL TokenInfo::IsPropertyFixable( const ByteString &aName ) const +{ + // name everything that is allowed to be fixed automatically here + if ( (aTagName.EqualsAscii( "ahelp" ) && aName.Equals( "hid" )) + || (aTagName.EqualsAscii( "link" ) && aName.Equals( "href" )) + || (aTagName.EqualsAscii( "alt" ) && aName.Equals( "id" )) + || (aTagName.EqualsAscii( "variable" ) && aName.Equals( "id" )) + || (aTagName.EqualsAscii( "image" ) && aName.Equals( "src" )) + || (aTagName.EqualsAscii( "image" ) && aName.Equals( "id" ) )) + return TRUE; + return FALSE; +} + +BOOL TokenInfo::MatchesTranslation( TokenInfo& rInfo, BOOL bGenErrors, ParserMessageList &rErrorList, BOOL bFixTags ) const +{ + // check if tags are equal + // check if all existing properties are in the translation as well and + // wether they have a matching content (the same in most cases) + + if ( nId != rInfo.nId ) + return FALSE; + + if ( !aTagName.Equals( rInfo.aTagName ) ) + return FALSE; + + // If one of the tags has formating errors already it does make no sense to check here, so return right away + if ( bGenErrors && ( bIsBroken || rInfo.bIsBroken ) ) + return TRUE; + + StringHashMap::const_iterator iProp; + for( iProp = aProperties.begin() ; iProp != aProperties.end(); ++iProp ) + { + if ( rInfo.aProperties.find( iProp->first ) != rInfo.aProperties.end() ) + { + if ( IsPropertyRelevant( iProp->first, iProp->second ) || IsPropertyRelevant( iProp->first, rInfo.aProperties.find( iProp->first )->second ) ) + { + if ( IsPropertyInvariant( iProp->first, iProp->second ) ) + { + if ( !rInfo.aProperties.find( iProp->first )->second.Equals( iProp->second ) ) + { + if ( bGenErrors ) + { + if ( bFixTags && IsPropertyFixable( iProp->first ) ) + { + rInfo.aProperties.find( iProp->first )->second = iProp->second; + rInfo.SetHasBeenFixed(); + rErrorList.AddWarning( 25, ByteString("Property '").Append(iProp->first).Append("': FIXED different value in Translation "), *this ); + } + else + rErrorList.AddError( 25, ByteString("Property '").Append(iProp->first).Append("': value different in Translation "), *this ); + } + else return FALSE; + } + } + } + } + else + { + if ( IsPropertyRelevant( iProp->first, iProp->second ) ) + { + if ( bGenErrors ) + rErrorList.AddError( 25, ByteString("Property '").Append(iProp->first).Append("' missing in Translation "), *this ); + else return FALSE; + } + } + } + for( iProp = rInfo.aProperties.begin() ; iProp != rInfo.aProperties.end(); ++iProp ) + { + if ( aProperties.find( iProp->first ) == aProperties.end() ) + { + if ( IsPropertyRelevant( iProp->first, iProp->second ) ) + { + if ( bGenErrors ) + rErrorList.AddError( 25, ByteString("Extra Property '").Append(iProp->first).Append("' in Translation "), rInfo ); + else return FALSE; + } + } + } + + // if we reach here eather + // the tags match completely or + // the tags match but not the properties and we generated errors for that + return TRUE; +} + +String TokenInfo::GetTagName() const +{ + return aTagName; +} + +String TokenInfo::MakeTag() const +{ + String aRet; + aRet.AppendAscii("\\<"); + if ( bCloseTag ) + aRet.AppendAscii("/"); + aRet.Append( GetTagName() ); + StringHashMap::const_iterator iProp; + + for( iProp = aProperties.begin() ; iProp != aProperties.end(); ++iProp ) + { + aRet.AppendAscii(" "); + aRet.Append( String( iProp->first, RTL_TEXTENCODING_UTF8 ) ); + aRet.AppendAscii("=\\\""); + aRet.Append( iProp->second ); + aRet.AppendAscii("\\\""); + } + if ( bClosed ) + aRet.AppendAscii("/"); + aRet.AppendAscii("\\>"); + return aRet; +} + + +void ParserMessageList::AddError( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ) +{ + Insert( new ParserError( nErrorNr, aErrorText, rTag ), LIST_APPEND ); +} + +void ParserMessageList::AddWarning( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ) +{ + Insert( new ParserWarning( nErrorNr, aErrorText, rTag ), LIST_APPEND ); +} + +BOOL ParserMessageList::HasErrors() +{ + USHORT i; + for ( i=0 ; i < Count() ; i++ ) + if ( GetObject( i )->IsError() ) + return TRUE; + return FALSE; +} + +struct Tag +{ + String GetName() const { return String::CreateFromAscii( pName ); }; + const char* pName; + TokenId nTag; +}; + + +static const Tag aKnownTags[] = +{ +/* commenting oldstyle tags +// { "<#GROUP_FORMAT>", TAG_GROUP_FORMAT }, + { "<#BOLD>", TAG_BOLDON }, + { "<#/BOLD>", TAG_BOLDOFF }, + { "<#ITALIC>", TAG_ITALICON }, + { "<#/ITALIC>", TAG_ITALICOFF }, + { "<#UNDER>", TAG_UNDERLINEON }, + { "<#/UNDER>", TAG_UNDERLINEOFF }, + +// { "<#GROUP_NOTALLOWED>", TAG_GROUP_NOTALLOWED }, + { "<#HELPID>", TAG_HELPID }, + { "<#MODIFY>", TAG_MODIFY }, + { "<#REFNR>", TAG_REFNR }, + +// { "<#GROUP_STRUCTURE>", TAG_GROUP_STRUCTURE }, + { "<#NAME>", TAG_NAME }, + { "<#HREF>", TAG_HREF }, + { "<#AVIS>", TAG_AVIS }, + { "<#AHID>", TAG_AHID }, + { "<#AEND>", TAG_AEND }, + + { "<#TITEL>", TAG_TITEL }, + { "<#KEY>", TAG_KEY }, + { "<#INDEX>", TAG_INDEX }, + + { "<#REFSTART>", TAG_REFSTART }, + + { "<#GRAPHIC>", TAG_GRAPHIC }, + { "<#NEXTVERSION>", TAG_NEXTVERSION }, + + // { "<#GROUP_SYSSWITCH>", TAG_GROUP_SYSSWITCH }, + { "<#WIN>", TAG_WIN }, + { "<#UNIX>", TAG_UNIX }, + { "<#MAC>", TAG_MAC }, + { "<#OS2>", TAG_OS2 }, + +// { "<#GROUP_PROGSWITCH>", TAG_GROUP_PROGSWITCH }, + { "<#WRITER>", TAG_WRITER }, + { "<#CALC>", TAG_CALC }, + { "<#DRAW>", TAG_DRAW }, + { "<#IMPRESS>", TAG_IMPRESS }, + { "<#SCHEDULE>", TAG_SCHEDULE }, + { "<#IMAGE>", TAG_IMAGE }, + { "<#MATH>", TAG_MATH }, + { "<#CHART>", TAG_CHART }, + { "<#OFFICE>", TAG_OFFICE }, + */ +// { "<#TAG_GROUP_META>", TAG_GROUP_META }, + { "$[officefullname]", TAG_OFFICEFULLNAME }, + { "$[officename]", TAG_OFFICENAME }, + { "$[officepath]", TAG_OFFICEPATH }, + { "$[officeversion]", TAG_OFFICEVERSION }, + { "$[portalname]", TAG_PORTALNAME }, + { "$[portalfullname]", TAG_PORTALFULLNAME }, + { "$[portalpath]", TAG_PORTALPATH }, + { "$[portalversion]", TAG_PORTALVERSION }, + { "$[portalshortname]", TAG_PORTALSHORTNAME }, +/* commenting oldstyle tags +// { "<#TAG_GROUP_SINGLE>", TAG_GROUP_SINGLE }, + { "<#REFINSERT>", TAG_REFINSERT }, + +// { "<#GROUP_MULTI>", TAG_GROUP_MULTI }, + { "<#END>", TAG_END }, + { "<#ELSE>", TAG_ELSE }, + { "<#VERSIONEND>", TAG_VERSIONEND }, + { "<#ENDGRAPHIC>", TAG_ENDGRAPHIC },*/ + { "", TAG_COMMONSTART }, + { "", TAG_COMMONEND }, + + { "", TAG_NOMORETAGS }, + { "", TAG_UNKNOWN_TAG }, +}; + + +SimpleParser::SimpleParser() +: nPos( 0 ) +, aNextTag( TAG_NOMORETAGS, TOK_INVALIDPOS ) +{ +} + +void SimpleParser::Parse( String PaSource ) +{ + aSource = PaSource; + nPos = 0; + aLastToken.Erase(); + aNextTag = TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); + aTokenList.Clear(); +}; + +TokenInfo SimpleParser::GetNextToken( ParserMessageList &rErrorList ) +{ + TokenInfo aResult; + USHORT nTokenStartPos = 0; + if ( aNextTag.nId != TAG_NOMORETAGS ) + { + aResult = aNextTag; + aNextTag = TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); + } + else + { + aLastToken = GetNextTokenString( rErrorList, nTokenStartPos ); + if ( aLastToken.Len() == 0 ) + return TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); + + // do we have a \< ... \> style tag? + if ( aLastToken.Copy(0,2).EqualsAscii( "\\<" ) ) + { + // check for paired \" \" + bool bEven = true; + USHORT nQuotePos = 0; + USHORT nQuotedQuotesPos = aLastToken.SearchAscii( "\\\"" ); + USHORT nQuotedBackPos = aLastToken.SearchAscii( "\\\\" ); // this is only to kick out quoted backslashes + while ( nQuotedQuotesPos != STRING_NOTFOUND ) + { + if ( nQuotedBackPos <= nQuotedQuotesPos ) + nQuotePos = nQuotedBackPos+2; + else + { + nQuotePos = nQuotedQuotesPos+2; + bEven = !bEven; + } + nQuotedQuotesPos = aLastToken.SearchAscii( "\\\"", nQuotePos ); + nQuotedBackPos = aLastToken.SearchAscii( "\\\\", nQuotePos ); // this is only to kick out quoted backslashes + } + if ( !bEven ) + { + rErrorList.AddError( 24, "Missing quotes ( \\\" ) in Tag", TokenInfo( TAG_UNKNOWN_TAG, nTokenStartPos, aLastToken ) ); + } + + // check if we have an end-tag or a start-tag + USHORT nNonBlankStartPos,nNonBlankEndPos; + nNonBlankStartPos = 2; + while ( aLastToken.GetChar(nNonBlankStartPos) == ' ' ) + nNonBlankStartPos++; + if ( aLastToken.GetChar(nNonBlankStartPos) == '/' ) + aResult = TokenInfo( TAG_COMMONEND, nTokenStartPos, aLastToken, rErrorList ); + else + { + aResult = TokenInfo( TAG_COMMONSTART, nTokenStartPos, aLastToken, rErrorList ); + nNonBlankEndPos = aLastToken.Len() -3; + while ( aLastToken.GetChar(nNonBlankEndPos) == ' ' ) + nNonBlankEndPos--; + if ( aLastToken.GetChar( nNonBlankEndPos ) == '/' ) + aNextTag = TokenInfo( TAG_COMMONEND, nTokenStartPos, String::CreateFromAscii("\\"), rErrorList ); + } + } + else + { + USHORT i = 0; + while ( aKnownTags[i].nTag != TAG_UNKNOWN_TAG && + aLastToken != aKnownTags[i].GetName() ) + i++; + aResult = TokenInfo( aKnownTags[i].nTag, nTokenStartPos ); + } + } + + if ( aResult.nId == TAG_UNKNOWN_TAG ) + aResult = TokenInfo( TAG_UNKNOWN_TAG, nTokenStartPos, aLastToken ); + aTokenList.Insert( aResult, LIST_APPEND ); + return aResult; +} + +String SimpleParser::GetNextTokenString( ParserMessageList &rErrorList, USHORT &rTagStartPos ) +{ +// USHORT nStyle1StartPos = aSource.SearchAscii( "<#", nPos ); + USHORT nStyle2StartPos = aSource.SearchAscii( "$[", nPos ); + USHORT nStyle3StartPos = aSource.SearchAscii( "\\<", nPos ); + USHORT nStyle4StartPos = aSource.SearchAscii( "\\\\", nPos ); // this is only to kick out quoted backslashes + + rTagStartPos = 0; + +/* removing since a \<... is not likely + // check if the tag starts with a letter to avoid things like <> <= ... > + while ( STRING_NOTFOUND != nStyle3StartPos && !( aSource.Copy( nStyle3StartPos+2, 1 ).IsAlphaAscii() || aSource.GetChar( nStyle3StartPos+2 ) == '/' ) ) + nStyle3StartPos = aSource.SearchAscii( "\\<", nStyle3StartPos+1 ); +*/ + if ( STRING_NOTFOUND == nStyle2StartPos && STRING_NOTFOUND == nStyle3StartPos ) + return String(); // no more tokens + + if ( nStyle4StartPos < nStyle2StartPos && nStyle4StartPos <= nStyle3StartPos ) // <= to make sure \\ is always handled first + { // Skip quoted Backslash + nPos = nStyle4StartPos +2; + return GetNextTokenString( rErrorList, rTagStartPos ); + } + +/* if ( nStyle1StartPos < nStyle2StartPos && nStyle1StartPos <= nStyle3StartPos ) // <= to make sure our spechial tags are recognized before all others + { // test for <# ... > style tokens + USHORT nEndPos = aSource.SearchAscii( ">", nStyle1StartPos ); + if ( nEndPos == STRING_NOTFOUND ) + { // Token is incomplete. Skip start and search for better ones + nPos = nStyle1StartPos +2; + return GetNextTokenString( rErrorList, rTagStartPos ); + } + nPos = nEndPos; + rTagStartPos = nStyle1StartPos; + return aSource.Copy( nStyle1StartPos, nEndPos-nStyle1StartPos +1 ).ToUpperAscii(); + } + else*/ if ( nStyle2StartPos < nStyle3StartPos ) + { // test for $[ ... ] style tokens + USHORT nEndPos = aSource.SearchAscii( "]", nStyle2StartPos); + if ( nEndPos == STRING_NOTFOUND ) + { // Token is incomplete. Skip start and search for better ones + nPos = nStyle2StartPos +2; + return GetNextTokenString( rErrorList, rTagStartPos ); + } + nPos = nEndPos; + rTagStartPos = nStyle2StartPos; + return aSource.Copy( nStyle2StartPos, nEndPos-nStyle2StartPos +1 ); + } + else + { // test for \< ... \> style tokens + USHORT nEndPos = aSource.SearchAscii( "\\>", nStyle3StartPos); + USHORT nQuotedBackPos = aSource.SearchAscii( "\\\\", nStyle3StartPos ); // this is only to kick out quoted backslashes + while ( nQuotedBackPos <= nEndPos && nQuotedBackPos != STRING_NOTFOUND ) + { + nEndPos = aSource.SearchAscii( "\\>", nQuotedBackPos +2); + nQuotedBackPos = aSource.SearchAscii( "\\\\", nQuotedBackPos +2 ); // this is only to kick out quoted backslashes + } + if ( nEndPos == STRING_NOTFOUND ) + { // Token is incomplete. Skip start and search for better ones + nPos = nStyle3StartPos +2; + ByteString sTmp( "Tag Start '\\<' without Tag End '\\>': " ); + rErrorList.AddError( 24, "Tag Start '\\<' without Tag End '\\>'", TokenInfo( TAG_UNKNOWN_TAG, nStyle3StartPos, aSource.Copy( nStyle3StartPos-10, 20 ) ) ); + return GetNextTokenString( rErrorList, rTagStartPos ); + } + // check for paired quoted " --> \"sometext\" + + nPos = nEndPos; + rTagStartPos = nStyle3StartPos; + return aSource.Copy( nStyle3StartPos, nEndPos-nStyle3StartPos +2 ); + } +} + +String SimpleParser::GetLexem( TokenInfo const &aToken ) +{ + if ( aToken.aTokenString.Len() ) + return aToken.aTokenString; + else + { + USHORT i = 0; + while ( aKnownTags[i].nTag != TAG_UNKNOWN_TAG && + aKnownTags[i].nTag != aToken.nId ) + i++; + + return aKnownTags[i].GetName(); + } +} + +TokenParser::TokenParser() +: pErrorList( NULL ) +{} + +void TokenParser::Parse( const String &aCode, ParserMessageList* pList ) +{ + pErrorList = pList; + + //Scanner initialisieren + aParser.Parse( aCode ); + + //erstes Symbol holen + aTag = aParser.GetNextToken( *pErrorList ); + + nPfCaseOptions = 0; + nAppCaseOptions = 0; + bPfCaseActive = FALSE; + bAppCaseActive = FALSE; + + nActiveRefTypes = 0; + + //Ausfuehren der Start-Produktion + Paragraph(); + + //Es wurde nicht die ganze Kette abgearbeitet, bisher ist aber + //kein Fehler aufgetreten + //=> es wurde ein einleitendes Tag vergessen + if ( aTag.nId != TAG_NOMORETAGS ) + { + switch ( aTag.nId ) + { + case TAG_END: + { + ParseError( 3, "Extra Tag <#END>. Switch or <#HREF> expected.", aTag ); + } + break; + case TAG_BOLDOFF: + { + ParseError( 4, "<#BOLD> expected before <#/BOLD>.", aTag ); + } + break; + case TAG_ITALICOFF: + { + ParseError( 5, "<#ITALIC> expected before <#/ITALIC>.", aTag ); + } + break; + case TAG_UNDERLINEOFF: + { + ParseError( 17, "<#UNDER> expected before <#/UNDER>.", aTag ); + } + break; +/* case TAG_MISSPARENTHESIS: + { + ParseError( 14, "missing closing parenthesis '>'", aTag ); + } + break;*/ + case TAG_AEND: + { + ParseError( 5, "Extra Tag <#AEND>. <#AVIS> or <#AHID> expected.", aTag ); + } + break; + case TAG_ELSE: + { + ParseError( 16, "Application-tag or platform-tag expected before <#ELSE>.", aTag ); + } + break; + case TAG_UNKNOWN_TAG: + { + ParseError( 6, "unknown Tag", aTag ); + } + break; + default: + { + ParseError( 6, "unexpected Tag", aTag ); + } + } + } + pErrorList = NULL; +} + +void TokenParser::Paragraph() +{ + switch ( aTag.nId ) + { + case TAG_GRAPHIC: + case TAG_NEXTVERSION: + { + TagRef(); + Paragraph(); + } + break; + case TAG_AVIS: + case TAG_AHID: + { + TagRef(); + Paragraph(); + } + break; + case TAG_HELPID: + { + SimpleTag(); + Paragraph(); + } + break; + case TAG_OFFICEFULLNAME: + case TAG_OFFICENAME: + case TAG_OFFICEPATH: + case TAG_OFFICEVERSION: + case TAG_PORTALNAME: + case TAG_PORTALFULLNAME: + case TAG_PORTALPATH: + case TAG_PORTALVERSION: + case TAG_PORTALSHORTNAME: + { + SimpleTag(); + Paragraph(); + } + break; + case TAG_REFINSERT: + { + SimpleTag(); + Paragraph(); + } + break; + case TAG_BOLDON: + case TAG_ITALICON: + case TAG_UNDERLINEON: + case TAG_COMMONSTART: + { + TagPair(); + Paragraph(); + } + break; + case TAG_HREF: + case TAG_NAME: + case TAG_KEY: + case TAG_INDEX: + case TAG_TITEL: + case TAG_REFSTART: + { + TagRef(); + Paragraph(); + } + break; + case TAG_OS2: + case TAG_WIN: + case TAG_UNIX: + case TAG_MAC: //... + { + if ( ! bPfCaseActive ) + { + //PfCases duerfen nicht verschachtelt sein: + bPfCaseActive = TRUE; + PfCase(); + + //So jetzt kann wieder ein PfCase kommen: + bPfCaseActive = FALSE; + Paragraph(); + } + } + break; + case TAG_WRITER: + case TAG_CALC: + case TAG_DRAW: + case TAG_IMPRESS: + case TAG_SCHEDULE: + case TAG_IMAGE: + case TAG_MATH: + case TAG_CHART: + case TAG_OFFICE: + { + if ( !bAppCaseActive ) + { + //AppCases duerfen nicht verschachtelt sein: + bAppCaseActive = TRUE; + AppCase(); + + //jetzt koennen wieder AppCases kommen: + bAppCaseActive = FALSE; + Paragraph(); + } + } + break; + + //Case TAG_BOLDOFF, TAG_ITALICOFF, TAG_BUNDERLINE, TAG_END + //nichts tun wg. epsilon-Prod. + } +} + +void TokenParser::PfCase() +{ + + //Produktion: + //PfCase -> PfCaseBegin Paragraph (PfCase | PfCaseEnd) + + PfCaseBegin(); + + //Jetzt ist eine PfCase-Produktion aktiv: + Paragraph(); + switch ( aTag.nId ) + { + case TAG_ELSE: + case TAG_END: + { + CaseEnd(); + } + break; + case TAG_OS2: + case TAG_WIN: + case TAG_UNIX: + case TAG_MAC: //First (PfBegin) + { + PfCase(); + } + break; + default: + ParseError( 8, "<#ELSE> or <#END> or platform-tag expected.", aTag ); + } + //Die gemerkten Tags wieder loeschen fuer naechstes PfCase: + nPfCaseOptions = 0; +} + +void TokenParser::PfCaseBegin() +{ + switch ( aTag.nId ) + { + case TAG_OS2: + case TAG_WIN: + case TAG_UNIX: + case TAG_MAC: + { + //Token darf noch nicht vorgekommen sein im + //aktuellen Plattform-Case: + if ( !HAS_FLAG( nPfCaseOptions, TAG_NOGROUP( aTag.nId ) ) ) + { + SET_FLAG( nPfCaseOptions, TAG_NOGROUP( aTag.nId ) ); + match( aTag, aTag ); + } + else { + ParseError( 9, "Tag defined twice in the same platform-case", aTag ); + } + } + } +} + +void TokenParser::AppCase() +{ + + //Produktion: + //AppCase -> AppCaseBegin Paragraph (AppCase | AppCaseEnd) + + + AppCaseBegin(); + + Paragraph(); + + switch ( aTag.nId ) + { + case TAG_ELSE: + case TAG_END: + { + CaseEnd(); + } + break; + case TAG_WRITER: + case TAG_DRAW: + case TAG_CALC: + case TAG_IMAGE: + case TAG_MATH: + case TAG_CHART: + case TAG_OFFICE: + case TAG_IMPRESS: + case TAG_SCHEDULE: //First (AppBegin) + { + AppCase(); + } + break; + default: + ParseError( 1, "<#ELSE> or <#END> or application-case-tag expected.", aTag ); + } + + //Die gemerkten Tags wieder loeschen fuer naechstes AppCase: + nAppCaseOptions = 0; +} + +void TokenParser::AppCaseBegin() +{ + switch ( aTag.nId ) + { + case TAG_WRITER: + case TAG_DRAW: + case TAG_CALC: + case TAG_IMAGE: + case TAG_MATH: + case TAG_CHART: + case TAG_OFFICE: + case TAG_IMPRESS: + case TAG_SCHEDULE: + { + //Token darf noch nicht vorgekommen sein im + //aktuellen Plattform-Case: + if ( !HAS_FLAG( nAppCaseOptions, TAG_NOGROUP( aTag.nId ) ) ) + { + SET_FLAG( nAppCaseOptions, TAG_NOGROUP( aTag.nId ) ); + match( aTag, aTag ); + } + else { + ParseError( 13, "Tag defined twice in the same application-case.", aTag ); + } + } + } +} + +void TokenParser::CaseEnd() +{ + //Produktion: + //CaseEnd -> <#ELSE> Paragraph <#END> | <#END> + + switch ( aTag.nId ) + { + case TAG_ELSE: + { + match( aTag, TAG_ELSE ); + Paragraph(); + match( aTag, TAG_END ); + } + break; + case TAG_END: + { + match( aTag, TAG_END ); + } + break; + default: + ParseError( 2, "<#ELSE> or <#END> expected.", aTag ); + } +} + +void TokenParser::SimpleTag() +{ + + switch ( aTag.nId ) + { + case TAG_HELPID: + { + match( aTag, TAG_HELPID ); + } + break; + case TAG_OFFICEFULLNAME: + case TAG_OFFICENAME: + case TAG_OFFICEPATH: + case TAG_OFFICEVERSION: + case TAG_PORTALNAME: + case TAG_PORTALFULLNAME: + case TAG_PORTALPATH: + case TAG_PORTALVERSION: + case TAG_PORTALSHORTNAME: + + case TAG_REFINSERT: + { + match( aTag, aTag ); + } + break; + default: + ParseError( 15, "[<#SimpleTag>] expected.", aTag ); + } +} + +void TokenParser::TagPair() +{ + switch ( aTag.nId ) + { + case TAG_BOLDON: + { + match( aTag, TAG_BOLDON ); + Paragraph(); + match( aTag, TAG_BOLDOFF ); + } + break; + case TAG_ITALICON: + { + match( aTag, TAG_ITALICON ); + Paragraph(); + match( aTag, TAG_ITALICOFF ); + } + break; + case TAG_UNDERLINEON: + { + match( aTag, TAG_UNDERLINEON ); + Paragraph(); + match( aTag, TAG_UNDERLINEOFF ); + } + break; + case TAG_COMMONSTART: + { + //remember tag so we can give the original tag in case of an error + TokenInfo aEndTag( aTag ); + aEndTag.nId = TAG_COMMONEND; + match( aTag, TAG_COMMONSTART ); + Paragraph(); + match( aTag, aEndTag ); + } + break; + default: + ParseError( 10, "<#BOLD>, <#ITALIC>, <#UNDER> expected.", aTag ); + } +} + + +void TokenParser::TagRef() +{ + switch ( aTag.nId ) + { + case TAG_GRAPHIC: + case TAG_NEXTVERSION: + { + if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) + { + TokenId aThisToken = aTag.nId; + SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + match( aTag, aTag ); + Paragraph(); + if ( aThisToken == TAG_GRAPHIC ) + match( aTag, TAG_ENDGRAPHIC ); + else + match( aTag, TAG_VERSIONEND ); + // don't reset since alowed only once per paragraph + // RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + } + else + { + ParseError( 11, "Tags <#GRAPHIC>,<#NEXTVERSION> allowed only once per paragraph at", aTag ); + } + } + break; + case TAG_AVIS: + case TAG_AHID: + { + if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) + { + TokenId aThisToken = aTag.nId; + SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + match( aTag, aTag ); + Paragraph(); + match( aTag, TAG_AEND ); + RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + } + else + { + ParseError( 11, "Nested <#AHID>,<#AVIS> not allowed.", aTag ); + } + } + break; + case TAG_HREF: + case TAG_NAME: + { + + } + // NOBREAK + case TAG_KEY: + case TAG_INDEX: + case TAG_TITEL: + case TAG_REFSTART: + { + if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) + { + TokenId aThisToken = aTag.nId; + match( aTag, aTag ); + if ( aThisToken != TAG_NAME ) + { // TAG_NAME has no TAG_END + SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + Paragraph(); + match( aTag, TAG_END ); + RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); + } + } + else + { + ParseError( 11, "Nested <#HREF>,<#NAME> or <#KEY> not allowed.", aTag ); + } + } + break; + default: + ParseError( 12, "<#HREF>,<#NAME> or <#KEY> expected.", aTag ); + } +} + +BOOL TokenParser::match( const TokenInfo &aCurrentToken, const TokenId &aExpectedToken ) +{ + return match( aCurrentToken, TokenInfo( aExpectedToken, TOK_INVALIDPOS ) ); +} + +BOOL TokenParser::match( const TokenInfo &aCurrentToken, const TokenInfo &rExpectedToken ) +{ + TokenInfo aExpectedToken( rExpectedToken ); + if ( aCurrentToken.nId == aExpectedToken.nId ) + { + if ( ( aCurrentToken.nId == TAG_COMMONEND + && aCurrentToken.GetTagName().Equals( aExpectedToken.GetTagName() ) ) + || aCurrentToken.nId != TAG_COMMONEND ) + { + aTag = aParser.GetNextToken( *pErrorList ); + return TRUE; + } + } + + if ( aExpectedToken.nId == TAG_COMMONEND ) + { + aExpectedToken.aTokenString.Insert( String::CreateFromAscii( "Close tag for " ), 0 ); + } + + ByteString sTmp( "Expected Symbol" ); + if ( aCurrentToken.nId == TAG_NOMORETAGS ) + { + ParseError( 7, sTmp, aExpectedToken ); + } + else + { + sTmp += ": "; + sTmp += ByteString( aParser.GetLexem( aExpectedToken ), RTL_TEXTENCODING_UTF8 ); + sTmp += " near "; + ParseError( 7, sTmp, aCurrentToken ); + } + return FALSE; +} + +void TokenParser::ParseError( USHORT nErrNr, ByteString aErrMsg, const TokenInfo &rTag ) +{ + pErrorList->AddError( nErrNr, aErrMsg, rTag); + + // Das Fehlerhafte Tag ueberspringen + aTag = aParser.GetNextToken( *pErrorList ); +} + + +ParserMessage::ParserMessage( USHORT PnErrorNr, ByteString PaErrorText, const TokenInfo &rTag ) + : nErrorNr( PnErrorNr ) + , aErrorText( PaErrorText ) + , nTagBegin( 0 ) + , nTagLength( 0 ) +{ + String aLexem( SimpleParser::GetLexem( rTag ) ); + aErrorText.Append(": "); + aErrorText += ByteString( aLexem, RTL_TEXTENCODING_UTF8 ); + if ( rTag.nId == TAG_NOMORETAGS ) + aErrorText.Append(" at end of line "); + else if ( rTag.nPos != TOK_INVALIDPOS ) + { + aErrorText.Append(" at Position "); + aErrorText.Append( ByteString::CreateFromInt32( rTag.nPos ) ); + } + nTagBegin = rTag.nPos; + nTagLength = aLexem.Len(); +} + +ParserError::ParserError( USHORT ErrorNr, ByteString ErrorText, const TokenInfo &rTag ) +: ParserMessage( ErrorNr, ErrorText, rTag ) +{} + +ParserWarning::ParserWarning( USHORT ErrorNr, ByteString ErrorText, const TokenInfo &rTag ) +: ParserMessage( ErrorNr, ErrorText, rTag ) +{} + +BOOL LingTest::IsTagMandatory( TokenInfo const &aToken, TokenId &aMetaTokens ) +{ + TokenId aTokenId = aToken.nId; + TokenId aTokenGroup = TAG_GROUP( aTokenId ); + if ( TAG_GROUP_PROGSWITCH == aTokenGroup + || TAG_REFINSERT == aTokenId + || TAG_REFSTART == aTokenId + || TAG_NAME == aTokenId + || TAG_HREF == aTokenId + || TAG_AVIS == aTokenId + || TAG_AHID == aTokenId + || TAG_GRAPHIC == aTokenId + || TAG_NEXTVERSION == aTokenId + || ( TAG_GROUP_META == aTokenGroup && (aMetaTokens & aTokenId) == aTokenId ) ) + { + if ( TAG_GROUP_META == aTokenGroup ) + aMetaTokens |= aTokenId; + return TRUE; + } + else if ( TAG_COMMONSTART == aTokenId + || TAG_COMMONEND == aTokenId ) + { + String aTagName = aToken.GetTagName(); + return !(aTagName.EqualsIgnoreCaseAscii( "comment" ) + || aTagName.EqualsIgnoreCaseAscii( "bookmark_value" ) + || aTagName.EqualsIgnoreCaseAscii( "emph" ) + || aTagName.EqualsIgnoreCaseAscii( "item" ) + || aTagName.EqualsIgnoreCaseAscii( "br" ) ); + } + return FALSE; +} + +void LingTest::CheckTags( TokenList &aReference, TokenList &aTestee, BOOL bFixTags ) +{ + ULONG i=0,j=0; + // Clean old Warnings + while ( aCompareWarningList.Count() ) + { + delete aCompareWarningList.GetCurObject(); + aCompareWarningList.Remove(); + } + + /* in xml tags, do not require the following tags + comment + bookmark_value + emph + item + br + */ + + // filter uninteresting Tags + TokenId aMetaTokens = 0; + for ( i=0 ; i < aReference.Count() ; i++ ) + { + if ( !IsTagMandatory( aReference.GetObject( i ), aMetaTokens ) ) + aReference.GetObject( i ).SetDone(); + } + + aMetaTokens = 0; + for ( i=0 ; i < aTestee.Count() ; i++ ) + { + if ( !IsTagMandatory( aTestee.GetObject( i ), aMetaTokens ) ) + aTestee.GetObject( i ).SetDone(); + } + + // remove all matching tags + for ( i=0 ; i < aReference.Count() ; i++ ) + { + if ( aReference.GetObject( i ).IsDone() ) + continue; + + BOOL bTagFound = FALSE; + for ( j=0 ; j < aTestee.Count() && !bTagFound ; j++ ) + { + if ( aTestee.GetObject( j ).IsDone() ) + continue; + + if ( aReference.GetObject( i ).MatchesTranslation( aTestee.GetObject( j ), FALSE, aCompareWarningList ) ) + { + aReference.GetObject( i ).SetDone(); + aTestee.GetObject( j ).SetDone(); + bTagFound = TRUE; + } + } + } + + BOOL bCanFix = TRUE; + + if ( bFixTags ) + { + // we fix only if its a really simple case + USHORT nTagCount = 0; + for ( i=0 ; i < aReference.Count() ; i++ ) + if ( !aReference.GetObject( i ).IsDone() ) + nTagCount++; + if ( nTagCount > 1 ) + bCanFix = FALSE; + + nTagCount = 0; + for ( i=0 ; i < aTestee.Count() ; i++ ) + if ( !aTestee.GetObject( i ).IsDone() ) + nTagCount++; + if ( nTagCount > 1 ) + bCanFix = FALSE; + } + + // generate errors for tags that have differing attributes + for ( i=0 ; i < aReference.Count() ; i++ ) + { + if ( aReference.GetObject( i ).IsDone() ) + continue; + + BOOL bTagFound = FALSE; + for ( j=0 ; j < aTestee.Count() && !bTagFound ; j++ ) + { + if ( aTestee.GetObject( j ).IsDone() ) + continue; + + if ( aReference.GetObject( i ).MatchesTranslation( aTestee.GetObject( j ), TRUE, aCompareWarningList, bCanFix && bFixTags ) ) + { + aReference.GetObject( i ).SetDone(); + aTestee.GetObject( j ).SetDone(); + bTagFound = TRUE; + } + } + } + + // list remaining tags as errors + for ( i=0 ; i < aReference.Count() ; i++ ) + { + if ( aReference.GetObject( i ).IsDone() ) + continue; + + aCompareWarningList.AddError( 20, "Missing Tag in Translation", aReference.GetObject( i ) ); + } + for ( i=0 ; i < aTestee.Count() ; i++ ) + { + if ( aTestee.GetObject( i ).IsDone() ) + continue; + + aCompareWarningList.AddError( 21, "Extra Tag in Translation", aTestee.GetObject( i ) ); + } + + for ( i=0 ; i < aReference.Count() ; i++ ) + aReference.GetObject( i ).SetDone( FALSE ); + + for ( i=0 ; i < aTestee.Count() ; i++ ) + aTestee.GetObject( i ).SetDone( FALSE ); +} + +void LingTest::CheckReference( GSILine *aReference ) +{ + aReferenceParser.Parse( aReference->GetUText(), aReference->GetMessageList() ); +} + +void LingTest::CheckTestee( GSILine *aTestee, BOOL bHasSourceLine, BOOL bFixTags ) +{ + aFixedTestee = aTestee->GetUText(); + aTesteeParser.Parse( aFixedTestee, aTestee->GetMessageList() ); + + if ( bHasSourceLine ) + CheckTags( aReferenceParser.GetTokenList(), aTesteeParser.GetTokenList(), bFixTags ); + + if ( bFixTags ) + { + TokenList& aTesteeTokens = aTesteeParser.GetTokenList(); + BOOL bFixesDone = FALSE; + // count backwards to allow replacing from right to left + int i; + for ( i=aTesteeTokens.Count()-1 ; i>=0 ; i-- ) + { + if ( aTesteeTokens.GetObject( i ).HasBeenFixed() ) + { + bFixesDone = TRUE; + aFixedTestee.Replace( aTesteeTokens.GetObject( i ).nPos, aTesteeTokens.GetObject( i ).aTokenString.Len(), aTesteeTokens.GetObject( i ).MakeTag() ); + } + } + if ( bFixesDone ) + { + aTestee->SetUText( aFixedTestee ); + aTestee->SetFixed(); + } + } +} + diff --git a/l10ntools/source/treeconfig.cxx b/l10ntools/source/treeconfig.cxx new file mode 100644 index 000000000000..137492c39a50 --- /dev/null +++ b/l10ntools/source/treeconfig.cxx @@ -0,0 +1,128 @@ +#include +#include +#include +#include "treeconfig.hxx" +#include "export.hxx" +#ifdef WNT +#include +#include +#else +#include +#endif +#include +#include +#include +#include + +using namespace std; + +namespace transex3 +{ + +bool Treeconfig::parseConfig(){ + + string source_config_file = string( static_cast( Export::GetEnv("SOURCE_ROOT_DIR") ).GetBuffer() ); + if( source_config_file.empty() ) + { + cerr << "Error: no suitable environment set?!?"; + exit( -1 ); + } + source_config_file += string("/source_config"); + if( isConfigFilePresent() ) + { + inireader.read( map , source_config_file ); + return true; + } + else return false; +} + +// ALWAYS add all repositories from source_config file to the container active_repos +// if a config_file is present ALWAYS return false +// if you are in the root of a repository also add it to the container active_repos +// if you are far inside a repository /my/path/ooo/sw/source then don't add it to the container but return true +// if you are in some misc place like /tmp then return true +// => the application can decide what to do in case the function returns true thus how to handle pwd() path +bool Treeconfig::getActiveRepositories( vector& active_repos ){ + + bool isPresent = isConfigFilePresent(); + bool hasPath = false; + string pwd; + string guessedRepo; + Export::getCurrentDir( pwd ); + string source_root = Export::GetEnv( "SOURCE_ROOT_DIR" ); + string solarsrc = Export::GetEnv( "SOLARSRC" ); + string partial; + + // if we are inside of a repository root then active it otherwise let the app handle the return! + string::size_type pos = pwd.find_first_of( source_root ); + if( pos != string::npos && ( pos + source_root.length() +1 ) < pwd.length()){ // I am within SOURCE_ROOT_DIR + partial = pwd.substr( pos + source_root.length() +1 , pwd.length()); + string::size_type nextPart = partial.find_first_of( "/" ); + if( nextPart != string::npos ) + hasPath = true; + else + guessedRepo = partial; + } + else // I am NOT within SOURCE_ROOT_DIR + hasPath = true; + + if( isPresent ) + { + hasPath = false; // if config_file is present don't care about pwd + stringmap* repos = static_cast( map[ string("repositories") ] ); + if( repos != 0 ) + { + for( stringmap::iterator iter = repos->begin() ; iter != repos->end() ; ++iter ) + { + if( static_cast( iter->second ) == string( "active" ) ) + { + active_repos.push_back( iter->first ); + if( static_cast( iter->first ) == guessedRepo ) + { + guessedRepo.clear(); // don't add double in case it is present in config_file + } + } + } + } + else + { + cerr << "Error: source_config files doesn't contain a 'repositories' section ?!?"; + exit( -1 ); + } + } + if( !guessedRepo.empty() ){ + active_repos.push_back( guessedRepo ); // add myrepo + } + return hasPath; // are we deep inside of a source tree or outside of SOURCE_ROOT_DIR? +} + +void Treeconfig::getCurrentDir( string& dir ) +{ + char buffer[64000]; + if( getcwd( buffer , sizeof( buffer ) ) == 0 ){ + cerr << "Error: getcwd failed!\n"; + exit( -1 ); + } + dir = string( buffer ); +} + +bool Treeconfig::isConfigFilePresent() +{ + string config_file = Export::GetEnv( "SOURCE_ROOT_DIR" ); + config_file += "/source_config"; + + struct stat status; + if( stat( config_file.c_str() , &status ) < 0 ) + { + return false; + } +#ifdef WNT + return ( status.st_mode & _S_IFREG ) && ( _access( config_file.c_str() , 4 ) >= 0 ) ; +#else + return ( status.st_mode & S_IFREG ) && ( access( config_file.c_str() , R_OK ) >= 0 ) ; +#endif +} + + + +} diff --git a/l10ntools/source/utf8conv.cxx b/l10ntools/source/utf8conv.cxx new file mode 100644 index 000000000000..ee35eb56befd --- /dev/null +++ b/l10ntools/source/utf8conv.cxx @@ -0,0 +1,77 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: utf8conv.cxx,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include "utf8conv.hxx" + +// +// class UTF8Converter +// + +#define MAX_CONV_BUFFER_SIZE 0xFF00 + +#define TO_CVTFLAGS (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_MAPTOPRIVATE |\ + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |\ + RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT) + +#define FROM_CVTFLAGS (RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT |\ + RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT |\ + RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |\ + RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0) + +/*****************************************************************************/ +void UTF8Converter::Convert( ByteString &rBuffer, + rtl_TextEncoding nSourceENC, rtl_TextEncoding nDestENC ) +/*****************************************************************************/ +{ + String sTemp( rBuffer, nSourceENC ); + rBuffer = ByteString( sTemp, nDestENC ); +} + +/*****************************************************************************/ +ByteString UTF8Converter::ConvertToUTF8( + const ByteString &rASCII, rtl_TextEncoding nEncoding ) +/*****************************************************************************/ +{ + ByteString sReturn( rASCII ); + Convert( sReturn, nEncoding, RTL_TEXTENCODING_UTF8 ); + return sReturn; +} + +/*****************************************************************************/ +ByteString UTF8Converter::ConvertFromUTF8( + const ByteString &rUTF8, rtl_TextEncoding nEncoding ) +/*****************************************************************************/ +{ + ByteString sReturn( rUTF8 ); + Convert( sReturn, RTL_TEXTENCODING_UTF8, nEncoding ); + return sReturn; +} diff --git a/l10ntools/source/wrdtrans.cxx b/l10ntools/source/wrdtrans.cxx new file mode 100644 index 000000000000..c4a9d6ea5570 --- /dev/null +++ b/l10ntools/source/wrdtrans.cxx @@ -0,0 +1,248 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wrdtrans.cxx,v $ + * $Revision: 1.7 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" + +/* +#include "wrdtrans.hxx" + + +// NOT FULLY DECLARED SERVICES +#include +#include + + +#include +#include "wtratree.hxx" + +#include +*/ +//************** Declaration WordTrans_ErrorList ******************// +/* +typedef NAMESPACE_STD(vector) Stl_ByteStringList; + +class WordTrans_ErrorList +{ + public: + // OPERATIONS + void AddError( + WordTransformer::E_Error + i_eType, + const char * i_sErrorDescription ); + void Clear(); /// Empties the list. + + // INQUIRY + USHORT NrOfErrors() const; + WordTransformer::E_Error + GetError( + USHORT i_nNr, /// [0 .. NrOfErrors()-1], other values return an empty error. + ByteString * o_pErrorText ) const; /// If o_pErrorText != 0, the String is filled with the description of the error. + private: + // DATA + Stl_ByteStringList aErrors; +}; + +*/ + +//************** Implementation WordTransformer ******************// + +/* +WordTransformer::WordTransformer() + : dpTransformer(0), + dpErrors(new WordTrans_ErrorList) +{ +} + +WordTransformer::~WordTransformer() +{ + if (dpTransformer != 0) + delete dpTransformer; + delete dpErrors; +} + +BOOL +WordTransformer::LoadWordlist( const ByteString & i_sWordlist_Filepath, + CharSet i_nWorkingCharSet, + CharSet i_nFileCharSet ) +{ + if (dpTransformer != 0) + return FALSE; + + SvFileStream aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ); + if (! aFile.IsOpen()) + return FALSE; + aFile.SetStreamCharSet( i_nFileCharSet ) ; +// aFile.SetTargetCharSet( i_nWorkingCharSet ); + + dpTransformer = new WordTransTree; + + ByteString sTrans; + while ( aFile.ReadLine(sTrans) ) + { + dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';')); + } + + aFile.Close(); + return TRUE; +} + +USHORT +WordTransformer::Transform(ByteString & io_sText) +{ + // Initialization and precondition testing: + dpErrors->Clear(); + if (dpTransformer == 0) + { + dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded."); + return dpErrors->NrOfErrors(); + } + else if (io_sText.Len() > 63 * 1024) + { + dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB)."); + return dpErrors->NrOfErrors(); + } + else if (io_sText.Len() == 0) + { + return 0; + } + + // Transform: + dpTransformer->InitTransformation( + io_sText.GetBuffer(), + io_sText.Len() ); + + for ( ; !dpTransformer->TextEndReached(); ) + { + if (dpTransformer->TransformNextToken() != WordTransTree::OK) + { + CreateError(); + } + } + io_sText = dpTransformer->Output(); + return dpErrors->NrOfErrors(); +} + +USHORT +WordTransformer::NrOfErrors() const +{ + return dpErrors->NrOfErrors(); +} + +WordTransformer::E_Error +WordTransformer::GetError( USHORT i_nNr, + ByteString * o_pErrorText) const +{ + return dpErrors->GetError(i_nNr,o_pErrorText); +} + +void +WordTransformer::CreateError() +{ + ByteString sErr; + + switch (dpTransformer->CurResult()) + { + case WordTransTree::OK: + break; + case WordTransTree::HOTKEY_LOST: + sErr = ByteString("Error: By replacement of string "); + sErr += dpTransformer->CurReplacedString(); + sErr += " by "; + sErr += dpTransformer->CurReplacingString(); + sErr += "the hotkey at char '"; + sErr += dpTransformer->CurHotkey(); + sErr += "' was lost."; + dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess()); + sErr.ReleaseBufferAccess(); + break; + case WordTransTree::OUTPUT_OVERFLOW: + dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow."); + break; + default: + dpErrors->AddError(OTHER_ERROR,"Error: Unknown error."); + } +} +*/ +//************** Implementation WordTrans_ErrorList ******************// +/* +void +WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType, + const char * i_sErrorDescription ) +{ + ByteString sErrorType = "xxx"; + char * pErrorChars = sErrorType.GetBufferAccess(); + pErrorChars[0] = char(i_eType / 100 + '0'); + pErrorChars[1] = char( (i_eType % 100) / 10 + '0'); + pErrorChars[2] = char(i_eType % 10 + '0'); + sErrorType += i_sErrorDescription; + + aErrors.push_back(sErrorType); + sErrorType.ReleaseBufferAccess(); +} + +void +WordTrans_ErrorList::Clear() +{ + aErrors.erase(aErrors.begin(),aErrors.end()); +} + +USHORT +WordTrans_ErrorList::NrOfErrors() const +{ + return aErrors.size(); +} + +WordTransformer::E_Error +WordTrans_ErrorList::GetError( USHORT i_nNr, + ByteString * o_pErrorText ) const +{ + if ( i_nNr < aErrors.size() ) + { + const ByteString & rError = aErrors[i_nNr]; + const char * pErrorChars = rError.GetBuffer(); + + USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100 + + (pErrorChars[1] - '0') * 10 + + pErrorChars[2] - '0'; + + if (o_pErrorText != 0) + *o_pErrorText = pErrorChars+3; + + return WordTransformer::E_Error(nError); + } + else + { + if (o_pErrorText != 0) + *o_pErrorText = ""; + return WordTransformer::OK; + } +} +*/ diff --git a/l10ntools/source/wtranode.cxx b/l10ntools/source/wtranode.cxx new file mode 100644 index 000000000000..401c0b20fe1a --- /dev/null +++ b/l10ntools/source/wtranode.cxx @@ -0,0 +1,111 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wtranode.cxx,v $ + * $Revision: 1.4 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" + + +#include "wtranode.hxx" + + +// NOT FULLY DECLARED SERVICES + + +const ByteString sEmptyString(""); + + +WTT_Node::WTT_Node( UINT8 i_nValue, + WTT_Node * i_pDefaultBranch, + WTT_Node * i_pDefaultBranchForAlphas ) + : nValue(i_nValue), + eType(token_to_keep), + sReplaceString(sEmptyString), + // aBranches, + bIsOnDeleting(char(0)) +{ + int i = 0; + for ( ; i < C_BR_ALPHABASE; i++ ) + { + aBranches[i] = i_pDefaultBranch; + } // end for + for ( ; i < C_NR_OF_BRANCHES; i++ ) + { + aBranches[i] = i_pDefaultBranchForAlphas; + } +} + +void +WTT_Node::SetBranch( UINT8 i_cBranch, + WTT_Node * i_pNode ) +{ + if (i_cBranch < C_NR_OF_BRANCHES) + { + aBranches[i_cBranch] = i_pNode; + } +} + +void +WTT_Node::SetAsTokenToReplace(const ByteString & i_sReplaceString) +{ + sReplaceString = i_sReplaceString; + eType = token_to_replace; +} + +WTT_Node::~WTT_Node() +{ + // Delete the tree hanging below this node: + + bIsOnDeleting = TRUE; // Avoid double deleting of multiple used nodes. + + for (int i = 0; i < C_NR_OF_BRANCHES; i++) + { + if (aBranches[i] != 0 ? ! aBranches[i]->IsOnDeleting() : FALSE) + { + delete aBranches[i]; + } + } // end for +} + + + + + + + + + + + + + + + + + diff --git a/l10ntools/source/wtratree.cxx b/l10ntools/source/wtratree.cxx new file mode 100644 index 000000000000..dbf02a6f22be --- /dev/null +++ b/l10ntools/source/wtratree.cxx @@ -0,0 +1,421 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: wtratree.cxx,v $ + * $Revision: 1.5 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" + + +#include "wtratree.hxx" + + + +/** @ATTENTION + For reasons of speed, class WordTransTree works with two simple + char arrays, sOutput and sInput, instead of secure containers or + streams. So be extremely careful, when changing this code!!! +**/ + + + +// NOT FULLY DECLARED SERVICES +#include +#include +#include +#include "wtranode.hxx" + + +const BRANCH_T BR_END = 0; +const BRANCH_T BR_NONALPHA = 1; +const BRANCH_T BR_HOTKEY = 2; +const BRANCH_T BR_BACKSLASH = 3; +const BRANCH_T BR_ALPHABASE = 4; /// @ATTENTION All branches not valid for words must be smaller than this value! +const BRANCH_T BR_AE = 30; +const BRANCH_T BR_OE = 31; +const BRANCH_T BR_UE = 32; +const BRANCH_T BR_SZ = 33; +const BRANCH_T BR_MAX = 34; /// @ATTENTION Must be updated always! + +const BRANCH_T BR_START = 0; + + + + + +WordTransTree::WordTransTree(CharSet i_nWorkingCharSet) + : sInput(0), + nInputLength(0), + pInputEnd(0), + sOutput(0), + nOutputMaxLength(0), + dpParsingTreeTop(0), + pUnknownAlpha(0), + // cChar2Branch + c_AE(u_char('\xC4')), c_OE(u_char('\xD6')), c_UE(u_char('\xDC')), + c_ae(u_char('\xE4')), c_oe(u_char('\xF6')), c_ue(u_char('\xFC')), + pInputCurTokenStart(0), + pInputPosition(0), + pOutputPosition(0), + pCurParseNode(0), + eCurResult(OK), + cCurHotkey(0), + cCurHotkeySign(u_char('~')) +{ + // Initialize parsing tree: + pUnknownAlpha = new WTT_Node(BR_ALPHABASE,0,0); // This will be deleted as part of the parsing tree. + for ( UINT8 i = BR_ALPHABASE; i < C_NR_OF_BRANCHES; i++) + { + pUnknownAlpha->SetBranch(i,pUnknownAlpha); + } // end for + + dpParsingTreeTop = new WTT_Node(BR_START,0,pUnknownAlpha); + + WTT_Node * dpNonAlpha = new WTT_Node(BR_NONALPHA,0,0); + + dpNonAlpha->SetBranch(BR_NONALPHA,dpNonAlpha); + dpParsingTreeTop->SetBranch(BR_NONALPHA,dpNonAlpha); + + WTT_Node * dpBackslash = new WTT_Node(BR_BACKSLASH,dpNonAlpha,dpNonAlpha); + dpBackslash->SetBranch(BR_END,0); + + dpParsingTreeTop->SetBranch(BR_BACKSLASH,dpBackslash); + dpNonAlpha->SetBranch(BR_BACKSLASH,dpBackslash); + + + // Initialize character set: + SetCharSet(i_nWorkingCharSet); + + if (C_BR_ALPHABASE != BR_ALPHABASE || C_NR_OF_BRANCHES != BR_MAX) + { + fprintf(stderr, "Assertion failed: file %s line %d.", __FILE__, __LINE__); + exit(1); + } +} + +void +WordTransTree::SetCharSet(CharSet i_nWorkingCharSet) +{ + ByteString sConvert("\xC4\xD6\xDC\xE4\xF6\xFC\xDF"); + const u_char * pConvert = (const u_char * ) ( sConvert.Convert(RTL_TEXTENCODING_MS_1252, i_nWorkingCharSet).GetBuffer() ); + + INT16 i = 0; + for ( ; i < C_NR_OF_POSSIBLE_CHARS; ++i ) + { + cChar2Branch[i] = BR_NONALPHA; + } // end for + for ( i = 'a'; i <= 'z'; ++i ) + { + cChar2Branch[i] = BR_ALPHABASE + i - 'a'; + } // end for + for ( i = 'A'; i <= 'Z'; ++i ) + { + cChar2Branch[i] = BR_ALPHABASE + i - 'A'; + } // end for + cChar2Branch[pConvert[0]] = BR_AE; + cChar2Branch[pConvert[1]] = BR_OE; + cChar2Branch[pConvert[2]] = BR_UE; + cChar2Branch[pConvert[3]] = BR_AE; + cChar2Branch[pConvert[4]] = BR_OE; + cChar2Branch[pConvert[5]] = BR_UE; + cChar2Branch[pConvert[6]] = BR_SZ; + + cChar2Branch[u_char('~')] = BR_HOTKEY; + cChar2Branch[u_char('&')] = BR_HOTKEY; + + + c_AE = pConvert[0]; + c_OE = pConvert[1]; + c_UE = pConvert[2]; + c_ae = pConvert[3]; + c_oe = pConvert[4]; + c_ue = pConvert[5]; +} + +WordTransTree::~WordTransTree() +{ + delete dpParsingTreeTop; + if (sOutput != 0) + delete [] sOutput; +} + +void +WordTransTree::AddWordPair( const ByteString & i_sOldString, + const ByteString & i_sReplaceString ) +{ + if (i_sOldString.Len() == 0) + return; + + pCurParseNode = dpParsingTreeTop; + WTT_Node * pBranch = 0; + char cBranch = 0; + + for ( constr pOld = i_sOldString.GetBuffer(); + *pOld != 0; + pOld++ ) + { + cBranch = CalculateBranch(*pOld); + pBranch = pCurParseNode->GetNextNode(cBranch); + if (pBranch == 0 || pBranch == pUnknownAlpha) + { + pBranch = new WTT_Node(cBranch,0,pUnknownAlpha); + pCurParseNode->SetBranch(cBranch,pBranch); + } + pCurParseNode = pBranch; + } // end for + pCurParseNode->SetAsTokenToReplace(i_sReplaceString); +} + +void +WordTransTree::InitTransformation( const char * i_sInput, + UINT32 i_nInputLength, + UINT32 i_nOutputMaxLength ) +{ + sInput = (const u_char *)i_sInput; + nInputLength = i_nInputLength; + pInputEnd = &sInput[i_nInputLength]; + + pInputCurTokenStart = sInput; + pInputPosition = sInput; + + if (nOutputMaxLength < i_nOutputMaxLength) + { + if (sOutput != 0) + delete [] sOutput; + sOutput = new unsigned char[i_nOutputMaxLength]; + nOutputMaxLength = i_nOutputMaxLength; + } + pOutputPosition = sOutput; +} + +/** pInputCurTokenStart and CurParseNode are updated just when + starting this function. After its end they must not be changed + till this functon is called again. + Outside this function pInputPositon and pOutputPosition are both + on the first not transformed char in their respective array. +**/ +WordTransTree::E_Result +WordTransTree::TransformNextToken() +{ + pInputCurTokenStart = pInputPosition; + pCurParseNode = dpParsingTreeTop; + cCurHotkey = 0; + eCurResult = OK; + + WTT_Node * pBranch = 0; + UINT8 cBranch = 0; + + for ( pCurParseNode = dpParsingTreeTop; + pInputPosition != pInputEnd; + ++pInputPosition ) + { + cBranch = CalculateBranch(*pInputPosition); + pBranch = pCurParseNode->GetNextNode( cBranch ); + if (pBranch != 0) + { + pCurParseNode = pBranch; + } + else + { + if (cBranch == BR_HOTKEY) // current letter is '~' or '&'. + { + // Logic of the following. There are 9 possible cases - + // A = alphabetic letter, NA = non alphabetic, TB = token begin, + // Eot = end of text: + // 1. A~A set hotkey to following letter, continue + // 2. A~NA token end + // 3. A~Eot token end + // 4. NA~A token end + // 5. NA~NA continue + // 6. A~Eof continue + // 7. TB~A set hotkey to following letter, continue + // 8. TB~NA continue + // 9. TB~Eot continue + + // bNext and Prev are true, if there are alphabetic letters: + BOOL bNext = pInputPosition + 1 != pInputEnd + ? CalculateBranch(pInputPosition[1]) >= BR_ALPHABASE + : FALSE; + BOOL bPrev = pCurParseNode->Value() >= BR_ALPHABASE; + + if ( bNext && (bPrev || pCurParseNode == dpParsingTreeTop) ) + { // case 1. and 7. + Handle_Hotkey(); + continue; + } + else if (!bPrev && !bNext) + { // case 5.,6.,8.,9. + continue; + } + + // Case 2.,3.,4. : + // so this should be handled as an end of a token. + } + if (pCurParseNode->TokenType() == WTT_Node::token_to_keep) + { + Handle_TokenToKeep(); + return eCurResult; + } + else + { + Handle_TokenToTransform(); + return eCurResult; + } // endif (pCurParseNode->TokenType() == WTT_Node::token_to_keep) + } // endif (pBranch == 0) else + } // end for + + // If here, the text end is reached + if (pCurParseNode->TokenType() == WTT_Node::token_to_keep) + { + Handle_TokenToKeep(); + return eCurResult; + } + else + { + Handle_TokenToTransform(); + return eCurResult; + } +} + +ByteString +WordTransTree::CurReplacingString() const +{ + return pCurParseNode->ReplaceString(); +} + +void +WordTransTree::Handle_Hotkey() +{ + if (cCurHotkey == 0) // Avoid to replace the first found hotkey by + // a later one - though this shouldn't happen anyway. + { + cCurHotkey = (pInputPosition+1) != pInputEnd ? pInputPosition[1] : 0; + cCurHotkeySign = *pInputPosition; + } +} + +void +WordTransTree::Handle_TokenToKeep() +{ + UINT32 nTokenLength = pInputPosition-pInputCurTokenStart; + + memcpy(pOutputPosition,pInputCurTokenStart,nTokenLength); + + pOutputPosition += nTokenLength; + *pOutputPosition = '\0'; +} + +void +WordTransTree::Handle_TokenToTransform() +{ + BOOL bHaveHotkey = CalculateBranch(cCurHotkey) >= BR_ALPHABASE; + const ByteString & rReplace = pCurParseNode->ReplaceString(); + + // Find position of hotkey in replace-string: + USHORT nHotkeyPos = bHaveHotkey + ? rReplace.Search(char(cCurHotkey)) + : STRING_NOTFOUND; + if (nHotkeyPos == STRING_NOTFOUND && bHaveHotkey) + { + if (cCurHotkey < 128) + { + if (islower(cCurHotkey)) + nHotkeyPos = rReplace.Search(toupper(char(cCurHotkey))); + else + nHotkeyPos = rReplace.Search(tolower(char(cCurHotkey))); + } + else // cCurHotkey >= 128 + { + if (cCurHotkey == c_ae) + nHotkeyPos = rReplace.Search(char(c_AE)); + else if (cCurHotkey == c_oe) + nHotkeyPos = rReplace.Search(char(c_OE)); + else if (cCurHotkey == c_ue) + nHotkeyPos = rReplace.Search(char(c_UE)); + else if (cCurHotkey == c_AE) + nHotkeyPos = rReplace.Search(char(c_ae)); + else if (cCurHotkey == c_OE) + nHotkeyPos = rReplace.Search(char(c_oe)); + else if (cCurHotkey == c_UE) + nHotkeyPos = rReplace.Search(char(c_ue)); + } // endif (cCurHotkey < 128) else + + if (nHotkeyPos == STRING_NOTFOUND) + { + eCurResult = HOTKEY_LOST; + bHaveHotkey = FALSE; + } + } // endif (nHotkeyPos == STRING_NOT_FOUND && bHaveHotkey) + + + UINT32 nOutputTokenLength = rReplace.Len() + (bHaveHotkey ? 1 : 0); + + if (bHaveHotkey) + { + memcpy( pOutputPosition, + pCurParseNode->ReplaceString().GetBuffer(), + nHotkeyPos ); + *(pOutputPosition + nHotkeyPos) = cCurHotkeySign; + memcpy( pOutputPosition + nHotkeyPos + 1, + pCurParseNode->ReplaceString().GetBuffer() + nHotkeyPos, + nOutputTokenLength - nHotkeyPos - 1); + } + else + { + memcpy( pOutputPosition, + pCurParseNode->ReplaceString().GetBuffer(), + nOutputTokenLength ); + } + + // Convert first letter into upper if necessary: + u_char cInStart = CalculateBranch(*pInputCurTokenStart) == BR_HOTKEY + ? pInputCurTokenStart[1] + : pInputCurTokenStart[0] ; + u_char * pOutStart = nHotkeyPos == 0 + ? pOutputPosition + 1 + : pOutputPosition ; + if (isupper(cInStart) || cInStart > 127) + { // Possibly cInStart is upper character: + if (isupper(cInStart) || cInStart == c_AE || cInStart == c_OE || cInStart == c_UE) + { // Surely cInStart is upper character: + u_char cOutStart = *pOutStart; + if (cOutStart < 128) + *pOutStart = toupper(cOutStart); + else if (cOutStart == c_ae) + *pOutStart = c_AE; + else if (cOutStart == c_oe) + *pOutStart = c_OE; + else if (cOutStart == c_ue) + *pOutStart = c_UE; + } + } // endif (isupper(cInStart) || cInStart > 127) + + pOutputPosition += nOutputTokenLength; + *pOutputPosition = '\0'; +} + diff --git a/l10ntools/source/xgfconv.cxx b/l10ntools/source/xgfconv.cxx new file mode 100644 index 000000000000..54b92fb3c1c2 --- /dev/null +++ b/l10ntools/source/xgfconv.cxx @@ -0,0 +1,66 @@ +#include + +#include "export.hxx" +#include "utf8conv.hxx" + +/*****************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#if defined(UNX) || defined(OS2) +int main( int argc, char *argv[] ) +#else +int _cdecl main( int argc, char *argv[] ) +#endif +/*****************************************************************************/ +{ + if ( argc != 3 ) { + fprintf( stderr, "xgfconv InputFile OutputFile\n" ); + return ( 5 ); + } + + ByteString sInput( argv[ 1 ] ); + ByteString sOutput( argv[ 2 ] ); + + SvFileStream aInput( String( sInput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); + if ( !aInput.IsOpen()) { + fprintf( stderr, "ERROR: Unable to open input file!\n" ); + return ( 5 ); + } + + SvFileStream aOutput( String( sOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); + if ( !aOutput.IsOpen()) { + fprintf( stderr, "ERROR: Unable to open output file!\n" ); + aInput.Close(); + return ( 5 ); + } + + ByteString sLine; + BOOL bFirst = TRUE; + while ( !aInput.IsEof()) { + aInput.ReadLine( sLine ); + ByteString sLangId = sLine.GetToken( 0, '\t' ); + ByteString sFile = sLine.GetToken( 1, '\t' ); + ByteString sText = sLine.Copy( sLangId.Len() + sFile.Len() + 2 ); + + USHORT nLangId = sLangId.ToInt32(); + CharSet aCharSet = Export::GetCharSet( nLangId ); + if ( aCharSet != 0xFFFF && sText.Len()) { + sText = UTF8Converter::ConvertToUTF8( sText, aCharSet ); + ByteString sOutput = sFile; + sOutput += "\t"; + sOutput += sText; + if ( !bFirst ) { + ByteString sEmpty; + aOutput.WriteLine( sEmpty ); + } + else + bFirst = FALSE; + aOutput.Write( sOutput.GetBuffer(), sOutput.Len()); + } + } + aInput.Close(); + aOutput.Close(); + return ( 0 ); +} + diff --git a/l10ntools/source/xmlparse.cxx b/l10ntools/source/xmlparse.cxx new file mode 100644 index 000000000000..f75a0afe9792 --- /dev/null +++ b/l10ntools/source/xmlparse.cxx @@ -0,0 +1,1456 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * $RCSfile: xmlparse.cxx,v $ + * $Revision: 1.24 $ + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +// MARKER(update_precomp.py): autogen include statement, do not remove +#include "precompiled_l10ntools.hxx" +#include /* std::iterator*/ + +#include +#include + +#include "xmlparse.hxx" +#include +#include +#include +#include +#ifdef __MINGW32__ +#include +#include +#endif +using namespace std; +using namespace osl; + +// +// class XMLChildNode +// + +/*****************************************************************************/ +XMLChildNode::XMLChildNode( XMLParentNode *pPar ) +/*****************************************************************************/ + : pParent( pPar ) +{ + if ( pParent ) + pParent->AddChild( this ); +} + + +/*****************************************************************************/ +XMLChildNode::XMLChildNode( const XMLChildNode& obj) +/*****************************************************************************/ +: XMLNode(obj), + pParent(obj.pParent){} + +/*****************************************************************************/ +XMLChildNode& XMLChildNode::operator=(const XMLChildNode& obj){ +/*****************************************************************************/ + if(this != &obj){ + pParent=obj.pParent; + } + return *this; +} +// +// class XMLParentNode +// + + +/*****************************************************************************/ +XMLParentNode::~XMLParentNode() +/*****************************************************************************/ +{ + if( pChildList ){ + RemoveAndDeleteAllChilds(); + delete pChildList; + pChildList = NULL; + } + pChildList = NULL; +} +/*****************************************************************************/ +XMLParentNode::XMLParentNode( const XMLParentNode& obj) +/*****************************************************************************/ +: XMLChildNode( obj ) +{ + if( obj.pChildList ){ + pChildList=new XMLChildNodeList(); + XMLChildNode* pNode = NULL; + for ( ULONG i = 0; i < obj.pChildList->Count(); i++ ){ + pNode = obj.pChildList->GetObject( i ); + if( pNode != NULL){ + switch(pNode->GetNodeType()){ + case XML_NODE_TYPE_ELEMENT: + AddChild( new XMLElement( *static_cast(pNode) ) ); break; + case XML_NODE_TYPE_DATA: + AddChild( new XMLData ( *static_cast (pNode) ) ); break; + case XML_NODE_TYPE_COMMENT: + AddChild( new XMLComment( *static_cast(pNode) ) ); break; + case XML_NODE_TYPE_DEFAULT: + AddChild( new XMLDefault( *static_cast(pNode) ) ); break; + default: fprintf(stdout,"XMLParentNode::XMLParentNode( const XMLParentNode& obj) strange obj"); + } + } + } + }else pChildList = NULL; +} +/*****************************************************************************/ +XMLParentNode& XMLParentNode::operator=(const XMLParentNode& obj){ +/*****************************************************************************/ + if(this!=&obj){ + XMLChildNode::operator=(obj); + if( pChildList ){ + RemoveAndDeleteAllChilds(); + delete pChildList; + pChildList = NULL; + } + if( obj.pChildList ){ + pChildList=new XMLChildNodeList(); + for ( ULONG i = 0; i < obj.pChildList->Count(); i++ ) + AddChild( obj.pChildList->GetObject( i ) ); + }else pChildList = NULL; + + } + return *this; +} +/*****************************************************************************/ +void XMLParentNode::AddChild( XMLChildNode *pChild ) +/*****************************************************************************/ +{ + if ( !pChildList ) + pChildList = new XMLChildNodeList(); + pChildList->Insert( pChild, LIST_APPEND ); +} + +/*****************************************************************************/ +void XMLParentNode::AddChild( XMLChildNode *pChild , int pos ) +/*****************************************************************************/ +{ + if ( !pChildList ) + pChildList = new XMLChildNodeList(); + pChildList->Insert( pChild, pos ); +} + +/*****************************************************************************/ +int XMLParentNode::GetPosition( ByteString id ){ +/*****************************************************************************/ + XMLElement* a; + + static const ByteString sEnusStr = ByteString(String::CreateFromAscii(ENGLISH_US_ISO).ToLowerAscii() , RTL_TEXTENCODING_ASCII_US ).ToLowerAscii(); + static const ByteString sDeStr = ByteString(String::CreateFromAscii(GERMAN_ISO2).ToLowerAscii() , RTL_TEXTENCODING_ASCII_US ).ToLowerAscii(); + + if ( pChildList ){ + for ( ULONG i = 0; i < pChildList->Count(); i++ ) { + XMLChildNode *pChild = pChildList->GetObject( i ); + if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ + a = static_cast(pChild); + ByteString elemid( a->GetId() ); + elemid.ToLowerAscii(); + if ( elemid.Equals( id.ToLowerAscii() ) ){ + ByteString elemLID( a->GetLanguageId() ); + elemLID.ToLowerAscii(); + if( elemLID.Equals( sEnusStr) ) { + return i; + } + else if( elemLID.Equals( sDeStr) ) { + return i; + } + } + } + } + } + return -1; +} + +/*****************************************************************************/ +int XMLParentNode::RemoveChild( XMLElement *pRefElement ) +/*****************************************************************************/ +{ + XMLElement* a; + if ( pChildList ){ + for ( ULONG i = 0; i < pChildList->Count(); i++ ) { + XMLChildNode *pChild = pChildList->GetObject( i ); + if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ + a = static_cast(pChild); + ByteString elemid( a->GetId() ); + elemid.ToLowerAscii(); + ByteString elemLID( a->GetLanguageId() ); + elemLID.ToLowerAscii(); + ByteString pRefLID( pRefElement->GetLanguageId() ); + pRefLID.ToLowerAscii(); + if ( elemid.Equals(pRefElement->GetId()) + && elemLID.Equals( pRefLID ) ) + { + if( pRefElement->ToOString().compareTo( a->ToOString() )==0 ){ + pChildList->Remove( i ); + delete a; // Test + return i; + } + } + } + + } + } + return -1; +} + +/*****************************************************************************/ +void XMLParentNode::RemoveAndDeleteAllChilds(){ +/*****************************************************************************/ + if ( pChildList ) { + for ( ULONG i = 0; i < pChildList->Count(); i++ ) + delete pChildList->GetObject( i ); + pChildList->Clear(); + } +} + +/*****************************************************************************/ +XMLElement *XMLParentNode::GetChildElement( XMLElement *pRefElement ) +/*****************************************************************************/ +{ + for ( ULONG i = 0; i < pChildList->Count(); i++ ) { + XMLChildNode *pChild = pChildList->GetObject( i ); + if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ) + if ((( XMLElement * ) pChild )->GetName() == + pRefElement->GetName()) + { + XMLAttributeList *pList = pRefElement->GetAttributeList(); + if ( !pList ) + return ( XMLElement * ) pChild; + + BOOL bMatch = FALSE; + for ( ULONG j = 0; j < pList->Count() && bMatch; j++ ) { + XMLAttribute *pAttribute = pList->GetObject( j ); + XMLAttribute *pCandidate = + (( XMLElement * ) pChild )->GetAttribute( + *pAttribute ); + if ( !pCandidate || !pAttribute->IsEqual( *pCandidate )) + bMatch = FALSE; + } + if ( bMatch ) + return ( XMLElement * ) pChild; + } + } + return NULL; +} + +// +// class XMLFile +// + +/*****************************************************************************/ +USHORT XMLFile::GetNodeType() +/*****************************************************************************/ +{ + return XML_NODE_TYPE_FILE; +} + +/*****************************************************************************/ +BOOL XMLFile::Write( ByteString &aFilename ) +/*****************************************************************************/ +{ + + if ( aFilename.Len()) { + // retry harder if there is a NFS problem, + for( int x = 1 ; x < 3 ; x++ ){ // this looks strange...yes! + ofstream aFStream( aFilename.GetBuffer() , ios::out | ios::trunc ); + + if( !aFStream ) // From time to time the stream can not be opened the first time on NFS volumes, + { // I wasn't able to track this down. I think this is an NFS issue ..... + //cerr << "ERROR: - helpex - Can't write to tempfile " << aFilename.GetBuffer() << " No#" << x << "\n"; + TimeValue aTime; + aTime.Seconds = 3; + aTime.Nanosec = 0; + + osl::Thread::wait( aTime ); + } + else + { + // write out + Write( aFStream ); + aFStream.close(); + + // check! + DirEntry aTarget( aFilename ); + FileStat aFileStat( aTarget ); + + if( aFileStat.GetSize() < 1 ) + { + //retry + //cerr << "WARNING: - helpex - Can't create file " << aFilename.GetBuffer() << " No#" << x << "\n"; + aTarget.Kill(); + } + else + { + //everything ok! + return true; + } + } + } + cerr << "ERROR: - helpex - Can't create file " << aFilename.GetBuffer() << "\nPossible reason: Disk full ? Mounted NFS volume broken ? Wrong permissions ?\n"; + exit( -1 ); + } + cerr << "ERROR: - helpex - Empty file name\n"; + exit( -1 ); +} + + + +void XMLFile::WriteString( ofstream &rStream, const String &sString ) +{ + ByteString sText( sString, RTL_TEXTENCODING_UTF8 ); + rStream << sText.GetBuffer(); +} + + +BOOL XMLFile::Write( ofstream &rStream , XMLNode *pCur ) +{ + XMLUtil& xmlutil = XMLUtil::Instance(); + (void) xmlutil; + + if ( !pCur ) + Write( rStream, this ); + else { + switch( pCur->GetNodeType()) { + case XML_NODE_TYPE_FILE: { + if( GetChildList()) + for ( ULONG i = 0; i < GetChildList()->Count(); i++ ) + Write( rStream, GetChildList()->GetObject( i )); + } + break; + case XML_NODE_TYPE_ELEMENT: { + XMLElement *pElement = ( XMLElement * ) pCur; + rStream << "<"; + WriteString( rStream, pElement->GetName()); + if ( pElement->GetAttributeList()) + for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ) { + rStream << " "; + String sData(*pElement->GetAttributeList()->GetObject( j )); + xmlutil.QuotHTML( sData ); + WriteString( rStream , sData ); + rStream << "=\""; + sData=pElement->GetAttributeList()->GetObject( j )->GetValue(); + xmlutil.QuotHTML( sData ); + WriteString( rStream , sData ); + rStream << "\""; + } + if ( !pElement->GetChildList()) + rStream << "/>"; + else { + rStream << ">"; + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) + Write( rStream, pElement->GetChildList()->GetObject( k )); + rStream << "GetName()); + rStream << ">"; + } + } + break; + case XML_NODE_TYPE_DATA: { + XMLData *pData = ( XMLData * ) pCur; + String sData( pData->GetData()); + xmlutil.QuotHTML( sData ); + WriteString( rStream, sData ); + } + break; + case XML_NODE_TYPE_COMMENT: { + XMLComment *pComment = ( XMLComment * ) pCur; + rStream << ""; + } + break; + case XML_NODE_TYPE_DEFAULT: { + XMLDefault *pDefault = ( XMLDefault * ) pCur; + WriteString( rStream, pDefault->GetDefault()); + } + break; + } + } + return TRUE; +} + + +void XMLFile::Print( XMLNode *pCur, USHORT nLevel ) +{ + + if ( !pCur ) + Print( this ); + else { + switch( pCur->GetNodeType()) { + case XML_NODE_TYPE_FILE: { + if( GetChildList()) + for ( ULONG i = 0; i < GetChildList()->Count(); i++ ) + Print( GetChildList()->GetObject( i )); + } + break; + case XML_NODE_TYPE_ELEMENT: { + XMLElement *pElement = ( XMLElement * ) pCur; + + fprintf( stdout, "<%s", ByteString( pElement->GetName(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); + if ( pElement->GetAttributeList()) + for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ + ByteString aAttrName( *pElement->GetAttributeList()->GetObject( j ), RTL_TEXTENCODING_UTF8 ); + if( !aAttrName.EqualsIgnoreCaseAscii( XML_LANG ) ) { + fprintf( stdout, " %s=\"%s\"", + aAttrName.GetBuffer(), + ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(), + RTL_TEXTENCODING_UTF8 ).GetBuffer()); + } + } + if ( !pElement->GetChildList()) + fprintf( stdout, "/>" ); + else { + fprintf( stdout, ">" ); + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) + Print( pElement->GetChildList()->GetObject( k ), nLevel + 1 ); + fprintf( stdout, "", ByteString( pElement->GetName(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); + } + } + break; + case XML_NODE_TYPE_DATA: { + XMLData *pData = ( XMLData * ) pCur; + String sData = pData->GetData(); + fprintf( stdout, "%s", ByteString( sData, RTL_TEXTENCODING_UTF8 ).GetBuffer()); + } + break; + case XML_NODE_TYPE_COMMENT: { + XMLComment *pComment = ( XMLComment * ) pCur; + fprintf( stdout, "", ByteString( pComment->GetComment(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); + } + break; + case XML_NODE_TYPE_DEFAULT: { + XMLDefault *pDefault = ( XMLDefault * ) pCur; + fprintf( stdout, "%s", ByteString( pDefault->GetDefault(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); + } + break; + } + } +} +XMLFile::~XMLFile() +{ + if( XMLStrings != NULL ){ + XMLHashMap::iterator pos = XMLStrings->begin(); + for( ; pos != XMLStrings->end() ; ++pos ){ + delete pos->second; // Check and delete content also ? + } + delete XMLStrings; + XMLStrings = NULL; + } +} +/*****************************************************************************/ +XMLFile::XMLFile( const String &rFileName ) // the file name, empty if created from memory stream +/*****************************************************************************/ + : XMLParentNode( NULL ), + sFileName ( rFileName ), + ID ( "id" ), + OLDREF ( "oldref" ), + XML_LANG ( "xml-lang" ), + XMLStrings ( NULL ) + +{ +// nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("bookmark_value"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("bookmark"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("variable"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("paragraph"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("alt"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("caption"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("title"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); + nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("link"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); +} +/*****************************************************************************/ +void XMLFile::Extract( XMLFile *pCur ) +/*****************************************************************************/ +{ + if( XMLStrings != NULL ) delete XMLStrings; // Elements ? + + XMLStrings = new XMLHashMap(); + if ( !pCur ) + SearchL10NElements( this ); + else { + if( pCur->GetNodeType()==XML_NODE_TYPE_FILE) { + SearchL10NElements(pCur); + } + } +} + +/*****************************************************************************/ +void XMLFile::View(){ +/*****************************************************************************/ + XMLElement* cur; + for(XMLHashMap::iterator pos=XMLStrings->begin(); pos!=XMLStrings->end();++pos){ + fprintf(stdout,"\nid=%s\n",(pos->first).GetBuffer()); + LangHashMap* elem=pos->second; + for(LangHashMap::iterator pos2=elem->begin(); pos2!=elem->end();++pos2){ + fprintf( stdout,"\nlanguage=%s\n",(pos2->first).GetBuffer() ); + cur=pos2->second; + fprintf(stdout,"\n%s\n",((XMLElement*)cur)->ToOString().getStr()); + + } + } +} + +/*****************************************************************************/ +void XMLFile::InsertL10NElement( XMLElement* pElement ){ +/*****************************************************************************/ + ByteString tmpStr,id,oldref,language(""); + LangHashMap* elem; + + if( pElement->GetAttributeList() != NULL ){ + for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ + tmpStr=ByteString( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); + if( tmpStr.CompareTo(ID)==COMPARE_EQUAL ){ // Get the "id" Attribute + id = ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + } + if( tmpStr.CompareTo( XML_LANG ) == COMPARE_EQUAL ){ // Get the "xml-lang" Attribute + language = ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + } + + } + }else{ + fprintf(stdout,"XMLFile::InsertL10NElement: No AttributeList found"); + fprintf(stdout,"++++++++++++++++++++++++++++++++++++++++++++++++++"); + Print( pElement , 0 ); + fprintf(stdout,"++++++++++++++++++++++++++++++++++++++++++++++++++"); + } + + XMLHashMap::iterator pos = XMLStrings->find( id ); + if( pos == XMLStrings->end() ){ // No instanze , create new one + elem = new LangHashMap(); + (*elem)[ language ]=pElement; + XMLStrings->insert( XMLHashMap::value_type( id , elem ) ); + order.push_back( id ); + }else{ // Already there + elem=pos->second; + if ( (*elem)[ language ] ) + { + fprintf(stdout,"Error: Duplicated entry. ID = %s LANG = %s in File %s\n", id.GetBuffer(), language.GetBuffer(), ByteString( sFullName,RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); + exit( -1 ); + } + (*elem)[ language ]=pElement; + } +} +/*****************************************************************************/ +void XMLFile::showType(XMLParentNode* node){ +/*****************************************************************************/ + switch (node->GetNodeType()){ + case XML_NODE_TYPE_ELEMENT: fprintf(stdout,"ELEMENT\n") ;break; + case XML_NODE_TYPE_FILE: fprintf(stdout,"FILE\n") ;break; + case XML_NODE_TYPE_COMMENT: fprintf(stdout,"COMMENT\n") ;break; + case XML_NODE_TYPE_DATA: fprintf(stdout,"DATA\n") ;break; + case XML_NODE_TYPE_DEFAULT: fprintf(stdout,"DEFAULT\n") ;break; + default: break; + } +} +XMLFile::XMLFile() +/*****************************************************************************/ + : XMLParentNode( NULL ), + ID ( "id" ), + OLDREF ( "oldref" ), + XML_LANG ( "xml-lang" ), + XMLStrings ( NULL ){}; + + +XMLFile::XMLFile( const XMLFile& obj ) +/*****************************************************************************/ + : XMLParentNode( obj ), + sFileName ( obj.sFileName ), + ID ( "id" ), + OLDREF ( "oldref" ), + XML_LANG ( "xml-lang" ), + XMLStrings ( NULL ) +{ + if( this!=&obj ) + { + nodes_localize =obj.nodes_localize; + order =obj.order; + + } +} +/*****************************************************************************/ +XMLFile& XMLFile::operator=(const XMLFile& obj){ +/*****************************************************************************/ + if( this!=&obj ){ + + XMLParentNode::operator=(obj); + + nodes_localize =obj.nodes_localize; + order =obj.order; + + if( XMLStrings ) delete XMLStrings; + + if( obj.XMLStrings ) + { + XMLStrings = new XMLHashMap(); + for( XMLHashMap::iterator pos = obj.XMLStrings->begin() ; pos != obj.XMLStrings->end() ; ++pos ) + { + LangHashMap* elem=pos->second; + LangHashMap* newelem = new LangHashMap(); + for(LangHashMap::iterator pos2=elem->begin(); pos2!=elem->end();++pos2){ + (*newelem)[ pos2->first ] = new XMLElement( *pos2->second ); + printf("*"); + } + (*XMLStrings)[ pos->first ] = newelem; + } + } + } + printf("done!\n"); + return *this; +} + + +/*****************************************************************************/ +void XMLFile::SearchL10NElements( XMLParentNode *pCur , int pos) +/*****************************************************************************/ +{ + static const ByteString LOCALIZE("localize"); + static const ByteString THEID("id"); + bool bInsert = true; + if ( !pCur ) + SearchL10NElements( this ); + else { + switch( pCur->GetNodeType()) { + case XML_NODE_TYPE_FILE: { + XMLParentNode* pElement; + if( GetChildList()){ + for ( ULONG i = 0; i < GetChildList()->Count(); i++ ){ + pElement = (XMLParentNode*) GetChildList()->GetObject( i ); + if( pElement->GetNodeType() == XML_NODE_TYPE_ELEMENT ) SearchL10NElements( pElement , i); + } + } + } + break; + case XML_NODE_TYPE_ELEMENT: { + XMLElement *pElement = ( XMLElement * ) pCur; + ByteString sName(pElement->GetName(),RTL_TEXTENCODING_ASCII_US); + ByteString language,tmpStrVal,oldref; + if ( pElement->GetAttributeList()){ + for ( ULONG j = 0 , cnt = pElement->GetAttributeList()->Count(); j < cnt && bInsert; j++ ){ + const ByteString tmpStr( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); + if( tmpStr.CompareTo(THEID)==COMPARE_EQUAL ){ // Get the "id" Attribute + tmpStrVal=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + //printf("Checking id = %s\n",tmpStrVal.GetBuffer() ); + } + if( tmpStr.CompareTo(LOCALIZE)==COMPARE_EQUAL ){ // Get the "localize" Attribute + bInsert=false; + } + if( tmpStr.CompareTo(XML_LANG)==COMPARE_EQUAL ){ // Get the "xml-lang" Attribute + language=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + } + if( tmpStr.CompareTo(OLDREF)==COMPARE_EQUAL ){ // Get the "oldref" Attribute + oldref=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + } + } + pElement->SetLanguageId ( language ); + pElement->SetId ( tmpStrVal.GetBuffer() ); + pElement->SetOldRef ( oldref ); + pElement->SetPos( pos ); + } + + if ( bInsert && ( nodes_localize.find( sName.ToLowerAscii() ) != nodes_localize.end() ) ) + InsertL10NElement(pElement); + else if ( bInsert && pElement->GetChildList() ){ + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) + SearchL10NElements( (XMLParentNode*) pElement->GetChildList()->GetObject( k ) , k); + } + } + break; + case XML_NODE_TYPE_DATA: { + } + break; + case XML_NODE_TYPE_COMMENT: { + } + break; + case XML_NODE_TYPE_DEFAULT: { + } + break; + } + } +} + +/*****************************************************************************/ +bool XMLFile::CheckExportStatus( XMLParentNode *pCur ) +/*****************************************************************************/ +{ + static bool bStatusExport = true; + const ByteString LOCALIZE("localize"); + const ByteString STATUS("status"); + const ByteString PUBLISH("PUBLISH"); + const ByteString DEPRECATED("DEPRECATED"); + + const ByteString TOPIC("topic"); + bool bInsert = true; + if ( !pCur ) + CheckExportStatus( this ); + else { + switch( pCur->GetNodeType()) { + case XML_NODE_TYPE_FILE: { + XMLParentNode* pElement; + if( GetChildList()){ + for ( ULONG i = 0; i < GetChildList()->Count(); i++ ){ + pElement = (XMLParentNode*) GetChildList()->GetObject( i ); + if( pElement->GetNodeType() == XML_NODE_TYPE_ELEMENT ) CheckExportStatus( pElement );//, i); + } + } + } + break; + case XML_NODE_TYPE_ELEMENT: { + XMLElement *pElement = ( XMLElement * ) pCur; + ByteString sName(pElement->GetName(),RTL_TEXTENCODING_ASCII_US); + if( sName.EqualsIgnoreCaseAscii( TOPIC ) ){ + if ( pElement->GetAttributeList()){ + for ( ULONG j = 0 , cnt = pElement->GetAttributeList()->Count(); j < cnt && bInsert; j++ ){ + const ByteString tmpStr( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); + if( tmpStr.EqualsIgnoreCaseAscii( STATUS ) ){ + ByteString tmpStrVal=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); + if( !tmpStrVal.EqualsIgnoreCaseAscii( PUBLISH ) && + !tmpStrVal.EqualsIgnoreCaseAscii( DEPRECATED )){ + bStatusExport = false; + } + } + + } + } + } + else if ( pElement->GetChildList() ){ + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) + CheckExportStatus( (XMLParentNode*) pElement->GetChildList()->GetObject( k ) );//, k); + } + } + break; + } + } + return bStatusExport; +} + +/*****************************************************************************/ +USHORT XMLElement::GetNodeType() +/*****************************************************************************/ +{ + return XML_NODE_TYPE_ELEMENT; +} + +/*****************************************************************************/ +XMLElement::XMLElement(const XMLElement& obj) +/*****************************************************************************/ + : + XMLParentNode ( obj ), + sElementName ( obj.sElementName ), + pAttributes ( NULL ), + project ( obj.project ), + filename ( obj.filename ), + id ( obj.id ), + sOldRef ( obj.sOldRef ), + resourceType ( obj.resourceType ), + languageId ( obj.languageId ), + nPos ( obj.nPos ) + +{ + if ( obj.pAttributes ){ + pAttributes = new XMLAttributeList(); + for ( ULONG i = 0; i < obj.pAttributes->Count(); i++ ) + AddAttribute( *obj.pAttributes->GetObject( i ) , obj.pAttributes->GetObject( i )->GetValue() ); + } +} + +/*****************************************************************************/ +XMLElement& XMLElement::operator=(const XMLElement& obj){ +/*****************************************************************************/ + if( this!=&obj ){ + XMLParentNode::operator=(obj); + sElementName =obj.sElementName; + project =obj.project; + filename =obj.filename; + id =obj.id; + sOldRef =obj.sOldRef; + resourceType =obj.resourceType; + languageId =obj.languageId; + nPos =obj.nPos; + + if ( pAttributes ){ + for ( ULONG i = 0; i < pAttributes->Count(); i++ ) + delete pAttributes->GetObject( i ); + delete pAttributes; + } + if ( obj.pAttributes ){ + pAttributes =new XMLAttributeList(); + for ( ULONG i = 0; i < obj.pAttributes->Count(); i++ ) + AddAttribute( *obj.pAttributes->GetObject( i ) , obj.pAttributes->GetObject( i )->GetValue() ); + } + } + return *this; +} + +/*****************************************************************************/ +void XMLElement::AddAttribute( const String &rAttribute, const String &rValue ) +/*****************************************************************************/ +{ + if ( !pAttributes ) + pAttributes = new XMLAttributeList(); + pAttributes->Insert( new XMLAttribute( rAttribute, rValue ), LIST_APPEND ); +} + +/*****************************************************************************/ +void XMLElement::ChangeLanguageTag( const String &rValue ){ +/*****************************************************************************/ + static const String rName = String::CreateFromAscii("xml-lang"); + SetLanguageId( ByteString(rValue,RTL_TEXTENCODING_UTF8) ); + if ( pAttributes ){ + for ( ULONG i = 0; i < pAttributes->Count(); i++ ){ + if ( *pAttributes->GetObject( i ) == rName ){ + pAttributes->GetObject( i )->setValue(rValue); + } + } + } + XMLChildNode* pNode = NULL; + XMLElement* pElem = NULL; + XMLChildNodeList* pCList = GetChildList(); + + if( pCList != NULL ){ + for ( ULONG i = 0; i < pCList->Count(); i++ ){ + pNode = pCList->GetObject( i ); + if( pNode != NULL && pNode->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ + pElem = static_cast< XMLElement* >(pNode); + pElem->ChangeLanguageTag( rValue ); + pElem->SetLanguageId( ByteString(rValue,RTL_TEXTENCODING_UTF8) ); + pElem = NULL; + pNode = NULL; + } + } + pCList = NULL; + } +} +/*****************************************************************************/ +XMLAttribute *XMLElement::GetAttribute( const String &rName ) +/*****************************************************************************/ +{ + if ( pAttributes ) + for ( ULONG i = 0; i < pAttributes->Count(); i++ ) + if ( *pAttributes->GetObject( i ) == rName ) + return pAttributes->GetObject( i ); + + return NULL; +} + +/*****************************************************************************/ +XMLElement::~XMLElement() +/*****************************************************************************/ +{ + if ( pAttributes ) { + for ( ULONG i = 0; i < pAttributes->Count(); i++ ) + delete pAttributes->GetObject( i ); + + delete pAttributes; + pAttributes = NULL; + } +} +/*****************************************************************************/ +bool XMLElement::Equals(OUString refStr){ +/*****************************************************************************/ + return refStr.equals( ToOUString() ); +} + +/*****************************************************************************/ +OString XMLElement::ToOString(){ +/*****************************************************************************/ + OUString ouEmpty; + + OUStringBuffer* buffer = new OUStringBuffer(); + Print( this, *buffer , true ); + + OString result( (sal_Unicode* )buffer->getStr(), buffer->getLength() , RTL_TEXTENCODING_UTF8 ); + delete buffer; + return result; +} +/*****************************************************************************/ +OUString XMLElement::ToOUString(){ +/*****************************************************************************/ + OUStringBuffer* buffer = new OUStringBuffer(); + Print(this,*buffer,true); + OUString result=buffer->makeStringAndClear(); + String xy(result.getStr()); + result=OUString(xy); + delete buffer; + return result; +} +/*****************************************************************************/ +void XMLElement::Print(XMLNode *pCur, OUStringBuffer& buffer , bool rootelement ){ +/*****************************************************************************/ + //YD FIXME somewhere COMMENT is defined as 4! + static const String _COMMENT = String::CreateFromAscii("comment"); + static const OUString XML_LANG ( OUString::createFromAscii("xml-lang") ); + + if(pCur!=NULL){ + if(rootelement){ + XMLElement *pElement = ( XMLElement * ) pCur; + if ( pElement->GetAttributeList()){ + if ( pElement->GetChildList()){ + XMLChildNode* tmp=NULL; + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ){ + tmp=pElement->GetChildList()->GetObject( k ); + Print( tmp, buffer , false); + } + } + } + } + else{ + + switch( pCur->GetNodeType()) { + case XML_NODE_TYPE_ELEMENT: { + XMLElement *pElement = ( XMLElement * ) pCur; + + if( !pElement->GetName().EqualsIgnoreCaseAscii( _COMMENT ) ){ + buffer.append( OUString::createFromAscii("\\<") ); + buffer.append( pElement->GetName() ); + if ( pElement->GetAttributeList()){ + for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ + + OUString aAttrName( *pElement->GetAttributeList()->GetObject( j ) ); + if( !aAttrName.equalsIgnoreAsciiCase( XML_LANG ) ) { + buffer.append( OUString::createFromAscii(" ") ); + buffer.append( aAttrName ); + buffer.append( OUString::createFromAscii("=") ); + buffer.append( OUString::createFromAscii("\\\"") ); + buffer.append( pElement->GetAttributeList()->GetObject( j )->GetValue() ); + buffer.append( OUString::createFromAscii("\\\"") ); + } + } + } + if ( !pElement->GetChildList()) + buffer.append( OUString::createFromAscii("/\\>") ); + else { + buffer.append( OUString::createFromAscii("\\>") ); + XMLChildNode* tmp=NULL; + for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ){ + tmp=pElement->GetChildList()->GetObject( k ); + Print( tmp, buffer , false); + } + buffer.append( OUString::createFromAscii("\\GetName() ); + buffer.append( OUString::createFromAscii("\\>") ); + } + } + } + break; + case XML_NODE_TYPE_DATA: { + XMLData *pData = ( XMLData * ) pCur; + String sData = pData->GetData(); + buffer.append( sData ); + } + break; + case XML_NODE_TYPE_COMMENT: { + XMLComment *pComment = ( XMLComment * ) pCur; + buffer.append( OUString::createFromAscii("") ); + } + break; + case XML_NODE_TYPE_DEFAULT: { + XMLDefault *pDefault = ( XMLDefault * ) pCur; + buffer.append( pDefault->GetDefault() ); + } + break; + } + } + }else { + fprintf(stdout,"\n#+------Error: NULL Pointer in XMLELement::Print------+#\n"); + return; + } +} + + +// +// class XMLData +// +/*****************************************************************************/ +XMLData::XMLData(const XMLData& obj) +/*****************************************************************************/ + : XMLChildNode( obj ), + sData( obj.sData ) , + isNewCreated ( obj.isNewCreated ){} + +/*****************************************************************************/ +XMLData& XMLData::operator=(const XMLData& obj){ +/*****************************************************************************/ + if( this!=&obj ){ + XMLChildNode::operator=( obj ); + sData = obj.sData; + isNewCreated = obj.isNewCreated; + } + return *this; +} +/*****************************************************************************/ +void XMLData::AddData( const String &rData) { +/*****************************************************************************/ + sData += rData; +} + +/*****************************************************************************/ +USHORT XMLData::GetNodeType() +/*****************************************************************************/ +{ + return XML_NODE_TYPE_DATA; +} + +// +// class XMLComment +// + +/*****************************************************************************/ +USHORT XMLComment::GetNodeType() +/*****************************************************************************/ +{ + return XML_NODE_TYPE_COMMENT; +} +/*****************************************************************************/ +XMLComment::XMLComment(const XMLComment& obj) +/*****************************************************************************/ + : XMLChildNode( obj ), + sComment( obj.sComment ){} + +/*****************************************************************************/ +XMLComment& XMLComment::operator=(const XMLComment& obj){ +/*****************************************************************************/ + if( this!=&obj ){ + XMLChildNode::operator=( obj ); + sComment = obj.sComment; + } + return *this; +} + +// +// class XMLDefault +// + +/*****************************************************************************/ +USHORT XMLDefault::GetNodeType() +/*****************************************************************************/ +{ + return XML_NODE_TYPE_DEFAULT; +} +/*****************************************************************************/ +XMLDefault::XMLDefault(const XMLDefault& obj) +/*****************************************************************************/ + : XMLChildNode( obj ), + sDefault( obj.sDefault){} + +/*****************************************************************************/ +XMLDefault& XMLDefault::operator=(const XMLDefault& obj){ +/*****************************************************************************/ + if( this!=&obj ){ + XMLChildNode::operator=( obj ); + sDefault = obj.sDefault; + } + return *this; +} + + +// +// class SimpleXMLParser +// + +#define XML_CHAR_TO_OUSTRING(x) OStringToOUString(OString(x), RTL_TEXTENCODING_UTF8) +#define XML_CHAR_N_TO_OUSTRING(x,n) OStringToOUString(OString(x,n), RTL_TEXTENCODING_UTF8 ) + + +/*****************************************************************************/ +SimpleXMLParser::SimpleXMLParser() +/*****************************************************************************/ + : pXMLFile( NULL ) +{ + aParser = XML_ParserCreate( NULL ); + XML_SetUserData( aParser, this ); + XML_SetElementHandler( aParser, (XML_StartElementHandler) StartElementHandler, (XML_EndElementHandler) EndElementHandler ); + XML_SetCharacterDataHandler( aParser, (XML_CharacterDataHandler) CharacterDataHandler ); + XML_SetCommentHandler( aParser, (XML_CommentHandler) CommentHandler ); + XML_SetDefaultHandler( aParser, (XML_DefaultHandler) DefaultHandler ); +} + +/*****************************************************************************/ +SimpleXMLParser::~SimpleXMLParser() +/*****************************************************************************/ +{ + XML_ParserFree( aParser ); +} + +/*****************************************************************************/ +void SimpleXMLParser::StartElementHandler( + void *userData, const XML_Char *name, const XML_Char **atts ) +/*****************************************************************************/ +{ + (( SimpleXMLParser * ) userData )->StartElement( name, atts ); +} + + +/*****************************************************************************/ +void SimpleXMLParser::EndElementHandler( + void *userData, const XML_Char *name ) +/*****************************************************************************/ +{ + (( SimpleXMLParser * ) userData )->EndElement( name ); +} + +/*****************************************************************************/ +void SimpleXMLParser::CharacterDataHandler( + void *userData, const XML_Char *s, int len ) +/*****************************************************************************/ +{ + (( SimpleXMLParser * ) userData )->CharacterData( s, len ); +} + +/*****************************************************************************/ +void SimpleXMLParser::CommentHandler( + void *userData, const XML_Char *data ) +/*****************************************************************************/ +{ + (( SimpleXMLParser * ) userData )->Comment( data ); +} + +/*****************************************************************************/ +void SimpleXMLParser::DefaultHandler( + void *userData, const XML_Char *s, int len ) +/*****************************************************************************/ +{ + (( SimpleXMLParser * ) userData )->Default( s, len ); +} + +/*****************************************************************************/ +void SimpleXMLParser::StartElement( + const XML_Char *name, const XML_Char **atts ) +/*****************************************************************************/ +{ + String sElementName = String( XML_CHAR_TO_OUSTRING( name )); + XMLElement *pElement = new XMLElement( sElementName, ( XMLParentNode * ) pCurNode ); + pCurNode = pElement; + pCurData = NULL; + + int i = 0; + while( atts[i] ) { + pElement->AddAttribute( + String( XML_CHAR_TO_OUSTRING( atts[ i ] )), + String( XML_CHAR_TO_OUSTRING( atts[ i + 1 ] ))); + i += 2; + } +} + +/*****************************************************************************/ +void SimpleXMLParser::EndElement( const XML_Char *name ) +/*****************************************************************************/ +{ + // This variable is not used at all, but the the sax C interface can't be changed + // To prevent warnings this dummy assignment is used + // +++ + (void) name; + + pCurNode = pCurNode->GetParent(); + pCurData = NULL; +} + +/*****************************************************************************/ +void SimpleXMLParser::CharacterData( + const XML_Char *s, int len ) +/*****************************************************************************/ +{ + if ( !pCurData ){ + String x=String( XML_CHAR_N_TO_OUSTRING( s, len )); + XMLUtil::UnQuotHTML(x); + pCurData = new XMLData( x , pCurNode ); + }else{ + String x=String( XML_CHAR_N_TO_OUSTRING( s, len )); + XMLUtil::UnQuotHTML(x); + pCurData->AddData( x ); + + } +} + +/*****************************************************************************/ +void SimpleXMLParser::Comment( + const XML_Char *data ) +/*****************************************************************************/ +{ + pCurData = NULL; + new XMLComment( String( XML_CHAR_TO_OUSTRING( data )), pCurNode ); +} + +/*****************************************************************************/ +void SimpleXMLParser::Default( + const XML_Char *s, int len ) +/*****************************************************************************/ +{ + pCurData = NULL; + new XMLDefault( + String( XML_CHAR_N_TO_OUSTRING( s, len )), pCurNode ); +} + +/*****************************************************************************/ +XMLFile *SimpleXMLParser::Execute( const String &rFullFileName , const String &rFileName, XMLFile* pXMLFileIn ) +/*****************************************************************************/ +{ +// printf("DBG: SimpleXMLParser::Execute( %s )", ByteString( rFileName , RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); + aErrorInformation.eCode = XML_ERROR_NONE; + aErrorInformation.nLine = 0; + aErrorInformation.nColumn = 0; + aErrorInformation.sMessage = String::CreateFromAscii( "ERROR: Unable to open file " ); + aErrorInformation.sMessage += rFileName; + + SvFileStream aStream( rFileName, STREAM_STD_READ ); + + if ( !aStream.IsOpen()) + return NULL; + + SvMemoryStream aMemStream; + aStream >> aMemStream; + aMemStream.Seek( 0 ); + + aStream.Close(); + + pXMLFile = pXMLFileIn; + pXMLFile->SetName( rFileName ); + pXMLFile->SetFullName( rFullFileName ); + + return Execute( &aMemStream ); +} + +/*****************************************************************************/ +XMLFile *SimpleXMLParser::Execute( SvMemoryStream *pStream ) +/*****************************************************************************/ +{ + if ( !pXMLFile ) + pXMLFile = new XMLFile( String()); + + pCurNode = pXMLFile; + pCurData = NULL; + + ULONG nPos = pStream->Tell(); + pStream->Seek( STREAM_SEEK_TO_END ); + + aErrorInformation.eCode = XML_ERROR_NONE; + aErrorInformation.nLine = 0; + aErrorInformation.nColumn = 0; + if ( pXMLFile->GetName().Len()) { + aErrorInformation.sMessage = String::CreateFromAscii( "File " ); + aErrorInformation.sMessage += pXMLFile->GetName(); + aErrorInformation.sMessage += String::CreateFromAscii( " parsed succesfully" ); + } + else + aErrorInformation.sMessage = String::CreateFromAscii( "XML-File parsed successfully" ); + + if ( !XML_Parse( + aParser, ( char * ) pStream->GetData() + nPos, pStream->Tell() - nPos, TRUE )) + { + aErrorInformation.eCode = XML_GetErrorCode( aParser ); + aErrorInformation.nLine = XML_GetErrorLineNumber( aParser ); + aErrorInformation.nColumn = XML_GetErrorColumnNumber( aParser ); + + aErrorInformation.sMessage = String::CreateFromAscii( "ERROR: " ); + if ( pXMLFile->GetName().Len()) + aErrorInformation.sMessage += pXMLFile->GetName(); + else + aErrorInformation.sMessage += String::CreateFromAscii( "XML-File" ); + aErrorInformation.sMessage += String::CreateFromAscii( " (" ); + aErrorInformation.sMessage += String::CreateFromInt64( aErrorInformation.nLine ); + aErrorInformation.sMessage += String::CreateFromAscii( "," ); + aErrorInformation.sMessage += String::CreateFromInt64( aErrorInformation.nColumn ); + aErrorInformation.sMessage += String::CreateFromAscii( "): " ); + + switch( aErrorInformation.eCode ) { + case XML_ERROR_NO_MEMORY: aErrorInformation.sMessage += String::CreateFromAscii( "No memory" ); break; + case XML_ERROR_SYNTAX: aErrorInformation.sMessage += String::CreateFromAscii( "Syntax" ); break; + case XML_ERROR_NO_ELEMENTS: aErrorInformation.sMessage += String::CreateFromAscii( "No elements" ); break; + case XML_ERROR_INVALID_TOKEN: aErrorInformation.sMessage += String::CreateFromAscii( "Invalid token" ); break; + case XML_ERROR_UNCLOSED_TOKEN: aErrorInformation.sMessage += String::CreateFromAscii( "Unclosed token" ); break; + case XML_ERROR_PARTIAL_CHAR: aErrorInformation.sMessage += String::CreateFromAscii( "Partial char" ); break; + case XML_ERROR_TAG_MISMATCH: aErrorInformation.sMessage += String::CreateFromAscii( "Tag mismatch" ); break; + case XML_ERROR_DUPLICATE_ATTRIBUTE: aErrorInformation.sMessage += String::CreateFromAscii( "Dublicat attribute" ); break; + case XML_ERROR_JUNK_AFTER_DOC_ELEMENT: aErrorInformation.sMessage += String::CreateFromAscii( "Junk after doc element" ); break; + case XML_ERROR_PARAM_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Param entity ref" ); break; + case XML_ERROR_UNDEFINED_ENTITY: aErrorInformation.sMessage += String::CreateFromAscii( "Undefined entity" ); break; + case XML_ERROR_RECURSIVE_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Recursive entity ref" ); break; + case XML_ERROR_ASYNC_ENTITY: aErrorInformation.sMessage += String::CreateFromAscii( "Async_entity" ); break; + case XML_ERROR_BAD_CHAR_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Bad char ref" ); break; + case XML_ERROR_BINARY_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Binary entity" ); break; + case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Attribute external entity ref" ); break; + case XML_ERROR_MISPLACED_XML_PI: aErrorInformation.sMessage += String::CreateFromAscii( "Misplaced xml pi" ); break; + case XML_ERROR_UNKNOWN_ENCODING: aErrorInformation.sMessage += String::CreateFromAscii( "Unknown encoding" ); break; + case XML_ERROR_INCORRECT_ENCODING: aErrorInformation.sMessage += String::CreateFromAscii( "Incorrect encoding" ); break; + case XML_ERROR_UNCLOSED_CDATA_SECTION: aErrorInformation.sMessage += String::CreateFromAscii( "Unclosed cdata section" ); break; + case XML_ERROR_EXTERNAL_ENTITY_HANDLING: aErrorInformation.sMessage += String::CreateFromAscii( "External entity handling" ); break; + case XML_ERROR_NOT_STANDALONE: aErrorInformation.sMessage += String::CreateFromAscii( "Not standalone" ); break; + case XML_ERROR_NONE: break; + default: + break; + + } + delete pXMLFile; + pXMLFile = NULL; + } + pStream->Seek( nPos ); + + return pXMLFile; +} + +/*****************************************************************************/ +void XMLUtil::QuotHTML( String &rString ) +/*****************************************************************************/ +{ + OUStringBuffer sReturn; + static const String LT(String::CreateFromAscii("<")); + static const String QLT(String::CreateFromAscii("<")); + static const String GT(String::CreateFromAscii(">")); + static const String QGT(String::CreateFromAscii(">")); + static const String QUOT(String::CreateFromAscii("\\")); + static const String QQUOT(String::CreateFromAscii(""")); + static const String APOS(String::CreateFromAscii("\"")); + static const String QAPOS(String::CreateFromAscii("'")); + static const String AMP(String::CreateFromAscii("&")); + static const String QAMP(String::CreateFromAscii("&")); + static const String SLASH(String::CreateFromAscii("\\")); + + for ( USHORT i = 0; i < rString.Len(); i++) { + if ( i < rString.Len()) { + switch ( rString.GetChar( i )) { + case '\\': if( i+1 <= rString.Len() ){ + switch( rString.GetChar( i+1 ) ){ + case '<': sReturn.append( LT );i++;break; + case '>': sReturn.append( GT );i++;break; + case '\\': sReturn.append( QUOT );i++;break; + case '\"': sReturn.append( APOS );i++;break; + //case '\'': sReturn += "\'";i++;break; + //case '&' : sRetrun += "&";i++;break; + default: sReturn.append( SLASH );break; + + } + } + break; + + case '<': + sReturn.append( QLT ); + break; + + case '>': + sReturn.append( QGT ); + break; + + case '\"': + sReturn.append( QQUOT ); + break; + +/* case '\'': + sReturn += "'"; + break; +*/ + case '&': + if ( + ( ( i + 4 ) < rString.Len()) && + ( String( rString.Copy( i, 5 ) ).Equals( QAMP ) ) + ) + sReturn.append( rString.GetChar( i ) ); + else + sReturn.append( QAMP ); + break; + + default: + sReturn.append( rString.GetChar( i ) ); + break; + } + } + } + rString = String( sReturn.makeStringAndClear() ); +} + +void XMLUtil::UnQuotHTML( String &rString ){ + UnQuotData( rString ); +} + +void XMLUtil::UnQuotData( String &rString_in ){ + ByteString sReturn; + ByteString sString( rString_in , RTL_TEXTENCODING_UTF8 ); + while ( sString.Len()) { + if ( sString.Copy( 0, 1 ) == "\\" ) { + sReturn += "\\\\"; + sString.Erase( 0, 1 ); + } + else if ( sString.Copy( 0, 5 ) == "&" ) { + sReturn += "&"; + sString.Erase( 0, 5 ); + } + else if ( sString.Copy( 0, 4 ) == "<" ) { + sReturn += "<"; + sString.Erase( 0, 4 ); + } + else if ( sString.Copy( 0, 4 ) == ">" ) { + sReturn += ">"; + sString.Erase( 0, 4 ); + } + else if ( sString.Copy( 0, 6 ) == """ ) { + sReturn += "\""; + sString.Erase( 0, 6 ); + } + else if ( sString.Copy( 0, 6 ) == "'" ) { + sReturn += "\'"; + sString.Erase( 0, 6 ); + } + else { + sReturn += sString.GetChar( 0 ); + sString.Erase( 0, 1 ); + } + } + rString_in = String(sReturn , RTL_TEXTENCODING_UTF8 ); + + +} + +XMLUtil::XMLUtil(){ +} + + +/*****************************************************************************/ +void XMLUtil::dump(){ +/*****************************************************************************/ + int cnt=1; + printf("size=%lu\n",static_cast(lMap.size())); + for(HashMap::iterator pos = lMap.begin(); pos != lMap.end() ; ++pos){ + fprintf(stdout,"key=%s , value=%d , no=%d\n",pos->first.GetBuffer(),pos->second,cnt++); + } +} +/*****************************************************************************/ +XMLUtil& XMLUtil::Instance(){ +/*****************************************************************************/ + static XMLUtil instance; + return instance; +} +/*****************************************************************************/ +XMLUtil::~XMLUtil(){} +/*****************************************************************************/ +/*****************************************************************************/ +ByteString XMLUtil::GetIsoLangByIndex( USHORT nIndex ) +/*****************************************************************************/ +{ + if(nIndex > 0 && MAX_LANGUAGES >= nIndex ) + return isoArray[nIndex]; + return ""; +} + diff --git a/l10ntools/source/xrm_yy_wrapper.c b/l10ntools/source/xrm_yy_wrapper.c new file mode 100644 index 000000000000..6a304d0d09dc --- /dev/null +++ b/l10ntools/source/xrm_yy_wrapper.c @@ -0,0 +1,2 @@ +// Helper to suppress warnings in lex generated c code, see #i57362# +#include "xrm_yy.c" diff --git a/l10ntools/source/xrmlex.l b/l10ntools/source/xrmlex.l new file mode 100644 index 000000000000..efc8bf1f7d91 --- /dev/null +++ b/l10ntools/source/xrmlex.l @@ -0,0 +1,228 @@ +%{ +/* + * lexer for parsing xml-property source files (*.xml) + * + */ + + +/* enlarge token buffer to tokenize whole strings */ +#undef YYLMAX +#define YYLMAX 64000 + +/* to enable debug output define LEXDEBUG */ +#define LEXDEBUG 1 +#ifdef LEXDEBUG +#define OUTPUT fprintf +#else +#define OUTPUT(Par1,Par2); +#endif + +/* table of possible token ids */ +#include "tokens.h" +#include +#include + +#if defined __GNUC__ +#pragma GCC system_header +#elif defined __SINPRO_CC +#pragma disable_warn +#elif defined _MSC_VER +#pragma warning(push, 1) +#endif + +/* external functions (C++ code, declared as extren "C" */ +extern int WorkOnTokenSet( int, char* ); +extern int Argument( char * ); +extern int InitXrmExport( char * , char * ); +extern int EndXrmExport(); +extern int GetError(); +extern int SetError(); +extern char *GetOutputFile( int argc, char* argv[]); +extern FILE *GetXrmFile(); +extern int isQuiet(); +extern void removeTempFile(); +extern char* getFilename(); + +/* forwards */ +void YYWarning(); + +int bText=0; +%} + +%p 24000 +%e 1200 +%n 500 + +%% + +"]*\> { + WorkOnTokenSet( XRM_README_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_README_END, yytext ); +} + +"]*\> { + WorkOnTokenSet( XRM_README_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_README_END, yytext ); +} + +"]*\> { + WorkOnTokenSet( XRM_SECTION_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_SECTION_END, yytext ); +} + +"]*\> { + WorkOnTokenSet( XRM_PARAGRAPH_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_PARAGRAPH_END, yytext ); +} + +"]*\> { + WorkOnTokenSet( XRM_TEXT_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_TEXT_END, yytext ); +} + +"]*\> { + WorkOnTokenSet( XRM_LIST_START, yytext ); +} + +"" { + WorkOnTokenSet( XRM_LIST_END, yytext ); +} + +" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <i>Copyright &#169; 2004 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303 USA</i> -
${docname}
- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- diff --git a/transex3/java/l10nconv/converter.MF b/transex3/java/l10nconv/converter.MF deleted file mode 100755 index 843d500b7548..000000000000 --- a/transex3/java/l10nconv/converter.MF +++ /dev/null @@ -1 +0,0 @@ -Main-Class: com.sun.star.tooling.converter.Convert diff --git a/transex3/java/l10nconv/documentation/readmeConverter.sxw b/transex3/java/l10nconv/documentation/readmeConverter.sxw deleted file mode 100755 index f779e10acb2c..000000000000 Binary files a/transex3/java/l10nconv/documentation/readmeConverter.sxw and /dev/null differ diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java b/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java deleted file mode 100755 index d304c2544bff..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapCheck.java +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: DirtyTagWrapCheck.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.DirtyTags; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - - - -public class DirtyTagWrapCheck { - static String line=""; - public static void main(String[] args) { - try { - File fi = new File("D:\\Testfiles\\KID_helpcontent.sdf");//Copy of - FileReader fr = new FileReader(fi); - BufferedReader br = new BufferedReader(fr); - - int readCounter=0; - int missCounter=0; - int lineErrorCounter=0; - while((line=br.readLine())!=null){ - readCounter++; - String [] split = line.split("\t"); - if(split.length<15){ - - lineErrorCounter++; - continue; - } - String string = split[10]; - String wrapped = DirtyTagWrapper.wrapString(string); - String unwrapped=DirtyTagWrapper.unwrapString(wrapped); - if(!string.equals(unwrapped)){ - - missCounter++; - System.out.println(""+readCounter+"\n"+string+"\n"+unwrapped+"\n"+wrapped+"\n"); - } - } - System.out.println("Fertig "+readCounter+" "+missCounter+" "+lineErrorCounter); - } catch (FileNotFoundException e) { - // - e.printStackTrace(); - } catch (IOException e) { - // - e.printStackTrace(); - } catch (DirtyTagWrapper.TagWrapperException e) { - System.out.println(e.getMessage()+"\n"+line+"\n"); - - } - - } -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java b/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java deleted file mode 100755 index 49fc08b69d32..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/DirtyTagWrapper.java +++ /dev/null @@ -1,252 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: DirtyTagWrapper.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.DirtyTags; - -import java.io.IOException; -import java.util.ArrayList; - -/** - * Solves the problem with translating strings from the - * Star-Office Help. This Strings contain XML snippets - * (that means parts of an xml dokument). I call them 'dirty' - * because the start of a tag (<) and the and of an tag (>) - * are quoted by a single backslash(\<.....\>). This is done - * because the text out of th tags should not contain '<' and '>' - * as Entity references (< or >) but as readable signs. - * This is for translation purposes. - * Because translators get mad while find out the really translatable - * parts between all the markup information, the XLIFF Specification - * allows to wrap parts of a String that should not be translated by - * special tags (, ). - * This Class has two static methods that do the wrapping and unwrapping - * NOTE: this won't work with not 'dirty' Strings. - * - * @author Christian Schmidt 2005 - * - */ -public class DirtyTagWrapper { - - private static boolean doWrap=true; - public static void setWrapping(boolean doWrap){ - DirtyTagWrapper.doWrap=doWrap; - } - - /** - * Unwraps the 'dirty' parts of a String from ept and bpt tags - * - * @param checkString The String to unwrap - * @return the unwrapped String - */ - public static String unwrapString(String checkString){ - //remove the ept and bpt tags - String[] splitted =checkString.split("(])*>)|()|(])*>)|()|(])*>)|()|(])*/>)"); - StringBuffer workBuffer= new StringBuffer(); - for(int i=0;i").replaceAll( ""","\"").replaceAll( "'","'"); - - //remove the nsub tags - splitted =string.split("(])*>)|()"); - StringBuffer returnBuffer= new StringBuffer(); - for(int i=0;i"); - - ArrayList tagString =new ArrayList(); - // put the while splitting lost parts to the end of the single strings - for(int j=0;j")){ - parts2[parts2.length-1]+="\\>"; - } - // split the leading text from the real tag string (<...>) - for(int j=0;j0&&parts2[j].indexOf("\\>")>0){ - //...then split it in two parts - // the leading text - tagString.add(parts2[j].substring(0,(parts2[j].indexOf("\\<")))); - // ...and the tag - tagString.add(parts2[j].substring(parts2[j].indexOf("\\<"))); - - }else{ - //no tag...must be text only - tagString.add(parts2[j]); - } - - } - ArrayList tagNames=new ArrayList(); - String item=""; - for(int i=0;i"); - if(start>=0&&end>0){ - boolean isStandalone=false; - if(item.endsWith("/\\>")){ - // this is a standalone tag - isStandalone=true; - } - item=item.substring(start,end); - - if(item.indexOf(" ")>0){ - item=item.substring(0,item.indexOf(" ")); - } - if(isStandalone){ - item=item+"/"; - } - tagNames.add(item); - }else{ - tagNames.add(""); - } - } - ArrayList tagType=new ArrayList(); - for(int i=0;i0){ - try{ - start=new TagPair(tagList); - returnBuffer.append(start.getWrapped()); - }catch(TagPair.TagPairConstructionException e){ - throw (new DirtyTagWrapper()).new TagWrapperException(e); - } - } - TagPair.resetCounter(); - return new String(returnBuffer); - } - /** - * @author Christian Schmidt 2005 - * - */ - public class TagWrapperException extends Exception { - - /** - * Create a new Instance of TagWrapperException - * - * - */ - public TagWrapperException() { - super(); - // - } - - /** - * Create a new Instance of TagWrapperException - * - * @param arg0 - */ - public TagWrapperException(String arg0) { - super(arg0); - // - } - - /** - * Create a new Instance of TagWrapperException - * - * @param arg0 - * @param arg1 - */ - public TagWrapperException(String arg0, Throwable arg1) { - super(arg0, arg1); - // - } - - /** - * Create a new Instance of TagWrapperException - * - * @param arg0 - */ - public TagWrapperException(Throwable arg0) { - super(arg0); - // - } - - } -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java b/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java deleted file mode 100755 index 7495736ab68c..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/Tag.java +++ /dev/null @@ -1,249 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Tag.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.DirtyTags; - -import java.io.IOException; -import java.util.Map; - -import com.sun.star.tooling.converter.ExtMap; - -/** - * @author Christian Schmidt 2005 - * - */ -public class Tag { - private static int indent=0; - Map tagNames; - private String tagType; - private String tagName; - private String tagString; - public static Tag EMPTYTAG=new Tag("","",""); - - /** - * Create a new Instance of Tag - * - * @param tagType - * @param tagName - * @param tagString - */ - public Tag(String tagType, String tagName, String tagString) { - - this.tagType=tagType; - this.tagName=tagName; - this.tagString=tagString; - - tagNames=new ExtMap(); - tagNames.put("link","name"); - tagNames.put("caption","xml-lang"); - tagNames.put("alt","xml-lang"); - } - - public String getWrappedTagString() throws IOException{ - if(this.canHaveTranslateableContent()){ - return this.wrapTagStringIntern(); - }else{ - return xmlString(this.tagString); - } - } - - private final String xmlString( final String string) throws java.io.IOException { - if (string == null) - return string; // "" - String str = string; - - for(int i=0;i'){ - str=str.substring(0, i)+">"+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='"'){ - str=str.substring(0, i)+"""+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='\''){ - str=str.substring(0, i)+"'"+str.substring(i+1); - continue; - } - } - - return str; - } - /** - * @return - */ - private boolean canHaveTranslateableContent() { - return (tagNames.containsKey(this.tagName)); - - } - - /** - * @throws IOException - * - */ - private String wrapTagStringIntern() throws IOException { - - - String[] split=this.tagString.split("="); - int length=split.length; - // no attribute found; - if (length==0) return xmlString(tagString); - else{ - int i=0; - - while(i")<0) split[i]=xmlString(split[i]); - i++; - String value; - attributeName=(attributeName.substring(attributeName.lastIndexOf(" ")).trim()); - if((value=translateableAttributeValue(this.tagName)).equals(attributeName)){ - int valueStart=0; - int valueEnd=0; - - // get the value to the found attribute name - // it must either be surrounded by '"'... - if((valueStart=split[i].indexOf('"'))>=0){ - valueEnd = split[i].lastIndexOf('"'); - //...or surrounded by "'" - }else if((valueStart=split[i].indexOf("'"))>=0){ - valueEnd = split[i].lastIndexOf("'"); - }else{ - // there seems to be an error, - // we found an '=' (we split there) but no '"' or ''' - // but although we don't check the syntax - // we just continue - continue; - } - //ok we found the border of a value that might be translated - //now we wrap it with the tags - - split[i]=xmlString(split[i].substring(0,valueStart+1))+""+xmlString(split[i].substring(valueStart+1,valueEnd))+""+xmlString(split[i].substring(valueEnd)); - - } - } - String wrappedString=""; - // we have the wrapped parts, now we put them together - int j=0; - for(j=0;j=0&&end>0){ - tagString=tagString.substring(start,end); - - if(tagString.indexOf(" ")>0){ - tagString=tagString.substring(0,tagString.indexOf(" ")); - } - return tagString; - }else{ - return ""; - } - } - private static String extractTagType(String tagName){ - if(tagName.equals("")){ - return "Text"; - }else if(tagName.startsWith("/")){ - return "EndTag"; - }else if(tagName.endsWith("/")){ - return "StartAndEndTag"; - }else { - return "StartTag"; - } - } - - /** - * @return Returns the tagName. - */ - public String getTagName() { - return this.tagName; - } - /** - * @return Returns the tagString. - */ - public String getTagString() { - return this.tagString; - } - /** - * @return Returns the tagType. - */ - public String getTagType() { - return this.tagType; - } - - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java b/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java deleted file mode 100755 index 7993fc9cf0a4..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/DirtyTags/TagPair.java +++ /dev/null @@ -1,310 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: TagPair.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.DirtyTags; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; - - -/** - * @author Christian Schmidt 2005 - * - */ -public class TagPair { - - - private Tag startTag=Tag.EMPTYTAG; - private Tag endTag=Tag.EMPTYTAG; - private String startingText=""; - private ArrayList enclosedTags=new ArrayList(); - private long id; - private static int ElementCounter=1; - private String endingText=""; - - /** - * @author Christian Schmidt 2005 - * - */ - public class TagPairConstructionException extends Exception { - - /** - * Create a new Instance of TagPairConstructionException - * - * @param string - */ - public TagPairConstructionException(String string) { - - } - - } - - /** - * Create a new Instance of TagPair - * - * - */ - public TagPair() { - - } - - - /** - * Create a new Instance of TagPair - * - * Find matching tags in tagList, create a TagPair of it, create - * tagPairs from the content in the tagPair and remove all used - * tags from tagList. The rest of the tagList starts after the - * endTag of this TagPair. - * - * @param tagList a List of the tags to check - * - * @throws TagPairConstructionException - */ - public TagPair(ArrayList tagList) throws TagPairConstructionException { - - if(tagList.size()==0){ - return; - } - ArrayList contentList=new ArrayList();; - Tag tag=(Tag)tagList.get(0); - tagList.remove(0); - - - if("Text".equals(tag.getTagType())){ - // is this Text the only content - // of this Tag ? - if(tagList.size()==0){ - //yes...then it is the starting Text of this TagPair - this.startingText=tag.getTagString(); - return; - }else{ - //no...the tag is normal content - contentList.add(tag); - } - this.startingText=tag.getTagString(); - - }else if("EndTag".equals(tag.getTagType())){ - //ERRor throw EXception - }else if("StartTag".equals(tag.getTagType())){ - // find the matching end tag - this.startTag=tag; - Iterator iter=tagList.iterator(); - - int equivalentTagCounter=0; - while(iter.hasNext()){ - //is this the end tag? - if((tag=(Tag)iter.next()).getTagName().equals('/'+this.startTag.getTagName())&&equivalentTagCounter==0){ - //found the corresponding end tag - - //this TagPair is complete - //so it needs an id - this.id=TagPair.ElementCounter++; - this.endTag=tag; - //...remove it from list - tagList.removeAll(contentList); - tagList.remove(tag); - break; - }else{ - // tag is not the end tag - // so it is between the start and the end tag - // and belongs to the content - // but first check if it has the same name as the current tag - if(tag.getTagName().equals(this.startTag.getTagName())){ - // if this is a start tag like the current start tag - // we count it to find out the matching end tag in nested tags - if(tag.getTagType().equals("StartTag")){ - equivalentTagCounter++; - } - } - if(tag.getTagName().equals("/"+this.startTag.getTagName())){ - if(tag.getTagType().equals("EndTag")){ - equivalentTagCounter--; - } - } - - contentList.add(tag); - } - } - //found the end tag ? - //no... - if (this.endTag.getTagType()==""){ - - throw new TagPairConstructionException("ERROR: Missing end tag ("+ - this.startTag.getTagString()+")."); - //...yes - }else{ - //We need to check whether the content is starting or ending with text - //...check starting with text - if(contentList.size()>=1&&((String)((Tag)contentList.get(0)).getTagType()).equals("Text")){ - //yes...store it as startingText - this.startingText=(String)((Tag)contentList.get(0)).getTagString(); - //remove it from list - contentList.remove(0); - } - // ...check ending with text - if(contentList.size()>=1&&((String)((Tag)contentList.get(contentList.size()-1)).getTagType()).equals("Text")){ - //yes...store it as endingText - this.endingText=(String)((Tag)contentList.get(contentList.size()-1)).getTagString(); - //remove it from list - contentList.remove(contentList.size()-1); - } - //create the list of tags enclosed by this tagPair - createEnclosedTags(contentList); - } - //if stand AloneTag create own TagObject...give ID...add to List - }else if("StartAndEndTag".equals(tag.getTagType())){ - this.startTag=tag; - this.endTag=new Tag("EndOfStandAlone","",""); - createEnclosedTags(contentList); - } - - } - - /** - * @param contentList - * @throws TagPairConstructionException - */ - private void createEnclosedTags(ArrayList contentList) throws TagPairConstructionException { - while(contentList.size()>0){ - //create the inner TagPairs - this.enclosedTags.add(new TagPair(contentList)); - } - - } - - public String toString(){ - StringBuffer outString= new StringBuffer(this.startTag.toString()); - TagPair help=new TagPair(); - Iterator iter=enclosedTags.iterator(); - outString.append(this.startingText); - while(iter.hasNext()){ - if((help=(TagPair)iter.next())==null){ - continue; - }else{ - outString.append(help.toString()); - } - } - outString.append(this.endingText); - outString.append(this.endTag.toString()); - return new String(outString); - } - - public String getWrapped() throws IOException{ - Iterator iter=enclosedTags.iterator(); - StringBuffer returnBuffer=new StringBuffer(); - - returnBuffer.append(wrap(this.startTag)+xmlString(this.startingText)); - while(iter.hasNext()){ - returnBuffer.append(((TagPair)iter.next()).getWrapped()); - } - returnBuffer.append(xmlString(this.endingText)+wrap(this.endTag)); - - - - return new String(returnBuffer); - } - - private String wrap(Tag tag) throws IOException{ - String string=""; - //can be a start tag - if(tag.getTagType().startsWith("Start")){ - return new String(""+tag.getWrappedTagString()+""); - //...or a end tag - }else if (tag.getTagType().startsWith("End")){ - //maybe the end tag of a Start and end tag -// if("EndOfStandAlone".equals(tag.getTagType())){ -// return new String(""); -// }else{ - string=tag.getWrappedTagString(); - return new String(""+string+""); -// } - - //...or text - }else{ - return xmlString(tag.getTagString()); - } - } - /** - * Replaces all characters that mustn't be in XLIFF PCdata - * - * @param string the string to check - * @return the checked string with all characters replaced - * @throws java.io.IOException - */ - private final String xmlString( final String string) throws java.io.IOException { - if (string == null) - return string; // "" - String str = string; - - for(int i=0;i'){ - str=str.substring(0, i)+">"+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='"'){ - str=str.substring(0, i)+"""+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='\''){ - str=str.substring(0, i)+"'"+str.substring(i+1); - continue; - } - } - - return str; - } - - /** - * - */ - public static void resetCounter() { - TagPair.ElementCounter=1; - - } - - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java deleted file mode 100755 index 5b1fb6c62b61..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Convert.java +++ /dev/null @@ -1,553 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Convert.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * the main Class - * - * Command Line arguments are reviewed - * and a Converter is constructed - */ -package com.sun.star.tooling.converter; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Calendar; - -import com.sun.star.tooling.DirtyTags.DirtyTagWrapper; - -/** - * The main class of the converter tool - * - * The converter tool is command line based. - * Its classes allow the converting between the - * file formats sdf, gsi and xliff. - * - * Those file formats are used in localization - * of Star-Office and Open-Office. - * - * Information about the whole localization process can be found in - * http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf - * - * @author Christian Schmidt 2005 - * - */ -public class Convert { - - private static Calendar cal; - - private static final String EMPTY = ""; - - /** - * The name of the file containing the debug information - * that where found while converting (every output goes here too) - */ - private static String dbgName = EMPTY; - - /** - * the character that separates the extension from the file name - */ - private static final char extensionSeperator = '.'; - - /** - * the log File - */ - private static File log; - - /** - * the name of the log file - */ - private static String logString = EMPTY; - - /** - * indicates whether existing sources should be overwritten - * without asking - */ - private static boolean overwrite = false; - - /** - * A second Source File needed for GSI Merging - */ - private static File secondSource; - - //private static final char pathSeperator = '\\'; - - /** - * The language that should be the source language - * that means the language to translate from - */ - private static String sourceLanguage = "en-US"; - - /** - * the name of the source file - */ - private static String sourceName = EMPTY; - - /** - * the type of the source file (sdf,xliff,...) - */ - private static String sourceType = EMPTY; - - /** - * The time when converting started - */ - private static String startTime = EMPTY; - /** - * The language that should be the target language - * that means the language to translate to - */ - private static String TargetLanguage = EMPTY; - - /** - * the name of the target file - */ - private static String targetName = EMPTY; - - /** - * the type of the target file (sdf,xliff,...) - */ - private static String targetType = EMPTY; - - /** - * Store the current version ID and number of this tool - */ - final static String version = " Prod.20050710:1255 "; - - /** - * The name of the (original) sdf file used as second source for gsi->sdf merging - */ - private static String secondSourceName=EMPTY; - /** - * Indicate whether strings in xliff files should - * be wrapped with ept/bpt or sub tags to enable translation tools - * to synchronize source language string with there translation - * - * @see http://ded-1.germany.sun.com/webcontent/guidelines/pdf/L10NSO8.pdf - */ - private static boolean doWrap=true; - - - - public static void main(String[] args) throws IOException, Exception { - try{ - - //go, parse and check the command line parameters - ParameterChecker.checkClParameters(args); - ParameterChecker.createContentOfClParameters(); - //Initialize the tagWrapper - DirtyTagWrapper.setWrapping(doWrap); - //create an instance of converter - Converter conv = new Converter(sourceType, sourceName, sourceLanguage, - targetType, targetName, TargetLanguage,secondSourceName, overwrite); - // get aktual time - cal = Calendar.getInstance(); - startTime = cal.getTime().toString(); - //show infos - printPreamble(); - //do the job - conv.convert(); - - showStatistic(); - - //close log, debug... - OutputHandler.closeAll(); - - } catch(Exception e){ - System.out.print("An EXCEPTION occured, please check your commad line settings \n"+e.getMessage()); - System.exit(-1); - }catch(Throwable t){ - System.out.print("A FATAL ERROR occured, please check your commad line settings \n"+t.getMessage()); - System.exit(-1); - } - - } - - /** - * show the command line help - */ - private static void printHelp() { - - final String ls = System.getProperty("line.separator"); - System.out - .println( - - "File Converting Tool 'converter' Version " - + Convert.version - + ls - + "Converts SDF files to wellformed XLIFF or GSI files and vice versa" + ls - + ls - + "Use: " + ls - + "convert [-h]|[SourcePath [TargetPath] [-T Type] [[-S Type [secondSourcePath]] " + ls - + " [-s LanguageID] [-t LanguageID] [-l [LogPath]] [-o]]" + ls - + ls - + "-h show this help." + ls - + "SourcePath path of the file to convert." + ls - + "secondSourcePath path of the SDF file to merge to (GSI -> SDF only!)." + ls - + "TargetPath path where to store the result." + ls - + "LogPath path of the log file" + ls - + "-T Type the type of the target file (xliff,sdf,gsi)" + ls - + "-S Type the type of the source file (xliff,sdf,gsi)" + ls - + "-s LanguageID the ISO language code of the source language (de, fr...)." + ls - + " Default is 'en-US' " + ls - + "-t LanguageID the language code of the target language (de, fr...)." + ls - + " Default is first found Language other than source language." + ls - + "-l [LogPath] write a log file, you can name the file." + ls - + "-o overwrite existing files without asking." + ls - + "-nw disable the wrapping with ept/bpt tags." + ls - + ls - + "The created files were stored in the SourceFile Path if nothing else is given. " + ls - + "The extension is '.xliff','.sdf' depending on the source file and '.log' " + ls - + "for the logfile." + ls); - } - - /** - * show the parameters the converter starts with - * - * @throws IOException - */ - final private static void printPreamble() throws IOException { - OutputHandler.out(EMPTY); - OutputHandler.out("Source File is: " + sourceName); - OutputHandler.out("Target File is: " + targetName); - if (OutputHandler.doLog) { - OutputHandler.out("Log File is: " + logString); - } else { - OutputHandler.out("Log File is: disabled"); - } - - OutputHandler.out(EMPTY); - - } - - /** - * show some statistic data - * - * @throws IOException - */ - final private static void showStatistic() throws IOException { - OutputHandler.dbg(EMPTY); - OutputHandler - .out((targetType.equalsIgnoreCase("xliff") ? "TransUnits written: " - : "Lines written : ") - + Converter.getLineCounter()); - OutputHandler.dbg(EMPTY); - OutputHandler.out("Started at : " + Convert.startTime); - Convert.cal = Calendar.getInstance(); - OutputHandler.out("Finished at : " + Convert.cal.getTime()); - OutputHandler.dbg(EMPTY); - - } - - /** - * Get the extensiion of a file name - * (sdf,xliff,gsi) - * - * @param sourceString the file name - * @return the extension - */ - static protected String extractExtension(String sourceString) { - String ext = sourceString.substring(sourceString - .lastIndexOf(Convert.extensionSeperator) + 1); - return ext; - } - -// static protected String extractFileName(String sourceString) { -// String sName = EMPTY; -// sName = (sourceString.substring(sourceString -// .lastIndexOf(File.separator) + 1, sourceString -// .lastIndexOf(Convert.extensionSeperator))); -// -// return sName; -// } -// -// static protected String extractPath(String sourceString) { -// String sPath = sourceString.substring(0, sourceString -// .lastIndexOf(File.separator) + 1); -// return sPath; -// } - - /** - * - */ - public Convert() { - } - - /** - * - * Verify a parameter array and create content useable by the programm - * from the switches and attributes set at command line - * - * @author Christian Schmidt 2005 - */ - private static class ParameterChecker { - - /** - * Holds the path of the source file - */ - private static String filePath; - /** - * Holds the name of the source file - */ - private static String fileName; - - /** - * Create a new Instance of ParameterChecker - * - * - */ - public ParameterChecker(){}; - /** - * Checks the command line parameters - * - * @param args the parameters to check and to parse - * @throws IOException - */ - private static void checkClParameters(String[] args) throws IOException { - try { - //show help if no attrributes... - if (args.length == 0) { - printHelp(); - System.exit(-1); - } - //...or attribute is -h - if (args[0].equals("-h")) { - printHelp(); - System.exit(0); - } - if (args[0].equals("-ver")) { - System.out.println("File Converting Tool Version "+version); - System.exit(0); - } - //source file Location and path is always first attribute - sourceName = new String(args[0]); - - File source = new File(sourceName); - //break if there is no source to convert - if (!source.exists()) - throw new IOException("ERROR:Can not find Source File '" - + sourceName + "'. Aborting..."); - - // String name=source.getName(); - // String parent=source.getParent(); - // String path=source.getPath(); - - filePath = (source.getParent()==null)?"":source.getParent()+File.separator; //extractPath(sourceName); - fileName = source.getName().substring(0,source.getName().lastIndexOf(extensionSeperator)); - - for (int i = 1; i < args.length; i++) { - - - if ("-s".equals(args[i])) { - if (args.length > i + 1) { - sourceLanguage = args[++i]; - - } else { - throw new ConverterException( - "missing argument for -s source language"); - } - continue; - } - - if ("-S".equals(args[i])) { - if (args.length > i + 1) { - sourceType = args[++i]; - if (args.length > i +1 &&!args[i+1].startsWith("-")) { - secondSourceName = args[++i]; - } - - } else { - throw new ConverterException( - "missing argument for -S source type"); - } - continue; - } - - if ("-T".equals(args[i])) { - if (args.length > i + 1) { - targetType = args[++i]; - - - } else { - throw new ConverterException( - "missing argument for -T target type"); - } - continue; - } - - if ("-l".equals(args[i])) { - OutputHandler.doLog = true; - if (args.length > i + 1 - && (!args[i + 1].startsWith("-"))) { - logString = args[++i]; - } else { - logString = EMPTY; - } - continue; - } - - if ("-o".equals(args[i])) { - overwrite = true; - continue; - } - - if ("-nw".equals(args[i])) { - doWrap = false; - continue; - } - - if ("-h".equals(args[i])) { - printHelp(); - System.exit(0); - } - - if ("-dbg".equals(args[i])) { - OutputHandler.doDebug = true; - continue; - } - - if ("-t".equals(args[i])) { - if (args.length > i + 1) { - TargetLanguage = args[++i]; - } else { - throw new ConverterException( - "missing argument for -t target language"); - } - continue; - } - - if (i == 1 && !args[i].startsWith("-")) { //target file - // found - targetName = args[i]; - continue; - } - //if we come here we - //can not match the Attribute - throw new ConverterException("unknown Attribute: " - + args[i]); - - - }//end for - } catch (ConverterException e) { - OutputHandler.out("ERROR: "+e.getMessage()); - System.exit(-1); - } catch (Throwable t){ - System.out.print("An Error occured while parsing the command line,\n please check your commad line settings.\n "+t.getMessage()); - System.exit(-1); - } - - }//end checkClParameters - - /** - * Creates the appropriate content of what ever data - * we found in the command line - * - * @throws IOException - */ - private static void createContentOfClParameters() throws IOException { - - try { - if (OutputHandler.doDebug) { - // if the -dbg switch is set, we - // create - // a file that gets all information - // produced by this tool - - OutputHandler.dbgFile = new BufferedWriter(new FileWriter( - new File(new String(filePath + fileName + ".dbg")))); - } - - if (OutputHandler.doLog) {// create a logfile? - //given at command line? - if (EMPTY.equals(logString) || logString == null) { - logString = new String(filePath + fileName + ".log"); - } - log = FileMaker.newFile(logString, overwrite); - OutputHandler.logFile = (new BufferedWriter(new FileWriter( - log))); - } - - if (EMPTY.equals(sourceType) || sourceType == null) { - // not given at command line? - if (!(EMPTY.equals(sourceName) || sourceName == null)) { - sourceType = extractExtension(sourceName); - } else { - throw new ConverterException("Source type is missing"); - } - } - - if(sourceType.equalsIgnoreCase("gsi")){ - - if(EMPTY.equals(Convert.secondSourceName)){ - Convert.secondSourceName=filePath+fileName+".sdf"; - } - //secondSource=new File(Convert.secondSourceName); - - } - - if (EMPTY.equals(sourceName)) { - sourceName = filePath + fileName + "." + sourceType; - } - //no target type given at command line? - if (EMPTY.equals(targetType) || targetType == null) { - if (!(EMPTY.equals(targetName) || targetName == null)) { - targetType = extractExtension(targetName); - } else { - throw new ConverterException("Target type is missing"); - - } - } - //no target File specified at command line - if (EMPTY.equals(targetName) || targetName == null) { - targetName = filePath + fileName + "." + targetType; - if (targetName.equals(Convert.secondSourceName)){ - OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same"); - System.exit(0); - }else if (targetName.equals(Convert.sourceName)){ - OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same"); - System.exit(0); - } - }else if (targetName.equals(Convert.secondSourceName)){ - OutputHandler.out("ERROR: \nSource '"+Convert.secondSourceName+"' and \nTarget'"+targetName+"' are the same"); - System.exit(0); - }else if (targetName.equals(Convert.sourceName)){ - OutputHandler.out("ERROR: \nSource '"+Convert.sourceName+"' and \nTarget'"+targetName+"' are the same"); - System.exit(0); - } - - - } catch (ConverterException e) { - OutputHandler.out(e.getMessage()); - } - - } - - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java deleted file mode 100755 index 7ec09bcb411a..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Converter.java +++ /dev/null @@ -1,523 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Converter.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Converter.java - * - * create Source and Target - * for converting - * TODO maybe a factory would be good here - */ - -package com.sun.star.tooling.converter; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.EntityResolver; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -/** - * - * This class handles the creating of the source to read from, - * the target to write to and the appropriate DataHandler - * - * @author Christian Schmidt 2005 - */ -public final class Converter { - - /** - * the used charset f.e. UTF-8 - */ - private final static String CHARSET = new String("UTF-8"); - - private static final String EMPTY = new String(""); - - /** - * The DataHandler use to connect reader and writer - */ - private static DataHandler handler; - - /** - * Counting the lines written by a writer - */ - private static int lineCounter; - - /** - * The target to write to - */ - private static DataWriter theTargetWriter; - - - /** - * Overwrite existing files - */ - private boolean overwrite = false; - /** - * The source to read from - */ - private Source reader; - /** - * The name of the source file - */ - private String sourceString; - /** - * the Type of the Source file(SDF,GSI,XLIFF) - */ - private String sourceType; - /** - * The name of the target fille - */ - private String targetString; - /** - * the Type of the Target file(SDF,GSI,XLIFF) - */ - private String targetType; - /** - * The writer that handles the output - */ - private Target writer; - - /** - * The sourceLanguage - */ - String sourceLanguage = "en-US"; - - /** - * The targetLanguage - */ - String targetLanguage = ""; - - /** - * The name of the second source, needed for GSI to SDF merge - */ - private String secondSourceString=EMPTY; - - - /** - * Get the line counter - * @return Returns the lineCounter. - */ - public static int getLineCounter() { - return lineCounter; - } - - /** - * increment the lineCounter - */ - final static void countLine() { - lineCounter++; - } - - /** - * Creates a new instance of Converter - * - * @param sourceType the type of the sourceFile - * @param sourceString the name of the sourceFile - * @param SourceLanguage the ISO Id of the sourceLanguage - * @param targetType the type of the targetFile - * @param targetString the name of the targetFile - * @param TargetLanguage the ISO Id of the targetLanguage - * @param secondSourceString the name of the second sourceFile (GSI merge only) - * @param overwrite indicates whether overwrite existing files - * @throws IOException - * @throws Exception - */ - public Converter(String sourceType, String sourceString, - String SourceLanguage, String targetType, String targetString, - String TargetLanguage,String secondSourceString, boolean overwrite) throws IOException, - Exception { - - this.sourceType = sourceType; - this.sourceString = sourceString; - this.sourceLanguage = SourceLanguage; - this.targetType = targetType; - this.targetString = targetString; - this.targetLanguage = TargetLanguage; - this.secondSourceString=secondSourceString; - this.overwrite = overwrite; - - handler = new DataHandler(); - - if ("sdf".equalsIgnoreCase(sourceType)) { - reader = new SDFSource(); - } else if ("xliff".equalsIgnoreCase(sourceType)||"dbxliff".equalsIgnoreCase(sourceType)) { - reader = new XLIFFSource(); - } else if ("gsi".equalsIgnoreCase(sourceType)) { - reader = new GSISource(); - } else { - throw new ConverterException("Unknown Source File Type: '"+sourceType+"'"); - } - - if ("sdf".equalsIgnoreCase(targetType)) { - writer = new SDFTarget(); - } else if ("xliff".equalsIgnoreCase(targetType)) { - writer = new XLIFFTarget(); - } else if ("gsi".equalsIgnoreCase(targetType)) { - writer = new GSITarget(); - } else { - throw new ConverterException("Unknown Target File Type: '"+targetType+"'"); - } - - } - - /** - * Do the converting from the source file format to the target file format - * - * @throws IOException - */ - public final void convert() throws IOException { - - try { - - reader.convertTo(writer); - - //TODO this belongs in the Target Class - theTargetWriter.flush(); - theTargetWriter.close(); - } catch (Exception e) { - OutputHandler.out(e.getMessage()); - } - - } - - - /** - * - * Encapsulate the reading from an GSI file - * - * @author Christian Schmidt 2005 - * - */ - private class GSISource implements Source { - DataReader theSourceReader; - /** - * Create a new Instance of GSISource - * - * @throws IOException - * @throws Exception - */ - public GSISource() throws IOException { - - theSourceReader = new GSIandSDFMerger(new File(sourceString),new File(secondSourceString), sourceLanguage, - targetLanguage, CHARSET); - } - - public void convertTo(Target t) { - - try { - theTargetWriter = t.getWriter(); - while (handler.fillDataFrom(theSourceReader)) { - - theTargetWriter.getDatafrom(handler); - theTargetWriter.writeData(); - } - } catch (IOException e) { - OutputHandler.out(e.getMessage()); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - } - /** - * - * Encapsulate to write to a GSI file - * - * @author Christian Schmidt 2005 - * - */ - private class GSITarget implements Target { - - File target; - - /** - * Create a new Instance of GSITarget - * - * @throws FileNotFoundException - * @throws IOException - */ - public GSITarget() throws FileNotFoundException, IOException { - - target = FileMaker.newFile(targetString, overwrite); - theTargetWriter = new GSIWriter(new BufferedOutputStream( - new FileOutputStream(target)), CHARSET); - } - - public DataWriter getWriter() { - - return theTargetWriter; - } - - } - /** - * - * Encapsulate the reading from an SDF file - * - * @author Christian Schmidt 2005 - * - */ - private final class SDFSource implements Source { - - DataReader Source; - - /** - * Create a new Instance of SDFSource - * @throws IOException - * @throws Exception - */ - public SDFSource() throws IOException, Exception { - - Source = new SDFReader(new File(sourceString), sourceLanguage, - targetLanguage, CHARSET); - } - - public void convertTo(Target t) { - try { - theTargetWriter = t.getWriter(); - while (handler.fillDataFrom(Source)) { - - theTargetWriter.getDatafrom(handler); - theTargetWriter.writeData(); - } - - } catch (IOException e) { - OutputHandler.out(e.getMessage()); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - } - /** - * Encapsulate writing to a SDF file - * - * @author Christian Schmidt 2005 - * - */ - private class SDFTarget implements Target { - - /** - * Create a new Instance of SDFTarget - * - * @throws IOException - */ - public SDFTarget() throws IOException { - File target = FileMaker.newFile(targetString, overwrite); - theTargetWriter = new SDFWriter(new BufferedOutputStream( - new FileOutputStream(target)), CHARSET); - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.Converter.Target#getWriter() - */ - public DataWriter getWriter() { - - return theTargetWriter; - } - - } - - /** - * The interface for all convertable sources - * - * @author Christian Schmidt 2005 - * - */ - private interface Source { - - DataReader Source=null; - /** - * Convert this. to the designated target - * @param target the target of the converting - * @throws IOException - */ - abstract void convertTo(Target target) throws IOException; - } - - /** - * The interface for all creatable targets - * - * @author Christian Schmidt 2005 - * - */ - private interface Target { - /** - * The writer to use - */ - public OutputStream writer = null; - - /** - * Get the writer - * this target uses to write the - * data in the correct format. - * - * @return the used DataWriter - */ - abstract DataWriter getWriter(); - - } - /** - * Encapsulate the reading from an XLIFF file - * - * @author Christian Schmidt 2005 - * - */ - private class XLIFFSource implements Source { - File source; - - /** - * Create a new Instance of XLIFFSource - * - * - */ - public XLIFFSource() { - - source = new File(sourceString); - } - - public void convertTo(Target t) throws IOException { - try { - System.setProperty("entityExpansionLimit", "1000000"); - boolean laden = source.canRead(); - if (laden) { - DefaultHandler contentHandler=null; - if("dbxliff".equalsIgnoreCase(sourceType)){ - contentHandler = new XLIFFReader(handler, t - .getWriter(),false); - }else{ - contentHandler = new XLIFFReader(handler, t - .getWriter()); - } - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setNamespaceAware( true ); - factory.setValidating( true ); - - SAXParser parser=factory.newSAXParser(); - XMLReader xliffreader=parser.getXMLReader(); - - - -// XMLReader xliffreader = XMLReaderFactory -// .createXMLReader("org.apache.crimson.parser.XMLReaderImpl"); - xliffreader.setErrorHandler(contentHandler); - xliffreader.setContentHandler(contentHandler); - /* one possibility to resolve an extern entity (DTD) */ - EntityResolver res = new Resolver(); - xliffreader.setEntityResolver(res); - /* - * a second possibility to resolve an extern entity (DTD) - * - * xliffreader.setFeature("xml.org/sax/features/validation",true); - * xliffreader.setEntityResolver(new EntityResolver() { - * public InputSource resolveEntity(java.lang.String - * publicId, java.lang.String systemId) throws SAXException, - * java.io.IOException { if (publicId.equals("-//XLIFF//DTD - * XLIFF//EN")) // this deactivates the open office DTD - * return new InputSource(new ByteArrayInputStream( " " .getBytes())); else - * return null; } }); - * - */ - - xliffreader.parse(sourceString); - - } else { - System.out.println("Datei existiert nicht"); - } - - } catch (SAXParseException e) { - try { - theTargetWriter.flush(); - } catch (IOException e1) { - - e1.printStackTrace(); - } - OutputHandler.out("PARSE ERROR Zeile " + e.getLineNumber() - + ", " + e.getMessage()); - - }catch (SAXException e){ - try { - theTargetWriter.flush(); - } catch (IOException e1) { - - e1.printStackTrace(); - } - OutputHandler.out("PARSE EXCEPTION " + e.getMessage()); - } catch (ParserConfigurationException e) { - OutputHandler.out("PARSER Configuration failed\n " + e.getMessage()); - } - } - - } - /** - * Encapsulate writing to a XLIFF file - * - * @author Christian Schmidt 2005 - * - */ - private class XLIFFTarget implements Target { - File target; - - /** - * Create a new Instance of XLIFFTarget - * - * @throws FileNotFoundException - * @throws IOException - */ - public XLIFFTarget() throws FileNotFoundException, IOException { - target = FileMaker.newFile(targetString, overwrite); - theTargetWriter = new XLIFFWriter(new BufferedOutputStream( - new FileOutputStream(target)), CHARSET); - - } - - public DataWriter getWriter() { - - return theTargetWriter; - } - } - - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java deleted file mode 100755 index 07a3708d4366..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ConverterException.java +++ /dev/null @@ -1,79 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ConverterException.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * a simple exception - * just to seperate - * it from other - * exceptions - */ -package com.sun.star.tooling.converter; - -/** - * @author Christian Schmidt - * - * Thrown if an error occurs during converting from one file format to another - * that does not belong to an other exception - */ -public class ConverterException extends Exception { - - /** - * - */ - public ConverterException() { - super(); - - } - - /** - * @param arg0 - */ - public ConverterException(String arg0) { - super(arg0); - - } - - /** - * @param arg0 - */ - public ConverterException(Throwable arg0) { - super(arg0); - - } - - /** - * @param arg0 - * @param arg1 - */ - public ConverterException(String arg0, Throwable arg1) { - super(arg0, arg1); - - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java deleted file mode 100755 index e8b4136f185a..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataHandler.java +++ /dev/null @@ -1,149 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: DataHandler.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * DataHandler.java - * - * take the data from the reader - * and put it to the Writer - * - */ - -package com.sun.star.tooling.converter; - -import java.util.*; - -/** - * Handle the Data to get it from the Source - * readable to the Target - * - * @author Christian Schmidt - */ -public class DataHandler { - - /** - * An arrays that holds the names that will be - * keys for the HashMap containing the data - * - */ - private final String[] dataNames = { "BlockNr", "Project", - "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", - "Width", "SourceLanguageID", "SourceText", "SourceHText", - "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", - "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; - - private static final String EMPTY = new String(""); - - /** - * The HashMap containing the data - */ - private final Map data = new ExtMap(dataNames, null); - - /** Creates a new instance of DataHandler */ - public DataHandler() { - } - - /** - * fill the data from the desired source - * - * @param source where to get the data from - * @return true if data is read and false if null is read - * @throws IOException - * @throws ConverterException - */ - public boolean fillDataFrom(DataReader source) throws java.io.IOException, - ConverterException { - - Map line = null; - - line = source.getData(); - if (line == null){ - - return false; - }else{ - - this.data.putAll(line); - return true; - } - - - } - - /** - * fill this data with the inData - * - * @param inData the data to handle by this handler - */ - public void fillDataWith(Map inData) { - data.putAll(inData); - } - -// public void transfer(DataWriter target, DataReader source) { -// -// source.setHandler(this); -// -// } - - /** - * The designated output is filled with the content of this handler - * - * @param output an array of Maps [0] should hold the source language data [1] the target language data - * @throws java.io.IOException - */ - public void putDataTo(Map[] output) throws java.io.IOException { - String aKey = EMPTY; - for (int j = 0; j < output.length; j++) { - Set keys = output[j].keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()) { - aKey = (String) iter.next(); - output[j].put(aKey, data.get(aKey)); - } - } - - } - /** - * The designated output is filled with the content of this handler - * - * @param output a Map that should hold the source language data and the target language data - * @throws java.io.IOException - */ - public void putDataTo(Map output) throws java.io.IOException { - String aKey = EMPTY; - - Set keys = output.keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()) { - aKey = (String) iter.next(); - output.put(aKey, data.get(aKey)); - } - - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java deleted file mode 100755 index 59de7ca7e1f4..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataReader.java +++ /dev/null @@ -1,79 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: DataReader.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.tooling.converter; - -import java.io.*; -import java.util.*; - -/** - * Gets Line counting from LineNumberReader all Converter Reader classes inherit - * from this. - * The abstract parent class of all converter reader classes - * - * @author Christian Schmidt - */ -abstract public class DataReader extends LineNumberReader { - - /** - * Creates a new instance of DataReader - * - * @param isr - * InputStreamReader used as Source for this class - */ - public DataReader(InputStreamReader isr) { - super(isr); - } - - /** - - * @throws java.io.IOException - * @throws ConverterException - * - * TODO this should no longer use an array as return type better a Map - * - */ - /** - * The next block of the SDF file is reviewed and the Line including the - * source language and the Line including the target Language are given back - * in an array - * - * - * @return A Map including the source language - * and the target Language content are given back - * - * @throws java.io.IOException - * @throws ConverterException - */ - public Map getData() throws java.io.IOException, ConverterException { - return null; - } - - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java deleted file mode 100755 index c5d6765e3840..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/DataWriter.java +++ /dev/null @@ -1,91 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: DataWriter.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * DataWriter.java - * - * parent of all XXXWriter classes used by - * Converter - */ - -package com.sun.star.tooling.converter; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; - -/** - * The abstract parent class of all converter writer classes - * - * @author Christian Schmidt - */ -abstract public class DataWriter extends OutputStreamWriter { - protected final String seperator = new String("|"); - - /** - * the char sequence used as line seperator - */ - protected final String lineEnd = java.lang.System.getProperty( - "line.seperator", "\n"); - - /** Creates a new instance of DataWriter */ - /** - * @param bos the buffered output stream holding the data - * @param encoding the encoding to use for read from bos - * @throws java.io.UnsupportedEncodingException - */ - public DataWriter(BufferedOutputStream bos, String encoding) - throws java.io.UnsupportedEncodingException { - super(bos, encoding); - } - -// abstract protected void writeData(Map[] data) throws java.io.IOException; - - /** - * get the data that should be written from the DataHandler - * - * @param handler the DataHandler having the data - * @throws java.io.IOException - */ - abstract protected void getDataFrom(DataHandler handler) - throws java.io.IOException; - - /** - * write the Data - * - * @throws java.io.IOException - */ - abstract protected void writeData() throws java.io.IOException; - - /** - * @param handler - * @throws IOException - */ - abstract protected void getDatafrom(DataHandler handler) throws IOException; -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java deleted file mode 100755 index b05767e93ae3..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ExtMap.java +++ /dev/null @@ -1,97 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ExtMap.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * A special HashMap, - * can be constructed of - * two Arrays - */ -package com.sun.star.tooling.converter; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Christian Schmidt - * - * Create a Hash Map from two Arrays - * - */ -public class ExtMap extends HashMap { - - /** - * - */ - public ExtMap() { - super(); - - } - - /** - * @see java.util.HashMap - * @param arg0 - */ - public ExtMap(int arg0) { - super(arg0); - - } - - /** - * @param arg0 - * @param arg1 - */ - public ExtMap(int arg0, float arg1) { - super(arg0, arg1); - - } - - /** - * @param arg0 - */ - public ExtMap(Map arg0) { - super(arg0); - - } - - // create a new Map from two string arrays - public ExtMap(String[] names, String[] content) { - super(names.length); - if (content == null) - content = new String[names.length]; - for (int i = 0; i < names.length; i++) { - if (i >= content.length) { - break; - } else { - this.put(names[i], content[i]); - } - } - - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java deleted file mode 100755 index a21b8daa7b1d..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/FileMaker.java +++ /dev/null @@ -1,87 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: FileMaker.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * creates new files - * checks if they exist or - * can be overwritten - * - */ -package com.sun.star.tooling.converter; - -import java.io.File; -import java.io.IOException; - -/** - * Creates new files only if the file does not yet exist - * or overwriting is allowed - * - * @author Christian Schmidt 2005 - * - */ -public final class FileMaker { - - /** - * Create a new file if overwriting is not alowed - * ask if existing files should be overwritten - * - * @param fileName the files name to overwrite - * @param overwrite indicates wether the file can be overwritten - * @return the File created from the fileName - * @throws IOException - */ - public final static File newFile(String fileName, boolean overwrite) - throws IOException { - File file = new File(fileName); - if (file.exists()) { - if (!overwrite) { - char c = 0; - - System.out.print("Warning: File " + fileName - + " already exist.\n" + "Overwrite (y/n) ? :"); - byte[] waste = new byte[10]; - System.in.read(waste); - c = (char) waste[0]; - if (c == 'y') { - OutputHandler.out("...overwriting " + fileName); - } else { - OutputHandler.out( - "\nPlease set '-o' switch at command line to overwrite.\n\nProgramm Aborted."); - System.exit(-1); - } - } else { - OutputHandler.out("...overwriting " + fileName); - } - } else { - OutputHandler.out("...creating new target file " + fileName); - } - return file; - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java deleted file mode 100755 index adb6e358a74c..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIReader.java +++ /dev/null @@ -1,250 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: GSIReader.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.converter; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.Map; - -import com.sun.star.tooling.languageResolver.LanguageResolver; -import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; - -/** - * @author Christian Schmidt 2005 - * - */ -public class GSIReader extends DataReader { - /** - * A Map holding an empty GSIBlock - */ - private Map EmptyGSIBlock; - - /** - * @see LanguageResolver - */ - LanguageResolver languageResolver; - - /** - * The source language identifier - */ - protected String sourceLanguage; - - /** - * The target language identifier - */ - protected String targetLanguage; - - /** - * The number of the last block - */ - private String oldBlockNr; - - /** - * A buffer holding one GSILine - */ - private Map GSILineBuffer; - - /** - * Indicates whether to use the buffered line - */ - private boolean useBuffer = false; - - private static final String EMPTY = new String(""); - - /** - * An empty Map to fill with language depending data - */ - private ExtMap EmptyLanguageMap; - - /** - * Indicates whether the first block is read - */ - private boolean isFirst = true; - - private int lineCounter; - - private int blockCounter; - /** - * Indicates whether the last line is read - */ - private boolean lastLineFound = false; - - /** - * Create a new Instance of GSIReader - * - * @param source - * the file to read from - * @param sourceLanguage - * the sourceLanguage (must not be empty) - * @param targetLanguage - * the targetLanguage - * @param charset - * the charset used to read source - * @throws java.io.IOException - * @throws Exception - */ - public GSIReader(File source, String sourceLanguage, String targetLanguage, - String charset) throws java.io.IOException { - super(new InputStreamReader(new FileInputStream(source), charset)); - this.languageResolver = new LanguageResolver(); - this.sourceLanguage = sourceLanguage; - this.targetLanguage = targetLanguage; - - EmptyLanguageMap = new ExtMap(new String[0], new String[0]); - - } - - /** - * Read the next GSIBlock and return the data - * - * @return A Map containing the data of the read GSIBlock the keys for the language depending data are the language id (numeric) the - * single language are acessible with the keys "BlockNr", "resType", "languageNr", "status","content". - * - * @throws IOException - */ - public Map getGSIData() throws IOException { - String help; - Map helpmap; - Map GSIBlock = new HashMap(); - GSIBlock.put(sourceLanguage, EmptyLanguageMap.clone()); - GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); - String line = EMPTY; - String[] splitLine; - Map GSILine; - String[] GSINames = { "BlockNr", "resType", "languageNr", "status", - "content" }; - - while (useBuffer || (line = readLine()) != null) { - - - - if (useBuffer) { - GSILine = GSILineBuffer; - GSIBlock.put(sourceLanguage, EmptyLanguageMap.clone()); - GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); - GSIBlock.put("BlockNr", GSILine.get("BlockNr")); - useBuffer = false; - } else { - this.lineCounter++; - if ((splitLine = split(line)) == null) { - continue; - } - GSILine = new ExtMap(GSINames, splitLine); - if (isFirst) { - GSIBlock.put("BlockNr", GSILine.get("BlockNr")); - oldBlockNr = (String) GSILine.get("BlockNr"); - isFirst = false; - } - } - if (oldBlockNr == null) { - oldBlockNr = (String) GSILine.get("BlockNr"); - } - if (!oldBlockNr.equals((String) GSILine.get("BlockNr"))) { - GSILineBuffer = GSILine; - oldBlockNr = (String) GSILine.get("BlockNr"); - useBuffer = true; - break; - } - String lang; - try { - // Is there the source language in this line? - if ((lang = languageResolver.getISOfromNr((String) GSILine - .get("languageNr"))).equals(this.sourceLanguage)) { - // ok..store it as Source String under the depending - // ressource type - - ((Map) GSIBlock.get(sourceLanguage)).put("Source" - + ResTypeResolver.getInternKey((String) GSILine - .get("resType")), GSILine.get("content")); - // ..maybe the target language? - } else { - if (targetLanguage.equals(EMPTY)) { - // if no target language is given at command line - targetLanguage = lang; - GSIBlock.put(targetLanguage, EmptyLanguageMap.clone()); - } - if (lang.equals(this.targetLanguage)) { - - // ok..store it as target String under the depending - // ressource type - ((Map) GSIBlock.get(targetLanguage)).put("Target" - + ResTypeResolver.getInternKey((String) GSILine - .get("resType")), GSILine - .get("content")); - } - } - } catch (LanguageResolvingException e) { - OutputHandler.out("Can not resolve the language "+e.getMessage()); - } - - } - if (line == null) { - if (lastLineFound){ - OutputHandler.out("\n\n"); - OutputHandler.out("GSI Blocks : " + this.blockCounter); - OutputHandler.out("GSI Lines : " + this.lineCounter); - - return null; - }else{ - lastLineFound = true; - this.blockCounter++; - return GSIBlock; - } - } else { - this.blockCounter++; - return GSIBlock; - } - - } - - /** - * Split a GSILine to single fields - * - * @param line - * The line to split - * @return An array containing the contents of the columns in the given line - */ - private String[] split(String line) { - String[] splitLine = (line.substring(0, line.length() - 1)) - .split("\\(\\$\\$\\)"); - if (splitLine.length != 5) - return null; - else - return splitLine; - } - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java deleted file mode 100755 index 085e26475e09..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIWriter.java +++ /dev/null @@ -1,246 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: GSIWriter.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.tooling.converter; -import java.io.*; -import java.util.Map; - -import com.sun.star.tooling.languageResolver.LanguageResolver; -import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; -/** - * - * @author cs156069 - */ -public class GSIWriter extends DataWriter { - /** - * The seperator used to seperate GSI columns - */ - final String seperator=new String("($$)"); - - /** - * Holding the keys used by a map holding the content of an GSI Line contianing the source language - */ - final static String[] sourceLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TimeStamp"}; - /** - * Holding the keys used by a map holding the content of an GSI Line contianing the target language - */ - final static String[] targetLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; - /** - * Holding the keys used by a map holding the content of an GSI Line contianing the source and the target language - */ - final static String[] outLineNames= {"BlockNr","Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; - - /** - * A map holding the content of an GSI Line contianing the source language - */ - private ExtMap sourceLine=new ExtMap(sourceLineNames,null); - /** - * A map holding the content of an GSI Line contianing the target language - */ - private ExtMap targetLine=new ExtMap(targetLineNames,null); - /** - * A map holding the content of an GSI Line contianing the source and the target language - */ - private ExtMap outData=new ExtMap(outLineNames, null); - - private static final String EMPTY = new String(""); - /** - * The sourceLanguage to use - */ - private String sourceLanguage; - /** - * The sourceLanguage to use - */ - private String targetLanguage; - - /** - * GSILines have a special Line End - */ - private final static String lineEnd="!"+'\r'+'\n'; - //private boolean SourceIsFirst=false; - - /** - * The blockNr of the current line - */ - private String blockNr; - - - - - /** - * Create a new Instance of GSIWriter - * - * @param bos the Buffered Output Stream to write to - * @param charset the used charset - * @throws java.io.UnsupportedEncodingException - */ - public GSIWriter(BufferedOutputStream bos,String charset) throws java.io.UnsupportedEncodingException { - super(bos,charset); - - - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#writeData() - */ - public final void writeData() throws java.io.IOException { - - StringBuffer buffer=new StringBuffer(""); - if(this.sourceLanguage==null&&this.targetLanguage==null){ - LanguageResolver lang =new LanguageResolver(); - try { - this.sourceLanguage=lang.getNrFromISO((String)outData.get("SourceLanguageID")); - this.targetLanguage=lang.getNrFromISO((String)outData.get("TargetLanguageID")); - } catch (LanguageResolvingException e) { - - OutputHandler.out(e.getMessage()); - System.exit(0); - } - } - - - this.blockNr=(String)outData.get("BlockNr"); - // get the values of the found fields - //create the gsi lines - // - //at first the source language line - buffer.append(getSourceLine("Text")); - buffer.append(getSourceLine("HText")); - buffer.append(getSourceLine("QText")); - buffer.append(getSourceLine("Title")); - - //now the target language line - // put them together for output - buffer.append(getTargetLine("Text")); - buffer.append(getTargetLine("HText")); - buffer.append(getTargetLine("QText")); - buffer.append(getTargetLine("Title")); - //ok...put all to disk; - this.write(buffer.toString()); - - } - - /** - * Create a line containing the source string from the data - * @param resType - * @return The StringBuffer containing the line - */ - private StringBuffer getSourceLine(String resType){ - StringBuffer buffer =new StringBuffer(200); - String resString = "Source"+resType; - - String help; - if(EMPTY.equals((String)outData.get(resString))||" ".equals(outData.get(resString))) return new StringBuffer(EMPTY); - else { - // put them together for output - buffer.append(this.blockNr); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(ResTypeResolver.getExternKey(resType)); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(this.sourceLanguage); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append("int"); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(outData.get(resString)); - - // this line is full - // so close it with '! cr lf' - buffer.append(GSIWriter.lineEnd); - Converter.countLine(); - return buffer; - } - - } - /** - * Create a line containing the target string from the data - * @param resType - * @return The StringBuffer containing the line - */ - private StringBuffer getTargetLine(String resType){ - StringBuffer buffer =new StringBuffer(200); - String resString = "Target"+resType; - - if(EMPTY.equals((String)outData.get(resString))||" ".equals(outData.get(resString))) return new StringBuffer(EMPTY); - else { - // put them together for output - buffer.append(this.blockNr); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(ResTypeResolver.getExternKey(resType)); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(this.targetLanguage); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append("ext"); - // seperate the fields with ($$) - buffer.append(this.seperator); - buffer.append(outData.get(resString)); - - // this line is full - // so close it with '! cr lf' - buffer.append(GSIWriter.lineEnd); - Converter.countLine(); - return buffer; - } - - } - - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#writeData(java.util.Map[]) - */ - protected void writeData(Map[] data) throws IOException { - // TODO redesign DataHandler in the way that this is not nessesary any more - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#getDataFrom(com.sun.star.tooling.converter.DataHandler) - */ - protected void getDataFrom(DataHandler handler) throws IOException { - - handler.putDataTo(this.outData); - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#getDatafrom(com.sun.star.tooling.converter.DataHandler) - */ - protected void getDatafrom(DataHandler handler) throws IOException { - - handler.putDataTo(this.outData); - - } -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java deleted file mode 100755 index ff0348f97d3d..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/GSIandSDFMerger.java +++ /dev/null @@ -1,167 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: GSIandSDFMerger.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.converter; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * Merge GSIFiles back to to the original (!) SDFFile - * - * - * @author Christian Schmidt 2005 - * - */ -public class GSIandSDFMerger extends SDFReader { - - int lineCounter=0; - - GSIReader gsiReader; - - private Map temp=new HashMap(); - private int j; - private boolean skip=true; - Map gsiBlock=null; - Map sdfBlock=null; - - private boolean dontLoadGSI=false; - - private int count; - /** - * Merge the GSIFile back to the original(!) SDFFile - * - * @param source the file to read from - * @param sourceLanguage the source language in the source file - * @param targetLanguage the target language in the source file - * @param charset the charset of the files - * @throws java.io.IOException - * @throws Exception - */ - public GSIandSDFMerger(File source, File secondSource,String sourceLanguage, - String targetLanguage, String charset) throws IOException { - // merging GSI and SDF requieres two Sources - //this. is the SDF source - super(secondSource, sourceLanguage, targetLanguage, charset); - //create the GSI Source - - gsiReader=new GSIReader(source,sourceLanguage,targetLanguage,charset); - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataReader#getData() - */ - public Map getData()throws java.io.IOException{ - do{ - skip=false; - this.temp=matchGSI(); - }while(skip); - if(temp==null){ - OutputHandler.out("Blocks merged : "+this.lineCounter); - } - return temp; - - } - - /** - * Read each block of the GSIFile and check whether there is a matching - * block in the SDFFile. Match depends on the BlockNr and BlockId. - * - * @return A Map that contains the source language content - * and the target language content. - * @throws IOException - * @throws ConverterException - */ - public Map matchGSI() throws IOException{ - - - try { - //System.out.println("Start..."); - - if (dontLoadGSI||(gsiBlock=gsiReader.getGSIData())!=null){ - dontLoadGSI=false; - //check if we must update this block - //if so its BlockNr is in the gsi file - if((sdfBlock = super.getData())!=null){ - - if(((String)sdfBlock.get("BlockNr")).equals((String)gsiBlock.get("BlockNr"))){ - - gsiBlock.remove(EMPTY); - //if the target language string is empty this may be caused by an error in the source sdf File - //I don't want to overwrite a possibly correct translation with an empty string - // so remove the target part from the gsiBlock - Map mp=(Map)gsiBlock.get(gsiReader.targetLanguage); - if (mp.size()!=0&&!((String)mp.get("TargetText")).equals("")){ - - // target language part in this gsiBlock -// if(((String)mp.get("TargetText")).equals("")){ -// gsiBlock.remove(targetLanguage); -// } - // count the merged blocks - lineCounter++; - Map helpMap = (Map)gsiBlock.get(super.targetLanguage);//"ja" - sdfBlock.putAll(helpMap); - skip=false; - }else{ - //no target language part in this gsiBlock - skip=true; -// -// return null; - } - }else{ -// skip=true; -// -// // we cant match this gsi block to the current sdf block - // try matching the next sdf block with this gsi line - dontLoadGSI=true; - } - } - return sdfBlock; - } - - } catch (IOException e) { - - e.printStackTrace(); - } - return null; - } - - - - - - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java deleted file mode 100755 index 6a11360cc472..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/LineErrorException.java +++ /dev/null @@ -1,81 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: LineErrorException.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Exception for errors in - * SDFLines - */ -package com.sun.star.tooling.converter; - - -/** - * This Exeption is thrown if a DataReader finds an error in a read Line - * f. e. wrong column number - * - * @author Christian Schmidt 2005 - * - */ -public class LineErrorException extends Exception { - - public int tokenCount; - /** - * - */ - public LineErrorException() { - super(); - - } - - /** - * @param arg0 - */ - public LineErrorException(String arg0) { - super(arg0); - - } - - /** - * @param arg0 - */ - public LineErrorException(Throwable arg0) { - super(arg0); - - } - - /** - * @param arg0 - * @param arg1 - */ - public LineErrorException(String arg0, Throwable arg1) { - super(arg0, arg1); - - } - - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java deleted file mode 100755 index 997c05a70b4f..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/OutputHandler.java +++ /dev/null @@ -1,228 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: OutputHandler.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Creates logfile and file for debug information - * - */ -package com.sun.star.tooling.converter; - -import java.io.BufferedWriter; -import java.io.IOException; - -/** - * Handle the whole output during converting process except the converted files. - * Write output to logfiles and to screen depending on switches given - * at command line. - * @author Christian Schmidt 2005 - * - */ -public class OutputHandler { - - private static final String EMPTY = ""; - - /** - * The logfile to write - */ - public static BufferedWriter logFile; - - /** - * Indicates whether excisting files should be overwritten - */ - public static boolean doLog = false; - - /** - * Indicate whether the debug information should be written - */ - public static boolean doDebug = false; - - /** - * The File to write the debug information to - */ - public static BufferedWriter dbgFile; - - /** - * Write the data to screen and if the switches were set to - * logfile and debugfile - * - * @param out the String to write - */ - final static void out(String out) { - try { - if (doDebug) - OutputHandler.dbg(out); - - if (!doLog || logFile == null) { - System.out.println(out); - } else { - System.out.println(out); - if (EMPTY.equals(out)) { - OutputHandler.log(EMPTY); - } else { - OutputHandler.log(out); - } - } - } catch (IOException e) { - - OutputHandler.log(e.toString()); - } - } - - /** - * make a dot on the screen to show the user that it is going on - */ - final static void printDot() { - System.out.print("."); - - } - - /** - * write the data to log file and if the switch is set - * to the debug file - * - * @param out the String to write - */ - final static void log(String out) { - try { - if(out==null) return; - if (doDebug) - - OutputHandler.dbg(out); - - if (doLog) { - if (!EMPTY.equals(out)) { - logFile.write(out); - } - logFile.newLine(); - logFile.flush(); - } - } catch (IOException e) { - - System.out.println(e.getMessage()); - } - } - - /** - * write the string to the debug file - * - * @param out the String to write - * @throws IOException - */ - final static void dbg(String out) throws IOException { - if(out==null) return; - if (doDebug) { - if (!EMPTY.equals(out)) { - dbgFile.write(out); - - } - dbgFile.newLine(); - dbgFile.flush(); - } - } - - /** - * Set a new value to indicate whether a debug file should be written or not - * - * @param doDebug - * The debug value to set. - */ - private static void setDebug(boolean doDebug) { - OutputHandler.doDebug = doDebug; - } - - // /** - // * @return Returns the doDebug. - // */ - // private static boolean isDebug() { - // return doDebug; - // } - - /** - * Set the debug file to write to. - * - * @param dbgFile - * The debug File to use. - */ - private static void setDbgFile(BufferedWriter dbgFile) { - OutputHandler.dbgFile = dbgFile; - } - - /** - * @return Returns the debug File. - */ - private static BufferedWriter getDbgFile() { - return dbgFile; - } - - /** - * @param doLog - * The log value to set. - */ - private static void setLog(boolean doLog) { - OutputHandler.doLog = doLog; - } - - /** - * @return Returns the log value. - */ - private static boolean isLog() { - return doLog; - } - - /** - * @param logFile - * The logFile to set. - */ - private static void setLogFile(BufferedWriter logFile) { - OutputHandler.logFile = logFile; - } - - /** - * @return Returns the logFile. - */ - private static BufferedWriter getLogFile() { - return logFile; - } - - /** - * @throws IOException - * close log and dbg - */ - public static void closeAll() throws IOException { - if (OutputHandler.logFile != null) { - OutputHandler.logFile.flush(); - OutputHandler.logFile.close(); - } - if (OutputHandler.dbgFile != null) { - OutputHandler.dbgFile.flush(); - OutputHandler.dbgFile.close(); - } - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java deleted file mode 100755 index f53fe0101275..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/ResTypeResolver.java +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ResTypeResolver.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.converter; - -import java.util.Map; - -/** - * Helps resolving restype descriptors used outside the tool to - * restype descriptors used by this tool - * - * @author Christian Schmidt 2005 - * - */ -public class ResTypeResolver { - final static String[] inFields={"Text","QText","HText","Title"}; - final static String[] outFields={"res","res-quickhelp","res-help","res-title"}; - final static Map internKeys=new ExtMap(inFields,outFields); - final static Map externKeys=new ExtMap(outFields,inFields); - - /** - * Get the intern key depending to the given extern key - * - * @param externKey the externKey {"res","res-quickhelp","res-help","title"} - * @return the depending intern key - */ - public static String getInternKey(String externKey){ - return (String)externKeys.get(externKey); - } - - /** - * Get the extern key to the given intern key - * - * @param internKey the internal key - * @return the external key - */ - public static String getExternKey(String internKey){ - return (String)internKeys.get(internKey); - } - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java deleted file mode 100755 index 29a9ee2e528a..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/Resolver.java +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Resolver.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 27.01.2005 - * - */ -package com.sun.star.tooling.converter; - -import java.io.IOException; -import java.io.InputStream; - -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * Resolve external entities by provide the - * XLIFF DTD stored in the jar file - */ -public class Resolver implements EntityResolver { - - /** - * Resolver constructor. - */ - public Resolver() { - } - - /** - * Allow the application to resolve external entities. - * - * The Parser will call this method before opening any external entity - * except the top-level document entity (including the external DTD subset, - * external entities referenced within the DTD, and external entities - * referenced within the document element): the application may request that - * the parser resolve the entity itself, that it use an alternative URI, or - * that it use an entirely different input source. - */ - - /* (non-Javadoc) - * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) - */ - - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - - if ((publicId != null) && (publicId.equals("-//XLIFF//DTD XLIFF//EN"))) { - systemId = "dtd:///xliff.dtd"; - } - if (systemId != null) { - if (systemId.startsWith("dtd://")) { - String dtd = "com/sun/star/tooling/converter/dtd" - + systemId.substring(6); - ClassLoader cl = this.getClass().getClassLoader(); - InputStream in = cl.getResourceAsStream(dtd); - InputSource ins = new InputSource(in); - ins.setSystemId(systemId); - return ins; - } /* - * else if ( systemId.startsWith("jar:") ) { try { URL url=new - * URL(systemId); JarURLConnection jarConn = - * (JarURLConnection)url.openConnection(); InputSource ins=new - * InputSource(jarConn.getInputStream()); - * ins.setSystemId(systemId); return ins; } - * catch(MalformedURLException me){ throw new SAXException(me); - * Incorrect URL format used } } - */ - } - return null; - } - -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java deleted file mode 100755 index 4c0c234778ec..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFReader.java +++ /dev/null @@ -1,635 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: SDFReader.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * SDFReader.java - * - * - */ - -package com.sun.star.tooling.converter; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.text.DecimalFormat; -import java.util.*; - -/** - * - * SDFReader is a FileReader that knows about - * the content of SDFFiles - * - * A SDFBlock is read of the given file. A SDFBlock - * consists of all SDFLines that are traanslations of the - * same String and the SDFLine containing the source string - * itself. SDFFile lines are read and checked whether they - * have the allowed column count and don't contain illeagal - * characters (like most unprintable characters below 0x00df). - * If the given source language is not found in the first - * block of SDFLines a ConverterException is thrown at runtime. - * If the given target language is "" (that means not given) - * the first language that is not the given source language - * is taken for target language. The found values are returned in HashMaps that - * use the following keys: - *
- * "BlockNr" originally coming from reading the sdf file, contains 'block nr in sdf file'+'-'+'hash value of the sdf id fields'.
- * "Project" first column in sdf file format.
- * "SourceFile" second column in sdf file format.
- * "Dummy" third column in sdf file format.
- * "ResType" 4. column in sdf file format.
- * "GID" 5. column in sdf file format.
- * "LID" 6. column in sdf file format.
- * "HID" 7. column in sdf file format.
- * "Platform" 8. column in sdf file format.
- * "Width", 9. column in sdf file format.
- * "SourceLanguageID" 10. column in sdf file format(in the line with the source language).
- * "SourceText" 11. column in sdf file format(in the line with the source language).
- * "SourceHText" 12. column in sdf file format(in the line with the source language).
- * "SourceQText" 13. column in sdf file format(in the line with the source language).
- * "SourceTitle" 14. column in sdf file format(in the line with the source language).
- * "TargetLanguageID" 10. column in sdf file format (in the line with the target language).
- * "TargetText" 11. column in sdf file format (in the line with the target language).
- * "TargetHText" 12. column in sdf file format (in the line with the target language).
- * "TargetQText" 13. column in sdf file format (in the line with the target language).
- * "TargetTitle", 14. column in sdf file format (in the line with the target language).
- * "TimeStamp" 15. column in sdf file format.
- * - * @author Christian Schmidt 2005 - * - */ - -public class SDFReader extends DataReader { - - /** - * an array of the SDF files column names - */ - final static String[] fieldnames = { "Project", "SourceFile", "Dummy", - "ResType", "GID", "LID", "HID", "Platform", "Width", "LanguageID", - "Text", "HText", "QText", "Title", "TimeStamp" }; - - /** - * an array of the SDF files column names if the source language is in - */ - final static String[] sourceLineNames = { "Project", "SourceFile", "Dummy", - "ResType", "GID", "LID", "HID", "Platform", "Width", - "SourceLanguageID", "SourceText", "SourceHText", "SourceQText", - "SourceTitle", "TimeStamp" }; - - /** - * an array of the SDF files column names if the target language is in - */ - final static String[] targetLineNames = { "Project", "SourceFile", "Dummy", - "ResType", "GID", "LID", "HID", "Platform", "Width", - "TargetLanguageID", "TargetText", "TargetHText", "TargetQText", - "TargetTitle", "TimeStamp" }; - - final static String EMPTY = new String(""); - - private int dotCount = 0; - - /** - * a Map containing an SDF line with source language - */ - private Map sourceMap; - - /** - * a Map containing an SDF line with target language - */ - private Map targetMap; - - /** - * a Map containing an SDF - */ - private Map SDFMap; - - /** - * a Map Array containing one SDF source language line and one SDF target - * language line - */ - private Map[] data = { sourceMap, targetMap }; - - /** - * The Id of the current SDFBlock - */ - private String CurrentBlockId; - - /** - * The SDF file to read from - */ - private File sourceFile; - - /** - * The language in the source file that should be handelt as source language - */ - protected String sourceLanguage; - - /** - * The language in the source file that should be handelt as target language - */ - protected String targetLanguage; - - /** - * A counter holding the number of blocks just read - * from this file - */ - private long blockNr = 0;// If we use Integer, more then numbers greater than 128k would be signed - - /** - * A counter holding the number of skipped lines that means - * lines that can not be worked with because they contain an error - */ - private int skippedLines = 0; - - /** - * This switch is set for indicating that all source file lines - * are read and no lines remain buffered. Finding this like 'true' - * means the source file is finished - */ - private boolean endIt = false; - - /** - * Indicates whether the targetLanguage is found in this source file so far - */ - private boolean foundTarget = false; - /** - * Indicates whether the sourceLanguage is found in this source file so far - */ - private boolean foundSource = false; - - /** - * Counts how many lines were skipped because the language is - * neither sourceLanguage nor targetLanguage - */ - private int langMiss; - - /** - * Indicates whether there is a line in the read buffer or not - */ - private boolean useBuffer = false; - - /** - * A buffer for SDFLines - */ - private String lineBuffer; - - /** - * The buffer for the already splitted SDFLines - */ - private String[] splittedLineBuffer; - - /** - * Counts how many Blocks were skipped - * f.e. because no sourceLanguage is found - * in it - */ - private int skippedBlocks; - - /** - * Counts the blocks without targetLanguage - */ - private int targetLangMiss; - - /** - * Counts the blocks without sourceLanguage - */ - private int sourceLangMiss; - - /** - * Counts the lines where no targetLanguage line was found - * and so empty lines were created - */ - private int targetLangCreate; - - - DecimalFormat blockNrFormatter = new DecimalFormat("000000"); - - /** - * The hashcode of the current block - */ - private int CurrentBlockHash; - - private boolean skip; - - /** - * Create a new Instance of SDFREader - * - * @param source the file to read from - * @param sourceLanguage the sourceLanguage (must not be empty) - * @param targetLanguage the targetLanguage - * @param charset the charset used to read source - * @throws java.io.IOException - * @throws Exception - */ - public SDFReader(File source, String sourceLanguage, String targetLanguage, - String charset) throws java.io.IOException { - super(new InputStreamReader(new FileInputStream(source), charset)); - sourceFile = source; - this.sourceLanguage = sourceLanguage; - this.targetLanguage = targetLanguage; - String line; - String[] splitLine; - //read first line to get the first - //SDF block id - mark(16000); - if ((line = readLine()) != null) { - if ((splitLine = split(line)) != null){ - this.CurrentBlockId = getSDFBlockId(splitLine); - this.CurrentBlockHash=this.CurrentBlockId.hashCode(); - //found the first - this.blockNr++; - } - this.splittedLineBuffer = splitLine; - } - reset(); - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataReader#getData() - */ - public Map getData()throws IOException { - - Map map=new HashMap(); -// do { - this.skip=false; - Map[] help=readBlock(); - if(help==null||help[1]==null||help[0]==null){ - return null; -// }else if (help[1].get("TargetLanguageID")==null||help[0].get("SourceLanguageID")==null) { -// OutputHandler.log("Missing Language Id in block "+blockNr+"\nthe block is skipped." ); -// this.skippedBlocks++; -// this.skip=true; - }else{ - map.putAll(help[1]); - map.putAll(help[0]); - - } -// }while(this.skip=true); - return map; - } - - - /** - * Read a Block from the sdf file and return - * @return a Map[] where [0] holds the source and [1] the target language data. - * - * @throws java.io.IOException - */ - public Map[] readBlock() throws java.io.IOException { - String line = EMPTY; - String blockId = EMPTY; - String[] splittedLine = null; - data[0]=new ExtMap(); - data[1]=new ExtMap(); - String help; - String c = null; - //read next line or use buffered line - while (useBuffer || (line = readLine()) != null) { //works because '||' is shortcut - - try { - // buffer used? - if (useBuffer) { - line = this.lineBuffer; - splittedLine = this.splittedLineBuffer; - this.SDFMap = new ExtMap(SDFReader.fieldnames, splittedLine); - - try { - checkLanguage(splittedLine); - } catch (ConverterException e) { - throw e; - }finally{ - - useBuffer = false; - } - } else { - //...are there wrong characters? - if ((check(line)).length() < line.length()) { - throw new LineErrorException(getLineNumber() - + " : Line contains wrong character " - //+ Integer.toHexString(Integer.parseInt(c)) - + " \n" + line); - } - //...is the number of columns ok? - if ((splittedLine = split(line)) == null) { - - throw new LineErrorException(super.getLineNumber() - + " : Line has wrong column number \n" + line); - //continue; - } else { - // TODO makeDot is better in Data Handler - makeDot(); - // ...is this line in a new SDF block ? - if ((blockId = getSDFBlockId(splittedLine)) - .equals(CurrentBlockId)) { - - this.SDFMap = new ExtMap(SDFReader.fieldnames, - splittedLine); - //what language is in it ? - checkLanguage(splittedLine); - - } else { - - /* - * we found the next block , but do we have the - * target text? - */ - - if (!foundTarget) { - createTargetLine(); - } - - blockNr++; - splittedLineBuffer = splittedLine;//read one line - // too much so - // buffer it - lineBuffer = line; - useBuffer = true;//reset(); - - this.CurrentBlockId = blockId; - this.CurrentBlockHash=this.CurrentBlockId.hashCode(); - - /* ...and what about the source text ? */ - if (!foundSource) { - - OutputHandler - .log("Error in Line:" - + getLineNumber() - + "Source Language is missing maybe " - + "previous block has an error.\nBlock " - + (blockNr - 1) - + " is skipped. before line: \n" - + line); - - foundTarget = false;//no target without source - skippedBlocks++; - skippedLines++; - sourceLangMiss++; - continue;// skip output of this block if no - // source language is found - - } - - break; - - } - } - - } - - } catch (LineErrorException e) { - - OutputHandler.log(e.getMessage()); - this.skippedLines++; - } catch (ConverterException e) { - OutputHandler.log(e.getMessage()); - } - - } - // did we read the whole stuff? - if (null != line) { - // no - foundSource = false; - foundTarget = false; - - return this.data; - - } else { - // ok , its the end but is everything written now? - if (!endIt) { - // there is something to write - // but next time we can end it - endIt = true; - if(!foundTarget){ - createTargetLine(); - } - // write - return this.data;//last lines - } else { - - showStat(); - return null; - } - } - // }catch(ConverterException e) { - // Converter.log(e.getMessage()); - // return null; - // } - } - - /** - * - */ - private void createTargetLine() { - targetLangMiss++; - // if not, create one ... - data[1] = new ExtMap(SDFReader.targetLineNames, - splittedLineBuffer); - data[1].put("TargetLanguageID", - this.targetLanguage); - if ((String) data[1].get("TargetText") != EMPTY) - data[1].put("TargetText", EMPTY); - if ((String) data[1].get("TargetHText") != EMPTY) - data[1].put("TargetHText", EMPTY); - if ((String) data[1].get("TargetQText") != EMPTY) - data[1].put("TargetQText", EMPTY); - if ((String) data[1].get("TargetTitle") != EMPTY) - data[1].put("TargetTitle", EMPTY); - this.data[1].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toString(this.CurrentBlockHash)); - targetLangCreate++; - } - - /** - * Show the statistic information got while - * reading the file - * - * @throws IOException - */ - private void showStat() throws IOException { - OutputHandler.out(EMPTY);OutputHandler.out(EMPTY); - // OutputHandler.out("Hashes: " + (theHashes.size()) + " "); - OutputHandler.out("Blocks found: " + blockNr + " "); - OutputHandler.out(EMPTY); - OutputHandler.out("Lines read: " + (getLineNumber()) + " "); - OutputHandler - .dbg("Lines created " + (targetLangCreate) + " "); - OutputHandler.dbg(" -------"); - OutputHandler.dbg("Lines total: " - + (getLineNumber() + targetLangCreate) + " "); - OutputHandler.dbg("Lines skipped: " + skippedLines + " "); - - OutputHandler.dbg("Source Language misses: " + sourceLangMiss + " "); - OutputHandler.dbg("Target Language misses: " + targetLangMiss + " "); - OutputHandler.dbg("Blocks found: " + blockNr + " "); - OutputHandler.dbg("Blocks skipped: " + skippedBlocks + " "); - if ((sourceLangMiss + skippedBlocks + skippedLines) > 0) - OutputHandler.out("\n---! Errors found !--- view Logfile.\n\n" - + "To enable logfile use -l option at command line.\n" - + "For help type 'convert -h {Enter}'.\n"); - } - - /** - * Check the current line whether the source language - * or target language is in it - * - * @throws ConverterException if a not needed language or no target language is found - * in this block - * @throws IOException - * - */ - final private void checkLanguage(String[] splittedLine) - throws ConverterException, IOException { - String langID = (String) SDFMap.get("LanguageID"); - - //maybe the source language is in this line - if (!foundSource && this.sourceLanguage.equals(langID)) { -// found the next source language line - this.data[0] = new ExtMap(SDFReader.sourceLineNames, splittedLine); - -// this.data[0].put("BlockNr", Integer.toHexString(blockNr)); -// this.data[0].put("BlockHash", Integer.toHexString(this.CurrentBlockHash)); - this.data[0].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toHexString(this.CurrentBlockHash)); -// this.data[0].put("BlockHash", blockHashFormatter.format(this.CurrentBlockHash)); - foundSource = true; - return; - - } else { - // or the target language is in this line - if (!foundTarget) { - //no target language is given at command line - if (this.targetLanguage.equals(EMPTY)) { - //try if we can use the current lines language for target - // language - if (!langID.equals(this.sourceLanguage)) { - //yes , we can use this lines laanguage as target - this.targetLanguage = langID; - - //source and target language both are known: show it - OutputHandler.out("Source Language is: " - + this.sourceLanguage + " "); - OutputHandler.out("Target Language is: " - + this.targetLanguage + " "); - OutputHandler.out(EMPTY); - System.out.println("Start"); - - } else { - throw new ConverterException("(" + getLineNumber() - + ") No target language found: " - + this.targetLanguage); - } - } - if (this.targetLanguage.equals(langID)) { - this.data[1] = new ExtMap(SDFReader.targetLineNames, - splittedLine);// found the next target language line - this.data[1].put("BlockNr", blockNrFormatter.format(blockNr)+'-'+Integer.toHexString(this.CurrentBlockHash)); - foundTarget = true; - - return; - } - }//end !foundTarget - } - //if we go here we dont need the found language... - throw new ConverterException("found not needed language '" - + this.SDFMap.get("LanguageID") + "' in Line: " - + getLineNumber()); - - } - - /** - * Make a dot on the screen to show the user that it is going on - */ - private void makeDot() { - int count = 0; - if ((count = (int) super.getLineNumber() / 1000) > this.dotCount) { - this.dotCount = count; - OutputHandler.printDot(); - } - - } - - /** - * split the SDFLine in its columns - * - * @param line the current SDFLine - * @return the splitted SDFLine as array of String - * or null if an error occours - * @throws IOException - */ - private String[] split(String line) throws IOException { - check(line); - String[] splitLine; - if ((splitLine = line.split("\t")).length == 15) - return splitLine; - else - //an error occured - return null; - } - - /** - * create a block Id from a splitted SDFLine - * the blockId consists of the column one to eight of an SDF File - * - * @param splitLine the line to create a block id from - * @return the blockId as String - */ - private String getSDFBlockId(String[] splitLine) { - StringBuffer BlockId = new StringBuffer(""); - for (int i = 0; i < 8; i++) { - BlockId.append(splitLine[i]); - } - return BlockId.toString(); - } - -// public final boolean canRead() { -// return this.sourceFile.canRead(); -// } - - /** - * Check if there are not allowed characters in this line - * - * @param line the SDFLine to check - * @return if everything, ok the original - * else the wrong character as String - * - * @throws java.io.IOException - */ - private String check(String line) throws java.io.IOException { - char c = ' '; - for (int i = 0; i < line.length(); i++) { - c = line.charAt(i); - if (c < 30 && c != 9) { - return (new Character(c)).toString(); - } - - } - return line; - - } -} \ No newline at end of file diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java deleted file mode 100755 index 98eb8c856e6a..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/SDFWriter.java +++ /dev/null @@ -1,175 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: SDFWriter.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * SDFWriter.java - * - * - */ - -package com.sun.star.tooling.converter; -import java.io.*; -import java.util.Map; - -/** - * Write data to a SDFFile - * - * @author Christian Schmidt 2005 - * - */ -public class SDFWriter extends DataWriter { - /** - * the seperator the seperate columns - */ - final String seperator=new String("\t"); - /** - * an array of the SDF files column names if the source language is in - */ - final static String[] sourceLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TimeStamp"}; - /** - * an array of the SDF files column names if the target language is in - */ - final static String[] targetLineNames= {"Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; - /** - * an array of the SDF files column names if the source and the target language is in - */ - final static String[] outLineNames= {"BlockNr","Project","SourceFile","Dummy","ResType","GID","LID","HID","Platform","Width","SourceLanguageID","SourceText","SourceHText","SourceQText","SourceTitle","TargetLanguageID","TargetText","TargetHText","TargetQText","TargetTitle","TimeStamp"}; - - /** - * A Map holding the source language line content - */ - private ExtMap sourceLine=new ExtMap(sourceLineNames,null); - /** - * A Map holding the target language line content - */ - private ExtMap targetLine=new ExtMap(targetLineNames,null); - /** - * A Map holding the whole content for output - */ - private ExtMap outData=new ExtMap(outLineNames, null); -// private ExtMap SDFLine; -// private InputStreamReader isr; - /** - * The language to translate from - */ - private String sourceLanguage; - /** - * The language to translate to - */ - private String targetLanguage; - -// private boolean SourceIsFirst=false; - - - - - /** - * Create a new Instance of SDFWriter - * - * @param bos BufferedWriter to write to - * @param charset the charset to use to write - * @throws java.io.UnsupportedEncodingException - */ - public SDFWriter(BufferedOutputStream bos,String charset) throws java.io.UnsupportedEncodingException { - super(bos,charset); - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#writeData() - */ - public final void writeData() throws java.io.IOException { - - StringBuffer buffer=new StringBuffer(""); - - // get the values of the found fields - //create the two sdf lines - - //at first the source language line - for(int i=0;i - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * XLIFFReader.java - * - * - */ -package com.sun.star.tooling.converter; - -import java.io.IOException; -import java.util.Hashtable; -import java.util.Map; - -import com.sun.star.tooling.languageResolver.LanguageResolver; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.AttributesImpl; -import org.xml.sax.helpers.DefaultHandler; - - -/** - * Parse the given file and extract the content needed. - *
- * This Reader understands the parts of the - * xliff spezification used to translate - * the strings in Star-Office and Open-Office. - *
- * The given file is parsed and the content is stored in a HashMap with those keys: - *
- * "BlockNr" originally coming from reading the sdf file, contains 'block nr in sdf file'+'-'+'hash value of the sdf id fields'.
- * "Project" first column in sdf file format.
- * "SourceFile" second column in sdf file format.
- * "Dummy" third column in sdf file format.
- * "ResType" 4. column in sdf file format.
- * "GID" 5. column in sdf file format.
- * "LID" 6. column in sdf file format.
- * "HID" 7. column in sdf file format.
- * "Platform" 8. column in sdf file format.
- * "Width", 9. column in sdf file format.
- * "SourceLanguageID" 10. column in sdf file format(in the line with the source language).
- * "SourceText" 11. column in sdf file format(in the line with the source language).
- * "SourceHText" 12. column in sdf file format(in the line with the source language).
- * "SourceQText" 13. column in sdf file format(in the line with the source language).
- * "SourceTitle" 14. column in sdf file format(in the line with the source language).
- * "TargetLanguageID" 10. column in sdf file format (in the line with the target language).
- * "TargetText" 11. column in sdf file format (in the line with the target language).
- * "TargetHText" 12. column in sdf file format (in the line with the target language).
- * "TargetQText" 13. column in sdf file format (in the line with the target language).
- * "TargetTitle", 14. column in sdf file format (in the line with the target language).
- * "TimeStamp" 15. column in sdf file format.
- * @ - * @author Christian Schmidt 2005 - * - */ -public class XLIFFReader extends DefaultHandler { - - /** - * A String array holding the keys used by the HashMap holding the Data - */ - private final String[] dataNames = { "BlockNr", "Project", - "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", - "Width", "SourceLanguageID", "SourceText", "SourceHText", - "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", - "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; - - /** - * Used to index in the data array - */ - static int index = 0; - - /** - * The Map that holds the data returned by this class - */ - private Map moveData = new ExtMap(); - - /** - * A Map that holds yet incomplete data - * until all depending transunits are found - */ - private Hashtable DataStore = new Hashtable(); - - /** - * An Elements name - */ - private String name = new String(""); - - /** - *List of Attributes used by an Element - */ - private Attributes attrs; - -// private String tagElement = new String(""); - - /** - * Indicates whether the next found content string should be printed - */ - private boolean printThis = false; - /** - * Indicates whether the next found content string should be stored - */ - private boolean storeIt = false; - - /** - * data holds the information created while parsing - * - */ - private String[] data = new String[26]; - - /** - * The handler used by this class - */ - private final DataHandler handler; - /** - * The target used by this class - */ - private final DataWriter target; - -// private boolean searchForText = false; - - /** - * counts how many dots are made - */ - private int dotCount; - - /** - * Counts how many Trans Units are read - */ - private int transUnitCounter; - - /** - * used source Language - */ - private String sourceLanguage; - - /** - * used target language - */ - private String targetLanguage; - - /** - * indicates whether this is the first Transunit - */ - private boolean isFirst = true; - - private static final String EMPTY = new String(""); - - /** - * the last index in data where something is written - */ - private int oldindex; - -// private boolean isBptEptTag; - -// private String innerString; -// -// private String key; - - /** - * Index for the BlockNr in the data array - */ - private static final int BLOCKNR_IDX = 0; - /** - * Index for the Project in the data array - */ - private static final int PROJECT_IDX = 1; - /** - * Index for the Sourcefile name in the data array - */ - private static final int SOURCEFILE_IDX = 2; - /** - * Index for the 'dummy' in the data array - */ - private static final int DUMMY_IDX = 3; - /** - * Index for the Group Id in the data array - */ - private static final int GID_IDX = 4; - /** - * Index for the Local Id in the data array - */ - private static final int LID_IDX = 5; - /** - * Index for the Help Id in the data array - */ - private static final int HID_IDX = 6; - /** - * Index for the Platform in the data array - */ - private static final int PLATFORM_IDX = 7; - /** - * Index for the 'Width' in the data array - */ - private static final int WIDTH_IDX = 8; - /** - * Index for the Sourcelanguage Id in the data array - */ - private static final int SOURCE_LANGUAGE_ID_IDX = 10; - /** - * Index for the Source Text in the data array - */ - private static final int SOURCE_TEXT_IDX = 11; - /** - * Index for the Source Helptext in the data array - */ - private static final int SOURCE_HELPTEXT_IDX = 12; - /** - * Index for the Source Quickhelp Text in the data array - */ - private static final int SOURCE_QUICK_HELPTEXT_IDX = 13; - /** - * Index for the Source Titletext in the data array - */ - private static final int SOURCE_TITLETEXT_IDX = 14; - /** - * Index for the Timestamp in the data array - */ - private static final int TIMESTAMP_IDX = 15; - /** - * Index for the res type in the data array - */ - private static final int RESTYPE_IDX = 16; - /** - * Index for the Target Language Id in the data array - */ - private static final int TARGET_LANGUAGE_ID_IDX = 20; - /** - * Index for the Target Text in the data array - */ - private static final int TARGET_TEXT_IDX = 21; - /** - * Index for the Target Helptext in the data array - */ - private static final int TARGET_HELP_TEXT_IDX = 22; - /** - * Index for the Target Quickhelp Text in the data array - */ - private static final int TARGET_QUICKHELP_TEXT_IDX = 23; - /** - * Index for the Target Titletext in the data array - */ - private static final int TARGET_TITLE_TEXT_IDX = 24; - /** - * Index for the Found Parts Counter in the data array - */ - private static final int FOUND_PARTS_COUNTER_IDX = 18; - - /** - * used to find the matching ISO or RFC3066 language code - */ - LanguageResolver languageResolver; - - private boolean doBlockCompleteCheck=true; - - - - /** - * Create a new Instance of XLIFFReader - * - * @param handler the DataHandler to use - * @param target the target used - * @throws IOException - */ - public XLIFFReader(DataHandler handler, DataWriter target) throws IOException { - this.languageResolver = new LanguageResolver(); - this.handler = handler; - this.target = target; - } - - /** - * Create a new Instance of XLIFFReader - * - * @param handler the DataHandler to use - * @param target the target used - * @param doBlockCompleteCheck indicates whether every single transunit should be returned or the whole block data is to be collected - * - * @throws IOException - */ - public XLIFFReader(DataHandler handler, DataWriter target,boolean doBlockCompleteCheck) throws IOException { - this(handler, target); - this.languageResolver = new LanguageResolver(); - this.doBlockCompleteCheck=doBlockCompleteCheck; - - } - - /** - * delete and initialize the data content - */ - public void initData() { - for (int i = BLOCKNR_IDX; i < SOURCE_LANGUAGE_ID_IDX; i++) { - data[i] = ""; - } - for (int i = SOURCE_TEXT_IDX; i < TIMESTAMP_IDX; i++) { // skip Time Stamp - data[i] = ""; - } - for (int i = RESTYPE_IDX; i < TARGET_LANGUAGE_ID_IDX; i++) { // skip Source language ID - data[i] = ""; - } - for (int i = TARGET_TEXT_IDX; i < 26; i++) {// skip Target language ID, - data[i] = ""; - } - - data[DUMMY_IDX] = "0";//dummy - data[FOUND_PARTS_COUNTER_IDX] = "1";//parts found - - } - - /** (non-Javadoc) - * @see org.xml.sax.ContentHandler#startDocument() - */ - public void startDocument() { - initData(); - //System.out.print("Start"); - - } - - /** (non-Javadoc) - * @see org.xml.sax.ContentHandler#endDocument() - */ - public void endDocument() { - - try { - showStatistic(); - } catch (IOException e) { - - OutputHandler.log(e.getMessage()); - - } - } - - /** (non-Javadoc) - * @throws SAXException - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - public void startElement(String namespaceURI, String sName, String qName, - Attributes attrs) throws SAXException { - this.name = new String(qName); - this.attrs = new AttributesImpl(attrs); - String resType; - - String attributeName = new String(""); - String attribute = new String(""); - String tagElement = new String(""); - int i; - - if (qName.equals("bpt")||qName.equals("ept")||qName.equals("sub")||qName.equals("ex")) { - //ignore bpt, ept, ex and sub tags - // content of the tags will be stored - - storeIt=true; - return; - - } - if (qName.equals("target")) { - if ((resType = data[RESTYPE_IDX]) == null) { - - } else { - if ("res".equals(resType)) { - index = TARGET_TEXT_IDX; - - storeIt = true; - return; - } - // if("res-Help".equals(resType)){ - // index=TARGET_HELP_TEXT_IDX; - // storeIt=true; - // return; - // } - if ("res-QuickHelp".equals(resType)) { - index = TARGET_QUICKHELP_TEXT_IDX; - - storeIt = true; - return; - } - if ("res-Title".equals(resType)) { - index = TARGET_TITLE_TEXT_IDX; - - storeIt = true; - return; - } - } - - } - if (qName.equals("source")) { - if ((resType = data[RESTYPE_IDX]) == null) { - //throw new SAXException("Ressource type not found"); - } else { - if ("res".equals(resType)) { - index = SOURCE_TEXT_IDX; - - storeIt = true; - return; - } - // if("res-Help".equals(resType)){ - // index=SOURCEHELPTEXT_IDX; - // storeIt=true; - // return; - // } - if ("res-QuickHelp".equals(resType)) { - index = SOURCE_QUICK_HELPTEXT_IDX; - storeIt = true; - return; - } - if ("res-Title".equals(resType)) { - index = SOURCE_TITLETEXT_IDX; - storeIt = true; - return; - } - } - } - - if (qName.equals("file")) { - data[TIMESTAMP_IDX] = attrs.getValue("date"); - //data[17]=(attrs.getValue("original")); - try{ - data[SOURCE_LANGUAGE_ID_IDX] = (languageResolver.getISOFromRFC((String)attrs.getValue("source-language"))); - if(languageResolver.getISOFromRFC((String)attrs.getValue("target-language"))!=null){ - data[TARGET_LANGUAGE_ID_IDX] = (languageResolver.getISOFromRFC((String)attrs.getValue("target-language"))); - } - }catch(Exception e){ - OutputHandler.log(e.getMessage()); - } - return; - } - if (qName.equals("trans-unit")) { - String id = attrs.getValue("id"); - if ((DataStore.get(id)) != null) { - //TODO arraycopy might not be nessessary - System.arraycopy((String[]) DataStore.get(id), 0, data, 0, - data.length); - int help = (new Integer(data[FOUND_PARTS_COUNTER_IDX])).intValue(); //found one more part - help++; // refresh the actual found parts - data[FOUND_PARTS_COUNTER_IDX] = (new Integer(help)).toString(); // belonging to this information - - DataStore.remove(attrs.getValue("id")); // TODO this can be deleted? - } else { - - data[BLOCKNR_IDX] = (attrs.getValue("id")); // a new part - } - data[RESTYPE_IDX] = (attrs.getValue("restype")); - - return; - } - - if (qName.equals("context")) { - - String value = attrs.getValue("context-type"); - - if ("SourceHelpText".equals(value)) { - index = SOURCE_HELPTEXT_IDX; - storeIt = true; - return; - }else if ("TargetHelpText".equals(value)) { - index = TARGET_HELP_TEXT_IDX; - storeIt = true; - return; - }else if ("DBType".equals(value)) { - //index=SOURCEFILE_IDX; - //storeIt=true; - return; - }else if ("Project".equals(value)) { - index = PROJECT_IDX; - storeIt = true; - return; - }else if ("Filename".equals(value)) { - index = SOURCEFILE_IDX; - storeIt = true; - return; - }else if ("Type".equals(value)) { - index = RESTYPE_IDX; - storeIt = true; - return; - }else if ("GID".equals(value)) { - index = GID_IDX; - storeIt = true; - return; - }else if ("LID".equals(value)) { - index = LID_IDX; - storeIt = true; - return; - }else if ("HID".equals(value)) { - index = HID_IDX; - storeIt = true; - return; - }else if ("Platform".equals(value)) { - index = PLATFORM_IDX; - storeIt = true; - return; - }else if ("Width".equals(value)) { - index = WIDTH_IDX; - storeIt = true; - return; - } - - } - - } - - /** (non-Javadoc) - * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) - */ - public void endElement(String namespaceURI, String sName, String qName) - throws SAXException { - //we ignore bpt and ept tags - if(!(qName.equals("bpt")||qName.equals("ept")||qName.equals("sub")||qName.equals("ex"))){ - storeIt = false; - } - if (qName.equals("trans-unit")) { - showData(); - } - - } - - /** (non-Javadoc) - * @see org.xml.sax.ContentHandler#characters(char[], int, int) - */ - public void characters(char[] ch, int start, int length) { - - // checkContent(); - String str2 = new String(ch, start, length); - - if (storeIt) { - - String str = new String(ch, start, length); - if (index == oldindex) { - data[index] += str; - } else { - data[index] = str; - } - - } - oldindex = index; - - } - - /** (non-Javadoc) - * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) - */ - public void error(SAXParseException e) throws SAXParseException { - - OutputHandler.log(e.getMessage()); - } - - /** (non-Javadoc) - * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) - */ - public void fatalError(SAXParseException e) throws SAXParseException { - - OutputHandler.log("PARSE ERROR in line " + e.getLineNumber() + ", " - + e.getMessage() ); - - } - - /** (non-Javadoc) - * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) - */ - public void warning(SAXParseException e) throws SAXParseException { - //throw e; - OutputHandler.log(e.getMessage()); - } - - /** - * Put the Data to the DataHandler - * tell the Writer to write it - * - * @throws SAXException - */ - public void showData() throws SAXException { - transUnitCounter++; - makeDot(); - if (isComplete()) { - - try { - moveData(); - if (isFirst == true) { - this.sourceLanguage = (String) this.moveData - .get("SourceLanguageID"); - this.targetLanguage = (String) this.moveData - .get("TargetLanguageID"); - OutputHandler.out(EMPTY); - OutputHandler.out("Source Language is: " - + this.sourceLanguage); - OutputHandler.out("Target Language is: " - + this.targetLanguage); - OutputHandler.out(EMPTY); - OutputHandler.out("Start"); - OutputHandler.out(EMPTY); - isFirst = false; - } - target.getDataFrom(handler); - target.writeData(); - - } catch (java.io.IOException e) { - throw new SAXException(e); - } - - } else { - DataStore.put(data[BLOCKNR_IDX], data.clone()); - initData(); - - } - initData(); - } - - - /** - * put the data in an Map in the format that - * DataHandler can handle it - */ - final public void moveData() { - - moveData.put("BlockNr", data[BLOCKNR_IDX]); - - moveData.put("Project", data[PROJECT_IDX]); - - moveData.put("SourceFile", data[SOURCEFILE_IDX]); - - moveData.put("Dummy", "0"); - - moveData.put("ResType", data[RESTYPE_IDX]); - - moveData.put("GID", data[GID_IDX]); - - moveData.put("LID", data[LID_IDX]); - - moveData.put("HID", data[HID_IDX]); - - moveData.put("Platform", data[PLATFORM_IDX]); - - if (EMPTY.equals(data[WIDTH_IDX])) - data[WIDTH_IDX] = "0"; - moveData.put("Width", data[WIDTH_IDX]); - - moveData.put("SourceLanguageID", data[SOURCE_LANGUAGE_ID_IDX]); - - moveData.put("SourceText", data[SOURCE_TEXT_IDX]); - - moveData.put("SourceHText", data[SOURCE_HELPTEXT_IDX]); - - moveData.put("SourceQText", data[SOURCE_QUICK_HELPTEXT_IDX]); - - moveData.put("SourceTitle", data[SOURCE_TITLETEXT_IDX]); - - moveData.put("TargetLanguageID", data[TARGET_LANGUAGE_ID_IDX]); - - moveData.put("TargetText", data[TARGET_TEXT_IDX]); - - moveData.put("TargetHText", data[TARGET_HELP_TEXT_IDX]); - - moveData.put("TargetQText", data[TARGET_QUICKHELP_TEXT_IDX]); - - moveData.put("TargetTitle", data[TARGET_TITLE_TEXT_IDX]); - - moveData.put("TimeStamp", data[TIMESTAMP_IDX]); - - //and give it to the data handler - this.handler.fillDataWith(moveData); - } - - /** - * complete means all depending parts have been found esp. all res types - * that belong to the same SDF Line - * - * @return true if the data is complete - * - */ - final public boolean isComplete() { - - if(!doBlockCompleteCheck){ - return true; - } - - String sParts; - if (data[FOUND_PARTS_COUNTER_IDX] == EMPTY) - data[FOUND_PARTS_COUNTER_IDX] = "1"; //this is the first part - - String sFoundParts = data[FOUND_PARTS_COUNTER_IDX]; - //create the new 'id' - sParts = data[BLOCKNR_IDX].substring(data[BLOCKNR_IDX].lastIndexOf(":") + 1); - - if (sFoundParts.equals(sParts)) { - return true; - } - return false; - } - - // TODO this belongs in OutputHandler - /** - * show the user that it is going - * on by printing dots on the screen - * - */ - private void makeDot() { - int count = 0; - if ((count = (int) this.transUnitCounter / 1000) > this.dotCount) { - this.dotCount = count; - OutputHandler.printDot(); - } - } - - /** - * show the statistic data found while parse this file - * - * @throws IOException - */ - final void showStatistic() throws IOException { - OutputHandler.out(EMPTY); - OutputHandler.out("TransUnits found: " + this.transUnitCounter); - // every data in DataStore is - // skipped 'cause its not complete - // TODO count really every transunit not only the data (might consist of - // more than one - OutputHandler.dbg("TransUnits skip : " + this.DataStore.size()); - //Converter.out(EMPTY); - } -} - diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java deleted file mode 100755 index 42eef42884c1..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/XLIFFWriter.java +++ /dev/null @@ -1,535 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: XLIFFWriter.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * - /* - * XLIFFWriter.java - * - * - */ - -package com.sun.star.tooling.converter; - -import java.io.*; -import java.util.*; - -import com.sun.star.tooling.DirtyTags.DirtyTagWrapper; -import com.sun.star.tooling.languageResolver.LanguageResolver; -import com.sun.star.tooling.languageResolver.LanguageResolver.LanguageResolvingException; - -/** - * Write the Data to a wellformed XLIFF File - * - * @author Christian Schmidt - */ -public class XLIFFWriter extends DataWriter { - - /** - * An array holding the keys of the HashMap containing the source language string - */ - private final static String[] sourceLineNames = { "Project", "SourceFile", - "Dummy", "ResType", "GID", "LID", "HID", "Platform", "Width", - "SourceLanguageID", "SourceText", "SourceHText", "SourceQText", - "SourceTitle", "TimeStamp" }; - /** - * An array holding the keys of the HashMap containing the target language string - */ - private final static String[] targetLineNames = { "Project", "SourceFile", - "Dummy", "ResType", "GID", "LID", "HID", "Platform", "Width", - "TargetLanguageID", "TargetText", "TargetHText", "TargetQText", - "TargetTitle", "TimeStamp" }; - /** - * An array holding the keys of the HashMap containing the source and target language string - */ - private final static String[] outLineNames = { "BlockNr", "Project", - "SourceFile", "Dummy", "ResType", "GID", "LID", "HID", "Platform", - "Width", "SourceLanguageID", "SourceText", "SourceHText", - "SourceQText", "SourceTitle", "TargetLanguageID", "TargetText", - "TargetHText", "TargetQText", "TargetTitle", "TimeStamp" }; - /** - * An Map holding the source and target content - */ - private final Map data = new ExtMap(outLineNames, null); - - - /** - * Indicates if this is the first Transunit to write - */ - boolean isFirst = true; - - LanguageResolver languageResolver; - - - /** - * Create a new Instance of XLIFFWriter - * - * @param bos the Buffered Output Stream to write to - * @param charset the charset to use - * @throws IOException - */ - public XLIFFWriter(BufferedOutputStream bos, String charset) - throws IOException { - super(bos, charset); - this.languageResolver =new LanguageResolver(); - - - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#getDatafrom(com.sun.star.tooling.converter.DataHandler) - */ - public void getDatafrom(DataHandler handler) throws java.io.IOException { - handler.putDataTo(this.data); - } - - /** - * check if the item is an empty String - * - * @param item the string to check - * @return true if it is not empty, false if it is empty - */ - private final boolean isUsed(String item) { - if (!"".equals(item)) - return true; - return false; - } - - /** - * Replaces all characters that mustn't be in XLIFF PCdata - * - * @param string the string to check - * @return the checked string with all characters replaced - * @throws java.io.IOException - */ - private final String xmlString( final String string) throws java.io.IOException { - if (string == null) - return string; // "" - String str = string; -// str = str.replaceAll("&", "&"); -// str = str.replaceAll("<", "<"); -// str = str.replaceAll(">", ">"); -// str = str.replaceAll("\"", """); -// str = str.replaceAll("'", "'"); - for(int i=0;i'){ - str=str.substring(0, i)+">"+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='"'){ - str=str.substring(0, i)+"""+str.substring(i+1); - continue; - } - - if(str.charAt(i)=='\''){ - str=str.substring(0, i)+"'"+str.substring(i+1); - continue; - } - } - - return str; - } - - /* (non-Javadoc) - * @see java.io.Writer#close() - */ - public void close() throws IOException { - this.writeTrailer(); - - super.close(); - } - - /* (non-Javadoc) - * @see com.sun.star.tooling.converter.DataWriter#writeData() - */ - public void writeData() throws IOException { - if (isFirst) { - - writeHeader(); - isFirst = false; - } - try{ - writeTransUnit(); - }catch(DirtyTagWrapper.TagWrapperException e){ - - } - } - - /** - * Write the XLIFFFiles header - * - * @throws IOException - */ - private void writeHeader() throws IOException { - - this.write(getHeader()); - } - - /** - * Write the XLIFFFiles Trailer - * - * @throws IOException - */ - private void writeTrailer() throws IOException { - this.write(getTrailer()); - } - - /** - * Write the next TransUnit - * - * @throws IOException - */ - private void writeTransUnit() throws IOException, DirtyTagWrapper.TagWrapperException { - try{ - StringBuffer writeBuffer = new StringBuffer(1000); - - StringBuffer allLinesEnd = new StringBuffer(200); - String sRessource = ""; - int parts = 0; - if (data == null) { - OutputHandler.out("error");// TBD Exception - } - - if (!(this.data.get("SourceText").equals("") || this.data.get( - "SourceText").equals(" "))) { - parts++; - } - // if(!(this.data.get("SourceHText").equals("")||this.data.get("SourceHText").equals(" - // "))){ - // parts++; - // } - if (!(this.data.get("SourceQText").equals("") || this.data.get( - "SourceQText").equals(" "))) { - parts++; - } - if (!(this.data.get("SourceTitle").equals("") || this.data.get( - "SourceTitle").equals(" "))) { - parts++; - } - if (!(this.data.get("SourceText").equals("") || this.data.get( - "SourceText").equals(" "))) { - sRessource = "res"; // normal TEXT source - - allLinesEnd - .append("\t\t\t\t\n"); - - if (isUsed((String) this.data.get("ResType"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data.get("ResType")) - + "\n"); - if (isUsed((String) this.data.get("Project"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data.get("Project")) - + "\n"); - if (isUsed((String) this.data.get("SourceFile"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data - .get("SourceFile")) + "\n"); - if (isUsed((String) this.data.get("SourceHText"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data - .get("SourceHText")) + "\n"); - if (isUsed((String) this.data.get("TargetHText"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data - .get("TargetHText")) + "\n"); - if (isUsed((String) this.data.get("ResType"))) - allLinesEnd.append("\t\t\t\t\t" - + xmlString((String) this.data.get("ResType")) - + "\n"); - if (isUsed((String) this.data.get("GID"))) - allLinesEnd.append("\t\t\t\t\t" - + xmlString((String) this.data.get("GID")) - + "\n"); - if (isUsed((String) this.data.get("LID"))) - allLinesEnd.append("\t\t\t\t\t" - + xmlString((String) this.data.get("LID")) - + "\n"); - if (isUsed((String) this.data.get("HID"))) - allLinesEnd.append("\t\t\t\t\t" - + xmlString((String) this.data.get("HID")) - + "\n"); - if (isUsed((String) this.data.get("Platform"))) - allLinesEnd - .append("\t\t\t\t\t" - + xmlString((String) this.data.get("Platform")) - + "\n"); - if (isUsed((String) this.data.get("Width"))) - allLinesEnd.append("\t\t\t\t\t" - + xmlString((String) this.data.get("Width")) - + "\n"); - allLinesEnd.append("\t\t\t\t\n" - + "\t\t\t\n"); - - writeBuffer.append("\t\t\t\n"); - if (isUsed((String) this.data.get("SourceText"))) - writeBuffer.append("\t\t\t\t" - + DirtyTagWrapper.wrapString((String) this.data.get("SourceText")) - + "\n"); - - if (isUsed((String) this.data.get("TargetText"))) - writeBuffer - .append("\t\t\t\t" - +DirtyTagWrapper.wrapString((String) this.data - .get("TargetText")) + "\n"); - writeBuffer.append(allLinesEnd); - Converter.countLine(); - - } - // if(!(this.data.get("SourceHText").equals("")||this.data.get("SourceHText").equals(" - // "))){ - // sRessource="res-Help"; //Source is Help - // //sLineNumber=String.valueOf(iLineNumber);// - // writeBuffer.append("\t\t\n");//always translate - // if(isUsed((String)this.data.get("SourceHText"))) - // writeBuffer.append("\t\t\t"+xmlString((String)this.data.get("SourceHText"))+"\n"); - // if(isUsed((String)this.data.get("TargetHText"))) - // writeBuffer.append("\t\t\t"+xmlString((String)this.data.get("TargetHText"))+"\n"); - // writeBuffer.append(allLinesEnd); - // Converter.countLine(); - // } - - if (!(this.data.get("SourceQText").equals("") || this.data.get( - "SourceQText").equals(" "))) { - sRessource = "res-QuickHelp"; // Source is OuickHelp - // sLineNumber=String.valueOf(iLineNumber);// - writeBuffer.append("\t\t\t\n");// always translate - if (isUsed((String) this.data.get("SourceQText"))) - writeBuffer.append("\t\t\t\t" - + DirtyTagWrapper.wrapString((String) this.data.get("SourceQText")) - + "\n"); - if (isUsed((String) this.data.get("TargetQText"))) - writeBuffer - .append("\t\t\t\t" - + DirtyTagWrapper.wrapString((String) this.data - .get("TargetQText")) + "\n"); - writeBuffer.append(allLinesEnd); - Converter.countLine(); - } - - if (!(this.data.get("SourceTitle").equals("") || this.data.get( - "SourceTitle").equals(" "))) { - sRessource = "res-Title"; // Source is Title - - writeBuffer.append("\t\t\t\n");// always translate - if (isUsed((String) this.data.get("SourceTitle"))) - writeBuffer.append("\t\t\t\t" - + DirtyTagWrapper.wrapString((String) this.data.get("SourceTitle")) - + "\n"); - if (isUsed((String) this.data.get("TargetTitle"))) - writeBuffer - .append("\t\t\t\t" - + DirtyTagWrapper.wrapString((String) this.data - .get("TargetTitle")) + "\n"); - writeBuffer.append(allLinesEnd); - Converter.countLine(); - } - this.write(writeBuffer.toString()); - }catch(Exception e){ - OutputHandler.log(e.getMessage()); - } - } - - /** - * Create the XLIFFFiles Header - * - * @return the header as string - * @throws java.io.UnsupportedEncodingException - */ - private String getHeader() throws java.io.UnsupportedEncodingException { - return new String( - (getProcessingInstructionTag() + getDTDLine() - + openVersionLine() + openFileLine() + getHeaderTag() + openBodyTag()) - .getBytes(), "UTF8"); - - } - - /** - * Create the XLIFFFiles Trailer - * - * @return the trailer as string - */ - private String getTrailer() { - return closeBodyTag() + closeFileLine() + closeVersionLine(); - } - - /** - * Create the Processing Instruction Tag used by this XLIFFFile - * @return the Processing Instruction Tag used by this XLIFFFile - */ - private String getProcessingInstructionTag() { - String sPITagStart = ""; - return sPITagStart + sPIName + sPIVersion + sPIEncoding - + /* sPIStandalone+ */sPITagEnd + '\n'; - } - - /** - * Create the line holding the DTD referenced by this XLIFFFile - * @return a string holding the DTD referenced by this XLIFFFile - */ - private String getDTDLine() { - String sDTDTagStart = "";// http://www.oasis-open.org/committees/xliff/documents/ - String sDTSTagEnd = ">"; - return sDTDTagStart + sDTDType + sDTDSource + '\n'; - } - - /** - * Create the beginning of the line holding the version of this XIFFFile - * - * @return a string with the beginning of the line holding the version of this XIFFFile - */ - private String openVersionLine() { - return "\n"; - } - /** - * Create the ending of the line holding the version of this XIFFFile - * - * @return a string with the ending of the line holding the version of this XIFFFile - */ - private String closeVersionLine() { - return ""; - } - /** - * Create the beginning of the line holding the file tag of this XIFFFile - * - * @return a string with the beginning of the file tag of this XIFFFile - */ - private String openFileLine() { - - String FileTagStart = "\t"; - } - /** - * Create a String containing the header tag - * @return the String containing the header tag - */ - private String getHeaderTag() { - return "
\n"; - } - /** - * Create the begining of the line holding the body tag of this XIFFFile - * - * @return a string with the begining of the body tag of this XIFFFile - */ - private String openBodyTag() { - return "\t\t\n"; - } - /** - * Create the ending of the line holding the body tag of this XIFFFile - * - * @return a string with the ending of the body tag of this XIFFFile - */ - private String closeBodyTag() { - return "\t\t"; - } - - /* - * (non-Javadoc) - * - * @see com.sun.star.tooling.converter.DataWriter#writeData(java.util.Map[]) - */ - protected void writeData(Map[] data) throws IOException { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see com.sun.star.tooling.converter.DataWriter#getDataFrom(com.sun.star.tooling.converter.DataHandler) - */ - protected void getDataFrom(DataHandler handler) { } - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd b/transex3/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd deleted file mode 100755 index 91262ec28204..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/converter/dtd/xliff.dtd +++ /dev/null @@ -1,391 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java b/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java deleted file mode 100755 index 62ff008156ab..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/LanguageResolver.java +++ /dev/null @@ -1,201 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: LanguageResolver.java,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -/* - * Created on 2005 - * by Christian Schmidt - */ -package com.sun.star.tooling.languageResolver; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.ListIterator; - -/** - * Translate language codes into another format - * between ISO, RFC3066 and numeric - * - * @author Christian Schmidt 2005 - * - */ -public class LanguageResolver { - private final static int ISO =2; - private final static int LANGID =0; - private final static int LANGNAME =1; - private final static int RFC3066 =3; - - ArrayList languages=new ArrayList(); - -// public static void main(String[] args){ -// try { -// LanguageResolver lr=new LanguageResolver(); -// } catch (IOException e) { -// // -// e.printStackTrace(); -// } -// } - - /** - * Create a new Instance of LanguageResolver - * - * @throws IOException - */ - public LanguageResolver() throws IOException{ - String lang = "com/sun/star/tooling/languageResolver/lang.map"; - ClassLoader cl = this.getClass().getClassLoader(); - InputStream in = cl.getResourceAsStream(lang); - BufferedReader languageTable= new BufferedReader(new InputStreamReader(in)); - - String line; - - while((line=(languageTable.readLine()))!=null){ - languages.add(line.split(",")); - } - } - /** - * Get the numeric value of the given ISO Language Code - * - * @param isoCode the ISO Language Code to find - * @return numeric value of the given isoCode - * @throws LanguageResolvingException if the Language ISO Code is not known - */ - public String getNrFromISO(String isoCode) throws LanguageResolvingException{ - if("".equals(isoCode)) return ""; - ListIterator iter=languages.listIterator(); - String[] line=new String[5]; - while(isoCode!="" && iter.hasNext()){ - line=(String[]) iter.next(); - if(line[ISO].equals(isoCode)) return line[LANGID]; - } - throw new LanguageResolvingException("Can not find ISO Code: "+isoCode ); - - } - - /** - * Get the ISO Language Code corresponding with the given Language ID - * - * @param ID the numeric language id to find - * @return the ISO Language Code corresponding with the given Language ID - * @throws LanguageResolvingException if the Language ID is not known - */ - public String getISOfromNr(String ID) throws LanguageResolvingException{ - if("".equals(ID)) return ""; - ListIterator iter=languages.listIterator(); - String[] line=new String[5]; - while(iter.hasNext()){ - line=(String[]) iter.next(); - if(line[LANGID].equals(ID)) return line[ISO]; - } - throw new LanguageResolvingException("Can not find Language Id: "+ID ); - } - - /** - * Get the RFC3066 value of the given ISO Language Code - * - * @param isoCode the ISO Language Code to find - * @return RFC3066 value of the given isoCode - * @throws LanguageResolvingException if the Language ISO Code is not known - */ - public String getRFCFromISO(String isoCode) throws LanguageResolvingException{ - if("".equals(isoCode)) return ""; - ListIterator iter=languages.listIterator(); - String[] line=new String[5]; - while(iter.hasNext()){ - line=(String[]) iter.next(); - if(line[ISO].equals(isoCode)) return line[RFC3066]; - } - throw new LanguageResolvingException("Can not find ISO Code: "+isoCode ); - } - - /** - * Get the ISO Language Code corresponding with the given RFC3066 code - * - * @param RFC RFC3066 language id to find - * @return the ISO Language Code corresponding with the given RFC3066 code - * @throws LanguageResolvingException if the RFC3066 code is not known - */ - public String getISOFromRFC(String RFC) throws LanguageResolvingException{ - if("".equals(RFC)) return ""; - ListIterator iter=languages.listIterator(); - String[] line=new String[5]; - while(iter.hasNext()){ - line=(String[]) iter.next(); - if(line[RFC3066].equals(RFC)) return line[ISO]; - } - throw new LanguageResolvingException("Can not find Language Id: "+RFC ); - } - - - /** - * This Exception is thrown if a Language Identfier is unknown - * - * @author Christian Schmidt 2005 - * - */ - public class LanguageResolvingException extends Exception { - - /** - * - */ - public LanguageResolvingException() { - super(); - // - } - - /** - * @param arg0 - */ - public LanguageResolvingException(String arg0) { - super(arg0); - // - } - - /** - * @param arg0 - * @param arg1 - */ - public LanguageResolvingException(String arg0, Throwable arg1) { - super(arg0, arg1); - // - } - - /** - * @param arg0 - */ - public LanguageResolvingException(Throwable arg0) { - super(arg0); - // - } - - } - -} diff --git a/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map b/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map deleted file mode 100755 index a43e8f5e0218..000000000000 --- a/transex3/java/l10nconv/java/com/sun/star/tooling/languageResolver/lang.map +++ /dev/null @@ -1,41 +0,0 @@ -1,English,en-US,en-US,1033 -3,Portuguese,pt,pt-PT,2070 -30,Greek,el,el-GR,1032 -33,French,fr,fr-FR,1036 -35,Finnish,fi,fi-FI,1035 -39,Italian,it,it-IT,1040 -43,Slowak,sk,sk-SK,1051 -46,Swedish,sv,sv-SE,1053 -48,Polish,pl,pl-PL,1045 -55,Portuguese (Brasil),pt-BR,pt-BR,2070 -82,Korean,ko,ko-KR,1042 -88,Chinese (traditional),zh-TW,zh-TW,1028 -96,Arabic,ar,,1025 -97,Hebrew,he,he-IL,1037 -7,Russian,ru,ru-RU,1049 -31,Dutch,nl,nl-NL,1043 -34,Spanish,es,es-ES,1034 -36,Hungarian,hu,hu-HU,1038 -42,Czech,cs,cs-CZ,1029 -45,Danish,da,da-DK,1030 -47,Norwegian (Bokmal),nb,nb-NB,1044 -49,German,de,de-DE,1031 -81,Japanese,ja,ja-JP,1041 -86,Chinese (simple),zh-CN,zh-CN,2052 -90,Turkish,tr,tr-TR,1055 -37,Catalan,ca,, -66,Thai,th,th-TH, -91,Hindi,hi-IN,hi-IN, -77,Estonian,et,et, -50,Slovenian,sl,sl, -79,Norwegian Nynorsk,nn,nn-NN, -53,Welsh,cy,cy, -27,Afrikaans,af,af-ZA, -38,Galician,gl-ES,gl-ES, -58,Lithuanian,lt,lt-LT, -29,Tswana,tn,tn-TN, -76,Khmer ( Cambodia ),km,km, -26,Northern Sotho,ns,ns-ZA, -28,Zulu,zu,zu-ZA, -10,Basque,eu,eu-ES, -93,Kannada,kn,kn-KN, \ No newline at end of file diff --git a/transex3/java/l10nconv/makefile.mk b/transex3/java/l10nconv/makefile.mk deleted file mode 100755 index feb869778e80..000000000000 --- a/transex3/java/l10nconv/makefile.mk +++ /dev/null @@ -1,39 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.3 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ=../.. -PRJNAME=transex3 -TARGET=converter - -.INCLUDE : ant.mk - -ALLTAR : ANTBUILD - diff --git a/transex3/java/receditor/build.xml b/transex3/java/receditor/build.xml deleted file mode 100755 index 34f02128f034..000000000000 --- a/transex3/java/receditor/build.xml +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/transex3/java/receditor/java/transex3/controller/EditorController.java b/transex3/java/receditor/java/transex3/controller/EditorController.java deleted file mode 100644 index 38462d665304..000000000000 --- a/transex3/java/receditor/java/transex3/controller/EditorController.java +++ /dev/null @@ -1,334 +0,0 @@ -package transex3.controller; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.*; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.Runtime; -import java.util.*; - -import javax.swing.ListSelectionModel; -import javax.swing.WindowConstants; -import javax.swing.event.*; - -import transex3.model.*; - -import java.io.*; -import javax.swing.*; -//import transex3.model.*; -public class EditorController { - public final String[] RESTYPES = { ".src",".hrc",".xcu",".xrm",".xhp" }; - public final String RECFILE = ".recommand"; - // Editor View - static transex3.view.Editor aEditor = null; - // Editor Model - static Vector sdfstrings = new Vector(); - static HashMap hashedsdfstrings = new HashMap(); - int oldindex = 0; - //HashMap hashedfilenames = new HashMap(); - // Search for source Strings - public String fetchSourceStrings( String rootdir ){ - - //String outputfile = "h:\\workspace\\recommandEditor\\null2"; - File tempfile = null; - - try { - tempfile = File.createTempFile( "receditor" , "tmp" ); - } catch (IOException e1) { - // TODO Auto-generated catch block - System.err.println("Can not create temp file\n"); - e1.printStackTrace(); - } - - String outputfile = tempfile.getAbsolutePath(); - try - { - //System.out.println("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile+" -d "+rootdir); - System.out.println("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile ); - java.lang.Process aProc = Runtime.getRuntime().exec("localize_sl -QQ -skip_links -e -l en-US -f "+outputfile); - - //java.lang.Process aProc = Runtime.getRuntime().exec("localize_sl -QQ -e -l en-US -f "+outputfile+" -d "+rootdir); - BufferedReader aBR = new BufferedReader( new InputStreamReader( aProc.getInputStream() ) ); - String line = aBR.readLine(); - while( line != null && line.length() > 0 ){ - //System.out.print( line ); - line = aBR.readLine(); - } - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return outputfile; - } - // Search for recommand files - public void findRecommandFiles( File rootdir , Vector list ){ - System.out.print("."); - System.out.flush(); - File[] aFileArray = rootdir.listFiles(); - if( aFileArray != null ){ - for( int cnt = 0; aFileArray.length > cnt ; cnt++ ){ - if( aFileArray[ cnt ].isDirectory() && !aFileArray[ cnt ].getAbsolutePath().endsWith(".lnk") ) - findRecommandFiles( aFileArray[ cnt ] , list); - else if( aFileArray[ cnt ].isFile() && isRecommandFile( aFileArray[ cnt ] ) ) - list.add( aFileArray[ cnt ]); - } - } - } - private boolean isResourceType( File aFile ){ - String filename = aFile.getName(); - boolean isResType = false; - for(int cnt = 0; cnt < RESTYPES.length ; cnt++){ - if( filename.endsWith( RESTYPES[ cnt ] ) ) - isResType = true; - } - return isResType; - } - private boolean isRecommandFile( File aFile ){ - return aFile.getName().endsWith( RECFILE ); - } - public void clearAllRows( JTable aTable ){ - for ( int n = 0; n < aTable.getRowCount() ; n++ ){ - aTable.setValueAt( null , n , 0 ); - aTable.setValueAt( null , n , 1 ); - aTable.setValueAt( null , n , 2 ); - aTable.setValueAt( null , n , 3 ); - aTable.setValueAt( null , n , 4 ); - } - } - // Add all data to view - void updateData(){ - JTable recTable =transex3.controller.EditorController.aEditor.getRectable(); - - SdfString aSdfString = (SdfString) sdfstrings.get( oldindex ); - Vector newStrings = new Vector(); - for ( int n = 1; n < recTable.getRowCount() ; n++ ){ - String lang = (String) recTable.getValueAt(n , 0 ); - String text = (String) recTable.getValueAt(n , 1 ); - String htext = (String) recTable.getValueAt(n , 2 ); - String qhtext = (String) recTable.getValueAt(n , 3 ); - String ttext = (String) recTable.getValueAt(n , 4 ); - if( lang != null && text != null ){ - //System.out.println("Data "+ lang + " " + text ); - SdfEntity aSdfEntity = new SdfEntity(); - aSdfEntity.setLangid( lang ); - aSdfEntity.setText( text ); - aSdfEntity.setHelptext( htext ); - aSdfEntity.setQuickhelptext( qhtext ); - aSdfEntity.setTitle( ttext ); - newStrings.add( aSdfEntity ); - aSdfString.setLanguageStrings( newStrings ); - } - } - } - - public void initView(){ - Object[][] sourceStringData = new Object[ sdfstrings.size() ][ 4 ]; - Object[][] firstData = new Object[100][5]; - // Set the files - Iterator aIter = sdfstrings.iterator(); - int counter = 0; - while( aIter.hasNext() ){ - SdfString aSdfString = (SdfString) aIter.next(); - sourceStringData[ counter ][ 0 ] = aSdfString.getSourceString().getProject()+"\\"+aSdfString.getSourceString().getSource_file(); - sourceStringData[ counter ][ 1 ] = aSdfString.getSourceString().getGid(); - sourceStringData[ counter ][ 2 ] = aSdfString.getSourceString().getLid(); - sourceStringData[ counter ][ 3 ] = aSdfString.getSourceString().getText(); - if( counter == 0 ){ - firstData[ 0 ][ 0 ] = "en-US"; - firstData[ 0 ][ 1 ] = aSdfString.getSourceString().getText(); - firstData[ 0 ][ 2 ] = aSdfString.getSourceString().getHelptext(); - firstData[ 0 ][ 3 ] = aSdfString.getSourceString().getQuickhelptext(); - firstData[ 0 ][ 4 ] = aSdfString.getSourceString().getTitle(); - aSdfString = (SdfString) sdfstrings.get( 0 ); - Vector values = aSdfString.getLanguageStrings(); - for( int n = 0; n < values.size() ; n++ ) - { - SdfEntity aEntity = (SdfEntity) values.get( n ); - firstData[ n+1 ][ 0 ] = aEntity.getLangid(); - firstData[ n+1 ][ 1 ] = aEntity.getText(); - firstData[ n+1 ][ 2 ] = aEntity.getHelptext(); - firstData[ n+1 ][ 3 ] = aEntity.getQuickhelptext(); - firstData[ n+1 ][ 4 ] = aEntity.getTitle(); - } - } - counter++; - } - // Set the source srtings - - - //aEditor = new transex3.view.Editor( sourceStringData , filedata.toArray() ); - aEditor = new transex3.view.Editor( sourceStringData , firstData ); - - aEditor.setBounds(100,100,800,900); - aEditor.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE ); - aEditor.setVisible(true); - aEditor.repaint(); - aEditor.addWindowListener( new WindowAdapter(){ - public void windowClosed(WindowEvent e ){ - System.exit( 0 ); - } - }); - - aEditor.getMiExit().addActionListener( new ActionListener(){ - public void actionPerformed( ActionEvent e ){ - System.exit( 0 ); - } - }); - - aEditor.getMiSave().addActionListener( new ActionListener(){ - public void actionPerformed( ActionEvent e ){ - Iterator aIter = sdfstrings.iterator(); - String lastFile=""; - while( aIter.hasNext() ) - { - SdfString aSdfString = (SdfString )aIter.next(); - if( aSdfString.getFileId().compareTo( lastFile ) != 0 ){ - //aSdfString.removeFile(); - } - aSdfString.writeString(); - lastFile = aSdfString.getFileId(); - } - } - }); - - //aEditor.getRectable().putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); - aEditor.getRectable().addFocusListener( new FocusListener(){ - public void focusLost(FocusEvent e){ - //super.focusLost( e ); - //System.out.println("focus lost"); - JTable aTable = aEditor.getRectable(); - if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) - aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); - updateData(); - } - public void focusGained( FocusEvent e){ - //super.focusGained( e ); - //System.out.println("focus gained"); - } - }); - //setDefaultEditor(Object.class, new transex3.view.FocusCellEditor(new JTextField())); - - aEditor.getRectable().getModel().addTableModelListener( new TableModelListener() { - public void tableChanged( TableModelEvent e ){ - //System.out.println( e ); - }}); - - - aEditor.getRectable().getSelectionModel().addListSelectionListener( new ListSelectionListener(){ - public void valueChanged( ListSelectionEvent e ){ - JTable aTable = aEditor.getRectable(); - //if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) - //aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); - - updateData(); - } - }); - - aEditor.getTable().setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - aEditor.getTable().getSelectionModel().addListSelectionListener( new ListSelectionListener(){ - public void valueChanged( ListSelectionEvent e ){ - //System.out.println("Selected = " +e.getFirstIndex()+"\n"); - JTable table =transex3.controller.EditorController.aEditor.getTable(); - JTable recTable =transex3.controller.EditorController.aEditor.getRectable(); - SdfString aSdfString; - JTable aTable = aEditor.getRectable(); - if( aTable.getSelectedRow() != -1 && aTable.getSelectedColumn() != -1 ) - aTable.getCellEditor( aTable.getSelectedRow(), aTable.getSelectedColumn() ).stopCellEditing(); - - updateData(); - clearAllRows( recTable ); - - aSdfString = (SdfString) sdfstrings.get( table.getSelectedRow() ); - recTable.setValueAt( "en-US" , 0, 0 ); - recTable.setValueAt( aSdfString.getSourceString().getText() , 0, 1 ); - recTable.setValueAt( aSdfString.getSourceString().getHelptext() , 0, 2 ); - recTable.setValueAt( aSdfString.getSourceString().getQuickhelptext() , 0, 3 ); - recTable.setValueAt( aSdfString.getSourceString().getTitle() , 0, 4 ); - Vector values = aSdfString.getLanguageStrings(); - for( int n = 0; n < values.size() ; n++ ) - { - SdfEntity aEntity = (SdfEntity) values.get( n ); - recTable.setValueAt( aEntity.getLangid() , n+1 , 0 ); - recTable.setValueAt( aEntity.getText() , n+1 , 1 ); - recTable.setValueAt( aEntity.getHelptext() , n+1 , 2 ); - recTable.setValueAt( aEntity.getQuickhelptext() , n+1 , 3 ); - recTable.setValueAt( aEntity.getTitle() , n+1 , 4 ); - } - oldindex = table.getSelectedRow(); - } - }); - //System.out.println("initView successfully"); - } - public void initInitialStrings(){ - String rootdir = java.lang.System.getProperty("SOLARSRC"); - String sourcestringsfile = null; - Vector recList = new Vector(); - sourcestringsfile = fetchSourceStrings( rootdir ); - //findRecommandFiles( new File( rootdir ) , recList ); - readStrings( sourcestringsfile , recList ); - File sfile = new File ( sourcestringsfile ); - sfile.delete(); - initView(); - aEditor.repaint(); - } - // Connect recommand strings with source strings - public void readStrings( String sourcefiles , Vector recfiles ) { - BufferedReader aBR = null; - try { - //System.out.println("DBG: sourcefiles = " +sourcefiles); - aBR = new BufferedReader( new FileReader( sourcefiles ) ); - String current = aBR.readLine(); - SdfString aSdfString = null; - SdfEntity aSdfEntity = null; - while( current != null ){ - aSdfEntity = new SdfEntity(); - aSdfEntity.setProperties( current ); - aSdfString = new SdfString(); - aSdfString.addSourceString( aSdfEntity ); - hashedsdfstrings.put( aSdfString.getId() , aSdfString ); - //System.out.println("Put ID '"+aSdfString.getId()+"'"); - sdfstrings.add( aSdfString ); - current = aBR.readLine(); - - } - Iterator aIter=recfiles.iterator(); - File aFile; - BufferedReader aBR2 = null; - //System.out.println("Connecting strings"); - while( aIter.hasNext() ){ - aFile = (File) aIter.next(); - aBR2 = new BufferedReader( new FileReader( aFile ) ) ; - String current2 = aBR2.readLine(); - - while ( current2 != null ){ - SdfEntity aEntity = new SdfEntity(); - aEntity.setProperties( current2 ); - - if( hashedsdfstrings.containsKey( aEntity.getId() ) ) - { - aSdfString = (SdfString) hashedsdfstrings.get( aEntity.getId() ); - aSdfString.addLanguageString( aEntity ); - } - else - { - System.out.println("DBG: Can't find source string '"+aEntity.getId()+"'" ); - } - current2 = aBR2.readLine(); - } - } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch ( IOException e){ - e.printStackTrace(); - } - - } -} diff --git a/transex3/java/receditor/java/transex3/controller/Main.java b/transex3/java/receditor/java/transex3/controller/Main.java deleted file mode 100644 index e8dd06ce9f85..000000000000 --- a/transex3/java/receditor/java/transex3/controller/Main.java +++ /dev/null @@ -1,10 +0,0 @@ -package transex3.controller; - -public class Main { - - public static void main( String args[] ){ - EditorController aEditor = new EditorController(); - aEditor.initInitialStrings(); - } -} - diff --git a/transex3/java/receditor/java/transex3/model/ResourceFile.java b/transex3/java/receditor/java/transex3/model/ResourceFile.java deleted file mode 100644 index 51fabb3a4b7a..000000000000 --- a/transex3/java/receditor/java/transex3/model/ResourceFile.java +++ /dev/null @@ -1,77 +0,0 @@ -package transex3.model; - -import java.util.*; - -public class ResourceFile { - Vector sdfStrings = new Vector(); - HashMap sdfHashMap = new HashMap(); - String filepathid = null; - String modulename = null; - String filename = null; - - - public String getModuleName(){ - return modulename; - } - public String getFilePath(){ - return filepathid; - } - public String getFileName(){ - return filename; - } -/* public List readSoureStrings( java.io.File aSdfFile ){ - List sdfList=null; - return sdfList; - };*/ - public void addString( SdfString aSdfstring ){ - sdfStrings.add( aSdfstring ); - sdfHashMap.put( aSdfstring.getFileId() , aSdfstring ); - if( filepathid == null ) - filepathid = aSdfstring.getFilePath(); - if( modulename == null ) - modulename = aSdfstring.getModuleName(); - if( filename == null ) - filename = aSdfstring.getFileName(); - } - - - public void ParseString( String aSourceString ){ - //sourceString = new SdfEntity(); - SdfEntity aSdfEntity = new SdfEntity(); - aSdfEntity.setProperties( aSourceString ); - SdfString sdfstring = null; - if( sdfHashMap.containsKey( aSdfEntity.getFileId() ) ){ - sdfstring = (SdfString) sdfHashMap.get( aSdfEntity.getFileId() ); - } - else - { - sdfstring = new SdfString(); - addString( sdfstring ); - } - sdfstring.addLanguageString( aSdfEntity ); - - - } - /*public void ParseSdfFile( java.util.Vector aSdfList ){ - ListIterator aLI = aSdfList.listIterator(); - String current; - String[] splitted; - SdfEntity aSdfEntity; - SdfString aSdfString = new SdfString(); - while( aLI.hasNext() ){ - aSdfEntity = new SdfEntity(); - aSdfEntity.setProperties( (String) aLI.next() ); - SdfString aString; - - if( sdfHashMap.containsKey( aSdfEntity.getFileId() ) ) - aString = (SdfString) sdfHashMap.get( aSdfEntity.getFileId() ); - else - { - aString = new SdfString(); - addString( aString ); - } - aString.addLanguageString( aSdfEntity ); - } - - }*/ -} diff --git a/transex3/java/receditor/java/transex3/model/SdfEntity.java b/transex3/java/receditor/java/transex3/model/SdfEntity.java deleted file mode 100644 index 4b293421fd28..000000000000 --- a/transex3/java/receditor/java/transex3/model/SdfEntity.java +++ /dev/null @@ -1,211 +0,0 @@ -package transex3.model; - -public class SdfEntity { - private String project; - private String source_file; - private String dummy1; - private String resource_type; - private String gid; - private String lid; - private String helpid; - private String platform; - private String dummy2; - private String langid; - private String text; - private String helptext; - private String quickhelptext; - private String title; - private String date; - - public static int PROJECT_POS = 0; - public static int SOURCE_FILE_POS = 1; - public static int DUMMY1_POS = 2; - public static int RESOURCE_TYPE_POS = 3; - public static int GID_POS = 4; - public static int LID_POS = 5; - public static int HELPID_POS = 6; - public static int PLATFORM_POS = 7; - public static int DUMMY2_POS = 8; - public static int LANGID_POS = 9; - public static int TEXT_POS = 10; - public static int HELPTEXT_POS = 11; - public static int QUICKHELPTEXT_POS = 12; - public static int TITLE_POS = 13; - public static int DATE_POS = 14; - - public SdfEntity(){} - public SdfEntity(String project, String source_file, String dummy1, String resource_type, String gid, String lid, String helpid, String platform, String dummy2, String langid, String text, String helptext, String quickhelptext, String title , String date) { - super(); - this.project = project; - this.source_file = source_file; - this.dummy1 = dummy1; - this.resource_type = resource_type; - this.gid = gid; - this.lid = lid; - this.helpid = helpid; - this.platform = platform; - this.dummy2 = dummy2; - this.langid = langid; - this.text = text; - this.helptext = helptext; - this.quickhelptext = quickhelptext; - this.title = title; - this.date = date; - } - - public void setProperties( String line ){ - - String[] splitted = line.split("\t"); - - setProject( splitted[ SdfEntity.PROJECT_POS ] ); - setSource_file( splitted[ SdfEntity.SOURCE_FILE_POS ] ); - setDummy1( splitted[ SdfEntity.DUMMY1_POS ] ); - setResource_type( splitted[ SdfEntity.RESOURCE_TYPE_POS ] ); - setGid( splitted[ SdfEntity.GID_POS ] ); - setLid( splitted[ SdfEntity.LID_POS ] ); - setHelpid( splitted[ SdfEntity.HELPID_POS ] ); - setPlatform( splitted[ SdfEntity.PLATFORM_POS ] ); - setDummy2( splitted[ SdfEntity.DUMMY2_POS ] ); - setLangid( splitted[ SdfEntity.LANGID_POS ] ); - setText( splitted[ SdfEntity.TEXT_POS ] ); - setHelptext( splitted[ SdfEntity.HELPTEXT_POS ] ); - setQuickhelptext( splitted[ SdfEntity.QUICKHELPTEXT_POS ] ); - setTitle( splitted[ SdfEntity.TITLE_POS ] ); - setDate( splitted[ SdfEntity.DATE_POS ] ); - } - - public String getFileId(){ - return project+"\\"+source_file; - } - public String getResourcePath(){ - return source_file.substring(0 , source_file.lastIndexOf( "\\" )-1 ); - } - public String toString(){ - return project+"\t"+source_file+"\t"+dummy1+"\t"+resource_type+"\t"+gid+"\t" - +lid+"\t"+helpid+"\t"+platform+"\t"+dummy2+"\t"+langid+"\t" - +text+"\t"+helptext+"\t"+quickhelptext+"\t"+title+"\t"+date; - } - public String getId(){ - return project+gid+lid+source_file+resource_type+platform+helpid; - } - - public String getDummy1() { - return dummy1; - } - - public void setDummy1(String dummy1) { - this.dummy1 = dummy1; - } - - public String getPlatform() { - return platform; - } - - public void setPlatform(String platform) { - this.platform = platform; - } - - public String getDummy2() { - return dummy2; - } - - public void setDummy2(String dummy2) { - this.dummy2 = dummy2; - } - - public String getGid() { - return gid; - } - - public void setGid(String gid) { - this.gid = gid; - } - - public String getHelpid() { - return helpid; - } - - public void setHelpid(String helpid) { - this.helpid = helpid; - } - - public String getHelptext() { - return helptext; - } - - public void setHelptext(String helptext) { - this.helptext = helptext; - } - - public String getLangid() { - return langid; - } - - public void setLangid(String langid) { - this.langid = langid; - } - - public String getLid() { - return lid; - } - - public void setLid(String lid) { - this.lid = lid; - } - - public String getProject() { - return project; - } - - public void setProject(String project) { - this.project = project; - } - - public String getQuickhelptext() { - return quickhelptext; - } - - public void setQuickhelptext(String quickhelptext) { - this.quickhelptext = quickhelptext; - } - - public String getResource_type() { - return resource_type; - } - - public void setResource_type(String resource_type) { - this.resource_type = resource_type; - } - - public String getSource_file() { - return source_file; - } - - public void setSource_file(String source_file) { - this.source_file = source_file; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - public String getDate() { - return date; - } - public void setDate(String date) { - this.date = date; - } - - -} diff --git a/transex3/java/receditor/java/transex3/model/SdfString.java b/transex3/java/receditor/java/transex3/model/SdfString.java deleted file mode 100644 index 7419aeb5578b..000000000000 --- a/transex3/java/receditor/java/transex3/model/SdfString.java +++ /dev/null @@ -1,192 +0,0 @@ -package transex3.model; -import java.util.*; -import java.io.*; -public class SdfString { - private SdfEntity sourceString = null; - //private java.util.HashMap languageStrings = new HashMap(); - private Vector languageList = new Vector(); - private String id = null; - private String fileid = null; - private String filename = null; - private String modulename = null; - private String filepath = null; - - /*public HashMap getLanguageStrings() { - return languageStrings; - }*/ - public Vector getLanguageStrings() { - return languageList; - } - - public void setLanguageStrings(Vector languageStrings) { - this.languageList = languageStrings; - } - - public void addSourceString( SdfEntity aSdfEntity ) - { - if( id == null ) - id = aSdfEntity.getId(); - if ( fileid == null ) - fileid = aSdfEntity.getFileId(); - if( modulename == null ) - modulename = aSdfEntity.getProject(); - if( filename == null ) - filename = aSdfEntity.getSource_file(); - if( filepath == null ) - filepath = aSdfEntity.getResourcePath(); - setSourceString( aSdfEntity ); - } - public void addLanguageString( SdfEntity aSdfEntity ){ - if( !aSdfEntity.getLangid().equals( "en-US" ) ) - { - if( id == null ) - id = aSdfEntity.getId(); - if ( fileid == null ) - fileid = aSdfEntity.getFileId(); - if( modulename == null ) - modulename = aSdfEntity.getProject(); - if( filename == null ) - filename = aSdfEntity.getSource_file(); - if( filepath == null ) - filepath = aSdfEntity.getResourcePath(); - - //if( aSdfEntity.getLangid().equals( "en-US" ) ) - //{ - // setSourceString( aSdfEntity ); - //} - //else - //{ - //languageStrings.put( aSdfEntity.getLangid() , aSdfEntity ); - languageList.add( aSdfEntity ); - //} - id = aSdfEntity.getId(); - } - } - - public SdfEntity getSourceString() { - return sourceString; - } - - public void setSourceString(SdfEntity sourceString) { - this.sourceString = sourceString; - id = sourceString.getId(); - } - public String getFilePath(){ - return filepath; - } - public String getId(){ - //return id; - return sourceString.getId(); - } - public String getFileId(){ - return fileid; - } - - public String getFileName() { - return filename; - } - - public void setFileName(String filename) { - this.filename = filename; - } - - public String getModuleName() { - return modulename; - } - - public void setModuleName(String modulename) { - this.modulename = modulename; - } - /* - public String getRealFileName(){ - //String srcroot = "U:\\cws01\\l10ncleanup\\SRC680\\src.m213";//java.lang.System.getProperty( "SOLARSRC"); - //String isWindows = "4nt";//java.lang.System.getProperty( "USE_SHELL"); - String srcroot = java.lang.System.getProperty( "SOLARSRC" ); - String isWindows = java.lang.System.getProperty( "USE_SHELL" ); - - //System.out.println("srcroot="+srcroot+" isWindows="+isWindows ); - //if( true ) return; - //String relpath = sourceString.getFileId().substring( sourceString.getFileId().lastIndexOf("\\") - // , sourceString.getFileId().length() ); - String filename; - if( isWindows != null && isWindows.compareTo( "4nt") == 0 ) - { - filename = srcroot + "\\" + //sourceString.getProject() + "\\" + - sourceString.getFileId() +".recommand"; - } - else - { - String filepart = sourceString.getFileId(); - filepart = filepart.replaceAll( "\\\\" , "/" ); - filename = srcroot + "/" + //sourceString.getProject() + "//" + - filepart +".recommand"; - } - return filename; - }*/ - public String getRealFileName(){ - String filepart = sourceString.getFileId(); - filepart = filepart.replaceAll( "\\\\" , "_" ); - String filename = "/so/ws/merge/In/" + java.lang.System.getProperty( "WORK_STAMP" ) + "/" + filepart + ".sdf"; - return filename; - } - public void removeFile(){ - String filename = getRealFileName(); - File aFile = new File( filename ); - if( aFile.exists() ){ - if( ! aFile.delete() ) - { - System.out.println("Can't delete File "+filename+"\nWrong access rights?\n"); - } - } - } - public void writeString(){ - String filename = getRealFileName(); - try { - if( languageList.size() > 0 ) - { - System.out.print("\nWrite to "+filename ); - BufferedWriter aBW = new BufferedWriter( new FileWriter( filename , true) ); - aBW.write( sourceString + "\n" ); - Iterator aIter = languageList.iterator(); - while( aIter.hasNext() ){ - SdfEntity aEntity = (SdfEntity)aIter.next(); - aBW.write( sourceString.getProject()+"\t" ); - aBW.write( sourceString.getSource_file()+"\t" ); - aBW.write( sourceString.getDummy1()+"\t" ); - aBW.write( sourceString.getResource_type()+"\t" ); - aBW.write( sourceString.getGid()+"\t" ); - aBW.write( sourceString.getLid()+"\t" ); - aBW.write( sourceString.getHelpid()+"\t" ); - aBW.write( sourceString.getPlatform()+"\t" ); - aBW.write( sourceString.getDummy2()+"\t" ); - if( aEntity.getLangid() == null ) - aBW.write( "\t" ); - else - aBW.write( aEntity.getLangid()+"\t" ); - if( aEntity.getText() == null ) - aBW.write( "\t" ); - else - aBW.write( aEntity.getText()+"\t" ); - if( aEntity.getHelptext() == null ) - aBW.write( "\t" ); - else - aBW.write( aEntity.getHelptext()+"\t" ); - if( aEntity.getQuickhelptext() == null ) - aBW.write( "\t" ); - else - aBW.write( aEntity.getQuickhelptext()+"\t" ); - if( aEntity.getTitle() == null ) - aBW.write( "\t" ); - else - aBW.write( aEntity.getTitle()+"\t" ); - aBW.write( "2002-02-02 02:02:02\n" ); - } - aBW.close(); - } - } catch (IOException e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - System.out.println("\nERROR: Can't write to file '"+filename+"'\nPlease contact RE/Tooling!"); - } - } -} diff --git a/transex3/java/receditor/java/transex3/view/Editor.java b/transex3/java/receditor/java/transex3/view/Editor.java deleted file mode 100644 index f46a82a11a2b..000000000000 --- a/transex3/java/receditor/java/transex3/view/Editor.java +++ /dev/null @@ -1,97 +0,0 @@ -package transex3.view; -import javax.swing.*; -import java.awt.*; - -public class Editor extends JFrame{ - Object[] columnnames = { "File" , "GID" , "LID" , "String" }; - Object[] stringcolnames = { "Language", "Text", "Helptext" , "Quickhelptext","Title"}; - //Object[][] data = new Object[4][1];//{ { "a " }, { "v " }, { "v " } , { "a " } }; - JTable table = null; - JTable rectable = null; - JComboBox cBox = null; - JMenuBar menubar = null; - JMenu filemenu = null; - JMenuItem miNew = null; - JMenuItem miSave = null; - JMenuItem miExit = null; - //JButton button = null; - - public Editor( Object[][] tabledata , Object[][] firstdata ){ - table = new JTable( tabledata , columnnames ); - rectable = new SdfTable( firstdata , stringcolnames ); - menubar = new JMenuBar(); - filemenu = new JMenu("File"); - //miNew = new JMenuItem("New"); - miSave = new JMenuItem("Save"); - miExit = new JMenuItem("Exit"); - //button = new JButton("Edit"); - //filemenu.add( miNew ); - filemenu.add( miSave ); - filemenu.add( miExit ); - menubar.add( filemenu ); - - Container contentPane = getContentPane(); - //contentPane.add( new ControlPanel() , BorderLayout.NORTH ); - contentPane.add( menubar , BorderLayout.NORTH ); - //JPanel aPanel = new JPanel( new FlowLayout( FlowLayout.CENTER) ); - JPanel aPanel = new JPanel( new GridLayout( 2,1 ) ); - aPanel.add( new JScrollPane( table ) ); - aPanel.add( new JScrollPane( rectable ) ); - contentPane.add( aPanel , BorderLayout.CENTER ); - //contentPane.add( button , BorderLayout.SOUTH ); - //contentPane.add( new JScrollPane( table ), BorderLayout.CENTER ); - //contentPane.add( new JScrollPane( table ), BorderLayout.SOUTH ); - //contentPane.add( new JScrollPane( rectable ), BorderLayout.SOUTH ); - //contentPane.add( new JScrollPane( rectable ), BorderLayout.SOUTH ); - this.repaint(); - - } - - public JTable getRectable() { - return rectable; - } - - public void setRectable(JTable rectable) { - this.rectable = rectable; - } - - public JTable getTable() { - return table; - } - - public void setTable(JTable table) { - this.table = table; - } - - /*public JButton getButton() { - return button; - } - - public void setButton(JButton button) { - this.button = button; - }*/ - - public JMenuItem getMiExit() { - return miExit; - } - - public void setMiExit(JMenuItem miExit) { - this.miExit = miExit; - } - - public JMenuItem getMiSave() { - return miSave; - } - - public void setMiSave(JMenuItem miSave) { - this.miSave = miSave; - } - - /*public void setTableData(){ - - }*/ - -} - -//class ControlPanel extends JPanel{} - diff --git a/transex3/java/receditor/java/transex3/view/SdfTable.java b/transex3/java/receditor/java/transex3/view/SdfTable.java deleted file mode 100644 index f0cc7bd84a34..000000000000 --- a/transex3/java/receditor/java/transex3/view/SdfTable.java +++ /dev/null @@ -1,24 +0,0 @@ -package transex3.view; - -import javax.swing.JTable; - -class SdfTable extends JTable{ - //private String tableId; - public SdfTable( Object[][] obj1 , Object[] obj2){ - super(obj1,obj2); - } - //@Override - public boolean isCellEditable(int row, int col) { - if( row == 0 && col == 0 || row == 0 && col == 1 || row == 0 && col == 2 || row == 0 && col == 3 || row == 0 && col == 4 ) - return false; - else - return true; - } - /*public String getTableId() { - return tableId; - } - public void setTableId(String tableId) { - this.tableId = tableId; - }*/ - -} \ No newline at end of file diff --git a/transex3/java/receditor/makefile.mk b/transex3/java/receditor/makefile.mk deleted file mode 100755 index e5e3921eea6b..000000000000 --- a/transex3/java/receditor/makefile.mk +++ /dev/null @@ -1,39 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.3 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ=../.. -PRJNAME=transex3 -TARGET=receditor - -.INCLUDE : ant.mk - -ALLTAR : ANTBUILD - diff --git a/transex3/java/receditor/receditor.MF b/transex3/java/receditor/receditor.MF deleted file mode 100755 index dced97882df9..000000000000 --- a/transex3/java/receditor/receditor.MF +++ /dev/null @@ -1 +0,0 @@ -Main-Class: transex3.controller.Main diff --git a/transex3/layout/README b/transex3/layout/README deleted file mode 100644 index 1838e2a94ba0..000000000000 --- a/transex3/layout/README +++ /dev/null @@ -1,27 +0,0 @@ -Tralay - Extract and translate strings in Layout xml files. - -Translatable strings in layout xml files are attributes that have name -which starts with an underscore, eg - - _title="Set Zoom" - _label="Whole Page" - -Here is how it works - - * Extract: generate out.sdf - ../unxlngx6.pro/bin/tralay -l en-US zoom.xml > out.sdf - - * Translate: do: - cat out.sdf > trans.sdf - sed 's/en-US\t/de\tde:/' out.sdf >> trans.sdf - - * Merge: translate - ../unxlngx6.pro/bin/tralay -m trans.sdf -l de zoom.xml > zoom-DE.xml - -Running - - dmake test - -does something similar. - - \ No newline at end of file diff --git a/transex3/layout/layoutparse.cxx b/transex3/layout/layoutparse.cxx deleted file mode 100644 index 0f43c9a3053f..000000000000 --- a/transex3/layout/layoutparse.cxx +++ /dev/null @@ -1,139 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: layoutparse.cxx,v $ - * - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#include "layoutparse.hxx" - -#define STRING( str ) String( str, RTL_TEXTENCODING_UTF8 ) -#define BSTRING( str ) ByteString( str, RTL_TEXTENCODING_UTF8 ) - -LayoutXMLFile::LayoutXMLFile( bool mergeMode ) - : XMLFile() - , mMergeMode( mergeMode ) -{ -} - -void -LayoutXMLFile::SearchL10NElements( XMLParentNode* pCur, int ) -{ - if ( !pCur ) - pCur = this; - - /* Recurse int children, SearchL10NElements does not do that for us. */ - if ( XMLChildNodeList* lst = pCur->GetChildList() ) - for ( ULONG i = 0; i < lst->Count(); i++ ) - if ( lst->GetObject( i )->GetNodeType() == XML_NODE_TYPE_ELEMENT ) - HandleElement( ( XMLElement* )lst->GetObject( i ) ); - else if ( lst->GetObject( i )->GetNodeType() == XML_NODE_TYPE_COMMENT ) - lst->Remove( i-- ); -} - -std::vector -interestingAttributes( XMLAttributeList* lst ) -{ - std::vector interesting; - if ( lst ) - for ( ULONG i = 0; i < lst->Count(); i++ ) - if ( lst->GetObject( i )->Equals( STRING( "id" ) ) ) - interesting.insert( interesting.begin(), lst->GetObject( i ) ); - else if ( ! BSTRING( *lst->GetObject( i ) ).CompareTo( "_", 1 ) ) - interesting.push_back( lst->GetObject( i ) ); - return interesting; -} - -void -LayoutXMLFile::HandleElement( XMLElement* element ) -{ - std::vector interesting = interestingAttributes( element->GetAttributeList() ); - - if ( interesting.size() ) - { - std::vector::iterator i = interesting.begin(); - - ByteString id = BSTRING( (*i++)->GetValue() ); - - if ( mMergeMode ) - InsertL10NElement( id, element ); - else - for ( ; i != interesting.end(); ++i ) - { - ByteString attributeId = id; - ByteString value = BSTRING( ( *i )->GetValue() ); - XMLElement *e = new XMLElement( *element ); - e->RemoveAndDeleteAllChilds(); - /* Copy translatable text to CONTENT. */ - //new XMLData( STRING( ( *i )->GetValue() ), e, true ); - new XMLData( STRING( value ), e, true ); - attributeId += BSTRING ( **i ); - InsertL10NElement( attributeId, e ); - } - } - - SearchL10NElements( (XMLParentNode*) element ); -} - -void LayoutXMLFile::InsertL10NElement( ByteString const& id, XMLElement* element ) -{ - ByteString const language = "en-US"; - LangHashMap* languageMap = 0; - XMLHashMap::iterator pos = XMLStrings->find( id ); - if ( pos != XMLStrings->end() ) - { - languageMap = pos->second; - fprintf( stderr, "error:%s:duplicate translation found, id=%s\n", - id.GetBuffer(), BSTRING( sFileName ).GetBuffer() ); - exit( 1 ); - } - else - { - languageMap = new LangHashMap(); - XMLStrings->insert( XMLHashMap::value_type( id , languageMap ) ); - order.push_back( id ); - } - (*languageMap)[ language ] = element; -} - -BOOL LayoutXMLFile::Write( ByteString &aFilename ) -{ - - if ( aFilename.Len() ) - { - ofstream aFStream( aFilename.GetBuffer() , ios::out | ios::trunc ); - if ( !aFStream ) - fprintf( stderr, "ERROR: cannot open file:%s\n", aFilename.GetBuffer() ); - else - { - XMLFile::Write( aFStream ); - aFStream.close(); - return true; - } - } - return false; -} diff --git a/transex3/layout/layoutparse.hxx b/transex3/layout/layoutparse.hxx deleted file mode 100644 index b9cd8f6c18b2..000000000000 --- a/transex3/layout/layoutparse.hxx +++ /dev/null @@ -1,55 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: layoutparse.hxx,v $ - * - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef LAYOUTPARSE_HXX -#define LAYOUTPARSE_HXX - -#include "xmlparse.hxx" - -class LayoutXMLFile : public XMLFile -{ - bool mMergeMode; - -public: - LayoutXMLFile( bool mergeMode ); - - void SearchL10NElements( XMLParentNode *pCur, int pos = 0 ); - BOOL Write( ByteString &aFilename ); - void HandleElement( XMLElement* element ); - void InsertL10NElement( ByteString const& id, XMLElement* element ); - - using XMLFile::InsertL10NElement; - using XMLFile::Write; -}; - -std::vector interestingAttributes( XMLAttributeList* lst ); - -#endif /* LAYOUTPARSE_HXX */ diff --git a/transex3/layout/loc.sdf b/transex3/layout/loc.sdf deleted file mode 100644 index 023357adc420..000000000000 --- a/transex3/layout/loc.sdf +++ /dev/null @@ -1,24 +0,0 @@ -transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 en-US Zoom factor 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 en-US Whole Page 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_PAGE_WIDTH 0 en-US Page Width 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_OPTIMAL 0 en-US Optimal 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_200 0 en-US 200 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_150 0 en-US 15~0 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_100 0 en-US 100 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_75 0 en-US 75 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_50 0 en-US 50 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_USER 0 en-US Variable 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 de deZoom factor 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 de deWhole Page 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_PAGE_WIDTH 0 de dePage Width 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_OPTIMAL 0 de deOptimal 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_200 0 de de200 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_150 0 de de15~0 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_100 0 de de100 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_75 0 de de75 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_50 0 de de50 % 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_USER 0 de deVariable 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 en-US Zoom factor 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 en-US Whole Page 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help FL_ZOOM 0 de de3:Zoom factor 20080204 13:51:01 -transex3 layout\workben\zoom-1.xml 0 help BTN_WHOLE_PAGE 0 de de3:Whole Page 20080204 13:51:01 diff --git a/transex3/layout/makefile.mk b/transex3/layout/makefile.mk deleted file mode 100644 index 9864b46242b2..000000000000 --- a/transex3/layout/makefile.mk +++ /dev/null @@ -1,81 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.3 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ=.. - -INCPRE=$(MISC) - -PRJNAME=transex3 -TARGET=tralay -#TARGETTYPE=GUI -TARGETTYPE=CUI -LIBTARGET=no - -# --- Settings ----------------------------------------------------- - -ENABLE_EXCEPTIONS=TRUE - -.INCLUDE : settings.mk - -.IF "$(SYSTEM_EXPAT)" == "YES" -CFLAGS+=-DSYSTEM_EXPAT -.ENDIF - -# --- Files -------------------------------------------------------- - -APP1TARGET=$(TARGET) - -OBJFILES =\ - $(OBJ)/export2.obj\ - $(OBJ)/helpmerge.obj\ - $(OBJ)/layoutparse.obj\ - $(OBJ)/merge.obj\ - $(OBJ)/tralay.obj\ - $(OBJ)/xmlparse.obj - -APP1OBJS = $(OBJFILES) - -APP1STDLIBS =\ - $(TOOLSLIB)\ - $(EXPATASCII3RDLIB)\ - $(VOSLIB)\ - $(CPPULIB) \ - $(SALLIB) - -# --- Targets ------------------------------------------------------ - -.INCLUDE : target.mk - -test .PHONY: - ../$(INPATH)/bin/tralay -l en-US -o out.sdf zoom.xml - cat out.sdf > trans.sdf - sed 's/en-US\t/de\tde:/' out.sdf >> trans.sdf - ../$(INPATH)/bin/tralay -m trans.sdf -l de -o zoom-DE.xml zoom.xml diff --git a/transex3/layout/tralay.cxx b/transex3/layout/tralay.cxx deleted file mode 100644 index 740981674c50..000000000000 --- a/transex3/layout/tralay.cxx +++ /dev/null @@ -1,403 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: tralay.cxx,v $ - * - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#include -#include - -#include - -#include "export.hxx" -#include "layoutparse.hxx" -#include "helpmerge.hxx" -#include "xmlparse.hxx" - -// Convert a rtl::OUString to a byte string. -#define OUSTRING_CSTR( str ) \ - rtl::OUStringToOString( str, RTL_TEXTENCODING_UTF8 ).getStr() - -#define STRING( str ) String( str, RTL_TEXTENCODING_UTF8 ) -#define BSTRING( str ) ByteString( str, RTL_TEXTENCODING_UTF8 ) - -using ::rtl::OUString; - -using namespace ::osl; -using namespace ::com::sun::star; -using namespace ::com::sun::star::uno; - - -class TranslateLayout : public Application -{ - ByteString mGid1; - ByteString mLanguage; - ByteString mLocalize; - ByteString mOutput; - ByteString mProject; - ByteString mRoot; - bool mMergeMode; - std::vector< ByteString > mLanguages; - std::list< ByteString > mFiles; - -public: - TranslateLayout(); - virtual ~TranslateLayout(); - ByteString GetCommandLineParam( int i ); - ByteString GetOptionArgument( int const i ); - void ExceptionalMain(); - void Main(); - void Merge(); - void MergeLanguage( ByteString const& language ); - void ParseCommandLine(); - void CreateSDF(); - - using Application::GetCommandLineParam; -}; - -static void usage() -{ - fprintf( stderr, "Usage: tralay [OPTION]... XML-FILE\n" ); - fprintf( stderr, "\nOptions:\n" ); - fprintf( stderr, " -h,--help show this help\n" ); - fprintf( stderr, " -l,--language=LANG process this language\n" ); - fprintf( stderr, " -m,--merge=DATABASE.SDF translation database\n" ); - fprintf( stderr, "\nExamples:\n" ); - fprintf( stderr, " tralay -l en-US -o localize.sdf zoom.xml # Extract\n" ); - fprintf( stderr, " tralay -m localize.sdf -l de -l nl -o out zoom.xml # Merge/translate\n" ); - exit( 2 ); -} - -static ByteString ConvertSystemPath( const ByteString& rPath ) -{ - if( rPath.CompareTo( ".", 1 ) == 0 ) - { - OUString sPath( rPath.GetBuffer(), rPath.Len(), RTL_TEXTENCODING_UTF8 ); - - ::rtl::OUString curDirPth, sURL; - osl_getProcessWorkingDir( &curDirPth.pData ); - - ::osl::FileBase::getAbsoluteFileURL( curDirPth, sPath, sURL ); - ::osl::FileBase::getSystemPathFromFileURL( sURL, sPath ); - - return ByteString( rtl::OUStringToOString( sPath, RTL_TEXTENCODING_UTF8 ) ); - } - else - { - return rPath; - } -} - -ByteString TranslateLayout::GetCommandLineParam( int i ) -{ - return ByteString( OUSTRING_CSTR( Application::GetCommandLineParam( sal::static_int_cast< USHORT >( i ) ) ) ); -} - -ByteString TranslateLayout::GetOptionArgument( int const i ) -{ - if ( i >= GetCommandLineParamCount() ) - usage(); - ByteString arg = GetCommandLineParam( i ); - if ( !arg.CompareTo( "-", 1 ) ) - { - fprintf( stderr, "Option needs an argument: %s, found: %s\n", - GetCommandLineParam( i - 1 ).GetBuffer(), - arg.GetBuffer() ); - usage(); - } - return arg; - } - -void TranslateLayout::ParseCommandLine() -{ - for ( int i = 0; i < GetCommandLineParamCount(); i++ ) - { - ByteString aParam = GetCommandLineParam( i ); - if ( aParam.Equals( "-h" ) || aParam.Equals( "--help" ) ) - usage(); - else if ( aParam.Equals( "-l" ) || aParam.Equals( "--language" ) ) - mLanguages.push_back ( GetOptionArgument( ++i ) ); - else if ( aParam.Equals( "-m" ) || aParam.Equals( "--merge" ) ) - { - mMergeMode = true; - mLocalize = GetOptionArgument( ++i ); - } - else if ( aParam.Equals( "-o" ) || aParam.Equals( "--output" ) ) - mOutput = ConvertSystemPath( GetOptionArgument( ++i ) ); - else if ( !aParam.CompareTo( "-", 1 ) ) - { - fprintf( stderr, "error: No such option: %s\n", aParam.GetBuffer() ); - usage(); - } - else - mFiles.push_back( ConvertSystemPath( aParam ) ); - } - if ( !mFiles.size() ) - { - fprintf( stderr, "error: No XML-FILE found\n" ); - usage(); - } -} - -static XMLAttribute* -findAttribute( XMLAttributeList* lst, String const& name ) -{ - for ( ULONG i = 0; i < lst->Count(); i++ ) - if ( lst->GetObject( i )->Equals( name ) ) - return lst->GetObject( i ); - return 0; -} - -static XMLAttribute* -translateAttribute( XMLAttributeList* lst, - String const& name, String const& translation ) -{ - if ( XMLAttribute* a = findAttribute( lst, name ) ) - return lst->Replace ( new XMLAttribute( name.Copy( 1 ), translation ), a ); - return 0; -} - -static void -translateElement( XMLElement* element, ByteString const& lang, - ResData* resData, MergeDataFile& mergeData ) -{ - XMLAttributeList* attributes = element->GetAttributeList(); - std::vector interesting( interestingAttributes( attributes ) ); - - - if( !interesting.empty() ) - { - std::vector::iterator i( interesting.begin() ); - ByteString id = BSTRING( (*i++)->GetValue() ); - for ( ; i != interesting.end(); ++i ) - { - ByteString attributeId = id; - attributeId += BSTRING ( **i ); - resData->sGId = attributeId; - resData->sId = element->GetOldref(); - - if ( PFormEntrys* entry = mergeData.GetPFormEntrys( resData ) ) - { - ByteString translation; - entry->GetText( translation, STRING_TYP_TEXT, lang, true ); - // ByteString original = removeContent( element ); - if ( !translation.Len() ) -#if 0 - translation = original; -#else - translation = BSTRING( ( *i )->GetValue() ); -#endif - delete translateAttribute( attributes, **i , STRING( translation ) ); - } - } - } -} - -static bool is_dir( ByteString const& name ) -{ - DirectoryItem aItem; - OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 ); - FileBase::getFileURLFromSystemPath( sFileURL, sFileURL ); - if( DirectoryItem::get( sFileURL, aItem ) == FileBase::E_None ) - { - FileStatus aStatus(FileStatusMask_Type); - if( aItem.getFileStatus( aStatus ) == FileBase::E_None ) - { - if( aStatus.getFileType() == FileStatus::Directory ) - return true; - } - } - return false; -} - -static void make_directory( ByteString const& name ) -{ - OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 ); - FileBase::getFileURLFromSystemPath( sFileURL, sFileURL ); - Directory::create( sFileURL ); -} - -static void insertMarker( XMLParentNode *p, ByteString const& file ) -{ - if ( XMLChildNodeList* lst = p->GetChildList() ) - if ( lst->Count() ) - { - ULONG i = 1; - // Skip newline, if possible. - if ( lst->Count() > 1 - && lst->GetObject( 2 )->GetNodeType() == XML_NODE_TYPE_DEFAULT ) - i++; - OUString marker = OUString::createFromAscii( "\n NOTE: This file has been generated automagically by transex3/layout/tralay,\n from source template: " ) - + STRING( file ) - + OUString::createFromAscii( ".\n Do not edit, changes will be lost.\n" ); - lst->Insert( new XMLComment( marker, 0 ), i ); - } -} - -void TranslateLayout::MergeLanguage( ByteString const& language ) -{ - ByteString xmlFile = mFiles.front(); - - MergeDataFile mergeData( mLocalize, xmlFile, - FALSE, RTL_TEXTENCODING_MS_1252 ); - - DirEntry aFile( xmlFile ); - SimpleXMLParser aParser; - LayoutXMLFile* layoutXml = new LayoutXMLFile( mMergeMode ); - if ( !aParser.Execute( aFile.GetFull() , STRING( xmlFile ), layoutXml ) ) - { - fprintf(stderr, "error: parsing: %s\n", xmlFile.GetBuffer() ); - return; - } - - layoutXml->Extract(); - insertMarker( layoutXml, xmlFile ); - - ResData resData( "", "", "" ); - resData.sResTyp = mProject; /* mGid1 ?? */ - resData.sFilename = xmlFile; - - XMLHashMap* xmlStrings = layoutXml->GetStrings(); - for ( XMLHashMap::iterator i = xmlStrings->begin(); i != xmlStrings->end(); - ++i ) - { - if ( LangHashMap* languageMap = i->second ) - if ( XMLElement* element = ( *languageMap )[ "en-US" ] ) - translateElement( element, language, &resData, mergeData ); - } - -#ifndef WNT - ByteString outFile = "/dev/stdout"; -#else - ByteString outFile = "\\\\.\\CON"; -#endif - if ( mOutput.Len() ) - { - outFile = mOutput; - if ( is_dir( outFile ) ) - { - ByteString outDir = mOutput; - outDir.Append( "/" ).Append( language ); - if ( !is_dir( outDir ) ) - make_directory( outDir ); - outFile = outDir; - outFile.Append( "/" ).Append( xmlFile ); - } - } - layoutXml->Write( outFile ); - delete layoutXml; -} - -void TranslateLayout::Merge() -{ - if ( mLanguages.size() ) - for ( std::vector::iterator i = mLanguages.begin(); - i != mLanguages.end(); ++i) - MergeLanguage( *i ); - else - MergeLanguage( mLanguage ); -} - -void TranslateLayout::CreateSDF() -{ - ByteString xmlFile = mFiles.front(); -#ifndef WNT - ByteString sdf = "/dev/stdout"; -#else - ByteString sdf = "\\\\.\\CON"; -#endif - if ( mOutput.Len() ) - sdf = mOutput; - Export::SetLanguages( mLanguages ); - HelpParser::CreateSDF( sdf, mProject, mRoot, xmlFile, - new LayoutXMLFile( mMergeMode ), mGid1 ); -} - -void TranslateLayout::ExceptionalMain() -{ - ParseCommandLine(); - if ( mLanguages.size() ) - mLanguage = mLanguages.front(); - if ( mMergeMode ) - Merge(); - else - CreateSDF(); -} - -void TranslateLayout::Main() -{ - try - { - ExceptionalMain(); - } - catch ( xml::sax::SAXException& rExc ) - { - OString aStr( OUStringToOString( rExc.Message, - RTL_TEXTENCODING_ASCII_US ) ); - uno::Exception exc; - if (rExc.WrappedException >>= exc) - { - aStr += OString( " >>> " ); - aStr += OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US ); - } - fprintf( stderr, "error: parsing: '%s'\n", aStr.getStr() ); - OSL_ENSURE( 0, aStr.getStr() ); - } - catch ( uno::Exception& rExc ) - { - OString aStr( OUStringToOString( rExc.Message, - RTL_TEXTENCODING_ASCII_US ) ); - fprintf( stderr, "error: UNO: '%s'\n", aStr.getStr() ); - OSL_ENSURE( 0, aStr.getStr() ); - } -} - -TranslateLayout::TranslateLayout() - : Application() - , mGid1( "layout" ) - , mLanguage( "en-US" ) - , mLocalize( "localize.sdf" ) - , mOutput() - , mProject( "layout" ) - , mRoot() - , mMergeMode( false ) - , mLanguages() - , mFiles() -{ -} - -TranslateLayout::~TranslateLayout() -{ -} - -SAL_IMPLEMENT_MAIN() -{ - TranslateLayout t; - t.Main(); - return 0; -} diff --git a/transex3/layout/zoom.xml b/transex3/layout/zoom.xml deleted file mode 100644 index 0fb3d27343ff..000000000000 --- a/transex3/layout/zoom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/transex3/prj/build.lst b/transex3/prj/build.lst deleted file mode 100644 index 685686192daf..000000000000 --- a/transex3/prj/build.lst +++ /dev/null @@ -1,10 +0,0 @@ -tr transex3 : tools LIBXSLT:libxslt BERKELEYDB:berkeleydb LUCENE:lucene NULL -tr transex3 usr1 - all tr_mkout NULL -tr transex3\inc nmake - all tr_inc NULL -tr transex3\source nmake - all tr_src tr_inc NULL -tr transex3\layout nmake - all rt_layout tr_src tr_inc NULL -tr transex3\java\l10nconv nmake - all tr_conv NULL -tr transex3\java\receditor nmake - all tr_rece NULL -tr transex3\source\help nmake - all tr_bla_help NULL -tr transex3\source\filter\utils nmake - all tr_bla_utils NULL -tr transex3\source\filter\merge nmake - all tr_bla_merge tr_bla_utils NULL diff --git a/transex3/prj/d.lst b/transex3/prj/d.lst deleted file mode 100644 index a469837275ed..000000000000 --- a/transex3/prj/d.lst +++ /dev/null @@ -1,61 +0,0 @@ -mkdir: %_DEST%\inc%_EXT%\transex3 -mkdir: %_DEST%\bin%_EXT% -mkdir: %_DEST%\bin%_EXT%\help -mkdir: %_DEST%\bin%_EXT%\help\com -mkdir: %_DEST%\bin%_EXT%\help\com\sun -mkdir: %_DEST%\bin%_EXT%\help\com\sun\star -mkdir: %_DEST%\bin%_EXT%\help\com\sun\star\help - -..\%__SRC%\bin\cfgex.exe %_DEST%\bin%_EXT%\cfgex.exe -..\%__SRC%\bin\cfgex %_DEST%\bin%_EXT%\cfgex -..\%__SRC%\bin\transex3.exe %_DEST%\bin%_EXT%\transex3.exe -..\%__SRC%\bin\transex3 %_DEST%\bin%_EXT%\transex3 -..\%__SRC%\bin\lngex.exe %_DEST%\bin%_EXT%\lngex.exe -..\%__SRC%\bin\lngex %_DEST%\bin%_EXT%\lngex -..\%__SRC%\bin\localize_sl.exe %_DEST%\bin%_EXT%\localize_sl.exe -..\%__SRC%\bin\localize_sl %_DEST%\bin%_EXT%\localize_sl -..\%__SRC%\bin\xrmex.exe %_DEST%\bin%_EXT%\xrmex.exe -..\%__SRC%\bin\xrmex %_DEST%\bin%_EXT%\xrmex -..\%__SRC%\bin\gsicheck.exe %_DEST%\bin%_EXT%\gsicheck.exe -..\%__SRC%\bin\gsicheck %_DEST%\bin%_EXT%\gsicheck -..\%__SRC%\bin\helpex.exe %_DEST%\bin%_EXT%\helpex.exe -..\%__SRC%\bin\helpex %_DEST%\bin%_EXT%\helpex -..\%__SRC%\bin\ulfex.exe %_DEST%\bin%_EXT%\ulfex.exe -..\%__SRC%\bin\ulfex %_DEST%\bin%_EXT%\ulfex -..\%__SRC%\bin\txtconv.exe %_DEST%\bin%_EXT%\txtconv.exe -..\%__SRC%\bin\txtconv %_DEST%\bin%_EXT%\txtconv -..\%__SRC%\bin\tralay.exe %_DEST%\bin%_EXT%\tralay.exe -..\%__SRC%\bin\tralay %_DEST%\bin%_EXT%\tralay -..\%__SRC%\bin\ulfconv %_DEST%\bin%_EXT%\ulfconv -..\%__SRC%\class\FCFGMerge.jar %_DEST%\bin%_EXT%\FCFGMerge.jar -..\%__SRC%\class\HelpIndexerTool.jar %_DEST%\bin%_EXT%\HelpIndexerTool.jar -..\%__SRC%\bin\HelpLinker %_DEST%\bin%_EXT%\HelpLinker -..\%__SRC%\bin\HelpCompiler %_DEST%\bin%_EXT%\HelpCompiler -..\%__SRC%\bin\HelpCompiler.exe %_DEST%\bin%_EXT%\HelpCompiler.exe -..\%__SRC%\bin\HelpLinker.exe %_DEST%\bin%_EXT%\HelpLinker.exe -..\%__SRC%\bin\HelpLinker* %_DEST%\bin%_EXT% - -..\%__SRC%\class\converter\converter.jar %_DEST%\bin%_EXT%\converter.jar -..\%__SRC%\doc\converter_javadoc.zip %_DEST%\bin%_EXT%\converter_javadoc.zip - -..\%__SRC%\class\receditor\receditor.jar %_DEST%\bin%_EXT%\receditor.jar - -..\scripts\localize.pl %_DEST%\bin%_EXT%\localize.pl -..\scripts\localize_old.pl %_DEST%\bin%_EXT%\localize_old.pl -..\scripts\localize %_DEST%\bin%_EXT%\localize -..\scripts\fast_merge.pl %_DEST%\bin%_EXT%\fast_merge.pl -..\scripts\keyidGen.pl %_DEST%\bin%_EXT%\keyidGen.pl - -..\inc\export.hxx %_DEST%\inc%_EXT%\transex3\export.hxx -..\inc\transex3\directory.hxx %_DEST%\inc%_EXT%\transex3\directory.hxx -..\inc\transex3\file.hxx %_DEST%\inc%_EXT%\transex3\file.hxx -..\inc\transex3\vosapp.hxx %_DEST%\inc%_EXT%\transex3\vosapp.hxx - -..\inc\utf8conv.hxx %_DEST%\inc%_EXT%\transex3\utf8conv.hxx -..\%__SRC%\lib\transex.lib %_DEST%\lib%_EXT%\transex.lib -..\%__SRC%\lib\libtransex.a %_DEST%\lib%_EXT%\libtransex.a - -..\source\help\compilehelp.hxx %_DEST%\inc%_EXT%\transex3\compilehelp.hxx -#..\source\help\helplinkerdllapi.h %_DEST%\inc%_EXT%\transex3\helplinkerdllapi.h -..\%__SRC%\lib\* %_DEST%\lib%_EXT%\* -..\%__SRC%\class\com\sun\star\help\* %_DEST%\bin%_EXT%\help\com\sun\star\help\* diff --git a/transex3/scripts/fast_merge.pl b/transex3/scripts/fast_merge.pl deleted file mode 100644 index 7321a9a42911..000000000000 --- a/transex3/scripts/fast_merge.pl +++ /dev/null @@ -1,348 +0,0 @@ -: -eval 'exec perl -wS $0 ${1+"$@"}' - if 0; -#************************************************************************* -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: fast_merge.pl,v $ -# -# $Revision: 1.1.2.2 $ -# -# last change: $Author: ihi $ $Date: 2007/07/20 10:37:53 $ -# -# The Contents of this file are made available subject to -# the terms of GNU Lesser General Public License Version 2.1. -# -# -# GNU Lesser General Public License Version 2.1 -# ============================================= -# Copyright 2005 by Sun Microsystems, Inc. -# 901 San Antonio Road, Palo Alto, CA 94303, USA -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License version 2.1, as published by the Free Software Foundation. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, -# MA 02111-1307 USA -# -#************************************************************************* - -use strict; -use Class::Struct; -use Getopt::Long; -use File::Temp; -use File::Path; - -my @files; -my @file_names; -my $module_name = ''; -my @current; -my @buffer; -my $last_file; -my $last_path; -my $last_localize_file; -my $first_run = "1"; -my $sdf_filename; -my $merge_dir; -my $WIN; -my $state = "none"; - -if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { $WIN = 'TRUE'; } -else { $WIN = ''; } - -$SIG{INT} = 'inthandler'; -$SIG{QUIT} = 'quithandler'; - -struct ( sdf_obj => -{ - module => '$', - file => '$', - dir => '$', - FILEHANDLE => '$', - line => '$', - endoffile => '$' -} -); - -parse_options(); -my $lock_file = $merge_dir."/lock.mk"; -$lock_file =~ s/\//\\/g , if ( $WIN ) ; -acquire_lock(); -read_sdf_file_names(); -init(); -my $reference; -my $path ; -my $localize_file; -while( hasLines() ) -{ - @current = (); - foreach ( @files ) - { - push @current , $_; - } - - $reference = getNextIdentifier( ); - - @current = (); - foreach ( @files ) - { - if( $_->module eq $reference->module && $_->dir eq $reference->dir ) - { - push @current , $_ ; - } - } - write_lines(); -} -if( $#current+1 ne 0 ) -{ - ( $path , $localize_file ) = make_paths(); - add_to_buffer(); - write_buffer( $path , $localize_file ); -} -release_lock(); -exit( 0 ); - -########################################################################################## -sub acquire_lock -{ - if( -e $lock_file ){ - $state = "blocked"; - print "WARNING: Lock file '$lock_file' 'found, waiting ....\n"; - my $cnt = 0; - sleep 10 , while( -e $lock_file && $cnt++ < 180 ); - exit( 0 ); - }else - { - $state = "locked"; - print "Writing lock file '$lock_file'\n"; - open FILE, ">$lock_file" or die "Can't create lock file '$lock_file'"; - print FILE "L10N_LOCK=YES" ; - close ( FILE ); - } -} -sub release_lock -{ - print "Deleting lock file '$lock_file'\n"; - unlink $lock_file, if( -e $lock_file ); - $state = "none"; -} -sub inthandler -{ - release_lock() , if( $state eq "locked" ); - exit( -1 ); -} -sub quithandler -{ - release_lock() , if( $state eq "locked" ); - exit( 0 ); -} - -sub init -{ - foreach my $file ( @file_names ) - { - my $obj = new sdf_obj; - open my $FILEHANDLE , "<$file" or die "Can't open file '$file'"; - $obj->FILEHANDLE ( $FILEHANDLE ) ; - getNextSdfObj( $obj ); - push @files, $obj ; - print "Open file '$file'\n"; - } -} - -# get the next module/file -sub getNextIdentifier -{ - my @sorted = sort { - return $a->module.$a->dir cmp $b->module.$b->dir; - } @current ; - return shift @sorted; -} - -# update the obj with the next line -sub getNextSdfObj -{ - my $obj = shift; - my $line = readline ( $obj->FILEHANDLE ); - if ( $line eq undef ) - { - $obj->endoffile( "true" ); - } - else - { - $line =~ /^(([^\t]*)\t([^\t]*)[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t*)/o ; - if( defined $1 && defined $2 && defined $3 ) - { - $obj->line ( $1 ); - $obj->module( $2 ); - $obj->file ( $3 ); - $obj->dir ( getDir( $3 ) ); - } - else - { - $obj->line ( "" ); - $obj->module( "" ); - $obj->file ( "" ); - $obj->dir ( "" ); - } - } - return $obj; -} -sub getNextSdfObjModule -{ - my $obj = shift; - while( !$obj->endoffile ) - { - my $line = readline ( $obj->FILEHANDLE ); - if ( $line eq undef ) - { - $obj->endoffile( "true" ); - } - else - { - $line =~ /^(([^\t]*)\t([^\t]*).*)/o ; - if( defined $1 && defined $2 && defined $3 ) - { - $obj->line ( $1 ); - $obj->module( $2 ); - $obj->file ( $3 ); - $obj->dir ( getDir( $3 ) ); - } - else - { - $obj->line ( "" ); - $obj->module( "" ); - $obj->file ( "" ); - $obj->dir ( "" ); - } - return $obj , if( $obj->module eq $module_name ) - } - } - #return $obj; -} -sub getDir -{ - my $path = shift ; - $path =~ s/\//\\/g; - my @tmp_path = split /\\/ , $path; - pop @tmp_path; - $path = join '\\' , @tmp_path; - return $path; -} - -sub hasLines -{ - my $hasLines = ""; - my @tmpfiles; - foreach ( @files ) - { - push @tmpfiles , $_, if( !$_->endoffile ); - } - @files = @tmpfiles; - return $#files+1; -} - -sub make_paths -{ - my $localizeFile = $merge_dir."\\".$current[ 0 ]->module."\\".$current[ 0 ]->file; - my $path = getDir( $localizeFile ); - if ( !$WIN ) { $path =~ s/\\/\//g; } - - $localizeFile = $path."\\localize.sdf"; - if ( !$WIN ) { $localizeFile =~ s/\\/\//g; } - - return ( $path , $localizeFile ); -} -sub write_lines -{ - if( $first_run ){ - add_to_buffer(); - my( $path , $localize_file ) = make_paths(); - $last_path = $path; - $last_localize_file = $localize_file; - mkpath $path; - write_buffer( $path , $localize_file ); - $first_run = ''; - } - else - { - return , if ( $#current+1 eq 0 ); - my( $path , $localize_file ) = make_paths(); - if( $path eq $last_path ) - { - add_to_buffer(); - } - else - { - mkpath $path; - write_buffer( $last_path , $last_localize_file ); - add_to_buffer(); - $last_path = $path; - $last_localize_file = $localize_file; - } - } -} -sub add_to_buffer -{ - my $plainline; - my $afile; - my $amodule; - foreach my $elem ( @current ) - { - do { - $amodule=$elem->module; - $afile=$elem->file; - $plainline=$elem->line; - push @buffer, $plainline; - getNextSdfObj( $elem ); - } while ( !$elem->endoffile && $amodule eq $elem->module && $afile eq $elem->file ); - } -} -sub write_buffer -{ - my $path = shift; - my $localize_file = shift; - my $cnt = $#buffer+1; - print "Write to $path $cnt lines\n"; - open FILE , ">>$localize_file" or die "Can't open file '$localize_file'\n"; - foreach ( @buffer ) - { - print FILE $_."\n"; - } - @buffer = (); -} -sub parse_options -{ - my $success = GetOptions( 'sdf_files=s' => \$sdf_filename , 'merge_dir=s' => \$merge_dir ); #, 'module=s' => \$module_name ); - if( ! ( $sdf_filename && $merge_dir && $success ) ) - { - usage(); - exit( -1 ); - } -} - -sub usage -{ - print "Usage: fast_merge -sdf_files -merge_dir \n" ; -} - -sub read_sdf_file_names -{ - open FILE , "<$sdf_filename" or die "Can't open file '$sdf_filename'\n"; - while ( ) - { - push @file_names , split " " , $_ ; - } - close ( FILE ); -} - - diff --git a/transex3/scripts/keyidGen.pl b/transex3/scripts/keyidGen.pl deleted file mode 100644 index acb5137e3f7c..000000000000 --- a/transex3/scripts/keyidGen.pl +++ /dev/null @@ -1,189 +0,0 @@ -: -eval 'exec perl -S $0 ${1+"$@"}' - if 0; -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: keyidGen.pl,v $ -# -# $Revision: 1.3 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* -# -# add keyids to sdf file -# - -use Compress::Zlib(); - -print "\nkeyidGen version 1.0 \n\n"; - -my ( $infile,$outfile,$dbimport ); -get_options(); - -print_help() if ( !defined $infile || $help ); -exit 1 if ( !defined $infile ); -if ( ! defined $outfile ) -{ - $outfile = $infile; - $outfile =~ s/\.sdf$//i; - $outfile .= "_KeyID.sdf"; -} - -$collisions = 0; -%hashcodes = (); -$count = 0; -print "writing to $outfile\n"; -open INFILE,"<$infile" || die "could not open $infile $! $^E\n"; -open OUTFILE,">$outfile" || die "could not open $outfile $! $^E\n"; - -while ( ) -{ - $line = $_; - chomp $line; - $hash = 0; - if ( $line =~ /^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)$/ ) - { - $string="$1 $2 $4 $5 $6 $7 $8"; - $hashp = makeID( $string ); - - if ( defined ($hashcodes{ $hashp } ) ) - { - $collisions ++ unless $hashcodes{ $hashp } eq $string; - } - $hashcodes{ $hashp } = $string; - $count++; - if ( $dbimport ) - { - my ( $pre, $post, $old ); - $pre = "$1\t$2\t"; - $post = "\t$4\t$5\t$6\t$7\t$8\t$9\t$10\t$11\t$12\t$13\t$14\t$15\n"; - $old = $3; - $old =~ s/;{0,1}keyid:......;{0,1}//; - $old =~ s/^0$//; - if ( $old ne "" ) { $old .= ";"; } - print OUTFILE "$pre${old}keyid:$hashp$post"; - } - else - { - print OUTFILE "$1\t$2\t$3\t$4\t$5\t$6\t$7\t$8\t$9\t$10\t".makekidstr($hashp,$11)."\t".makekidstr($hashp,$12)."\t$13\t".makekidstr($hashp,$14)."\t$15\n"; - } - } -} -print "$count entries\n"; -print "$collisions collisions\n"; - -close INFILE; -close OUTFILE; - -sub makeID -{ - my ( $String ) = shift; - my ( $hash ); - # hardcoded to prevent windows installer to choke on bad directoryname :-(( - if ( $String eq "scp2 source\\ooo\\directory_ooo.ulf LngText STR_DIR_KAPITEL " ) - { - return "keyid1"; - } - - $hash = Compress::Zlib::crc32( $String, undef ); - return makenumber( $hash ); -} - -sub makenumber -{ - $h = shift; - # 1 2 3 4 - # 1234567890123456789012345678901234567890 - $symbols="0123456789abcdefghijklmnopqrstuvwxyz+-<=>"; - $order = length($symbols); - $result = ""; - while ( length( $result ) < 6 ) - { - $result .= substr( $symbols, ($h % $order), 1 ); - $h = int( $h / $order ); - } - die "makenumber failed because number is too big (this cannot be so this is a strange error)" if $h > 0; - - return reverse $result; -} - - -sub makekidstr -{ - $kid = shift; - $str = shift; - - if ( $str ne "" ) - { - # special handling for strings starting with font descriptions like {&Tahoma8} (win system integration) - if ( $str =~ s/^(\{\&[^\}]+\})// ) - { - return "$1$kid‖$str"; - } - else - { - return "$kid‖$str"; - } - } - else - { - return ""; - } -# return "default"; -} - -sub print_help -{ - print "\n\n"; - print "keyidGen 0.5 for sdf files\n"; - print "--------------------------\n"; - print "Usage:\n"; - print "keyidGen [] [-dbimport]\n"; - print " add keyids to the entries and write them to a file with\n"; - print " _KeyID added to the name\n"; - print " -dbimport Add KeyID to a new column instead of to the strings.\n"; - print " This is needed to import the IDs into tha database.\n"; - print "\n\n"; -} - - -sub get_options { - my ($arg,$has_infile); - - while ($arg = shift @ARGV) { - $arg =~ /^-dbimport$/ and $dbimport = 1 and next; - $arg =~ /^-help$/ and $help = 1 and next; #show help - - if ( !$has_infile ) - { - $infile = $arg; - $has_infile = 1; - } - else - { - $outfile = $arg; - } - } -} diff --git a/transex3/scripts/localize.pl b/transex3/scripts/localize.pl deleted file mode 100755 index 0f6a19effc38..000000000000 --- a/transex3/scripts/localize.pl +++ /dev/null @@ -1,1201 +0,0 @@ -: -eval 'exec perl -wS $0 ${1+"$@"}' - if 0; - - -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: localize.pl,v $ -# -# $Revision: 1.18.6.2 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -use strict; -use Getopt::Long; -use IO::Handle; -use File::Find; -use File::Temp; -use File::Path; -use File::Copy; -use File::Glob qw(:glob csh_glob); -use Cwd; - -my $CVS_BINARY = "/usr/bin/cvs"; -# ver 1.1 -# -#### module lookup -#use lib ("$ENV{SOLARENV}/bin/modules", "$ENV{COMMON_ENV_TOOLS}/modules"); - -#### module lookup -# OOo conform -my @lib_dirs; -BEGIN { - if ( !defined($ENV{SOLARENV}) ) { - die "No environment found (environment variable SOLARENV is undefined)"; - } - push(@lib_dirs, "$ENV{SOLARENV}/bin/modules"); - push(@lib_dirs, "$ENV{COMMON_ENV_TOOLS}/modules") if defined($ENV{COMMON_ENV_TOOLS}); -} -use lib (@lib_dirs); - -#### globals #### -my $sdffile = ''; -my $no_sort = ''; -my $create_dirs = ''; -my $multi_localize_files = ''; -my $module_to_merge = ''; -my $sort_sdf_before = ''; -my $outputfile = ''; -my $no_gsicheck = ''; -my $mode = ''; -my $bVerbose = "0"; -my $srcpath = ''; -my $WIN; -my $languages; -#my %sl_modules; # Contains all modules where en-US and de is source language -my $use_default_date = '0'; -my $force_ooo_module = '0'; -my %is_ooo_module; -my %is_so_module; -my $DELIMITER; - - # ( leftpart ) ( rightpart ) - # prj file dummy type gid lid helpid pform width lang text helptext qhelptext title timestamp -my $sdf_regex = "((([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*))\t([^\t]*)\t(([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t)([^\t]*))"; -my $file_types = "(src|hrc|xcs|xcu|lng|ulf|xrm|xhp|xcd|xgf|xxl|xrb)"; -# Always use this date to prevent cvs conflicts -my $default_date = "2002-02-02 02:02:02"; -my @sdfparticles; - -#### main #### -parse_options(); -check_modules_scm(); - -if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { - $WIN = 'TRUE'; - $DELIMITER = "\\"; -} - else { - $WIN = ''; - $DELIMITER = "/"; -} - -my $binpath = ''; -if( defined $ENV{UPDMINOREXT} ) -{ - $binpath = $ENV{SOLARVER}.$DELIMITER.$ENV{INPATH}.$DELIMITER."bin".$ENV{UPDMINOREXT}.$DELIMITER ; -} -else -{ - $binpath = $ENV{SOLARVER}.$DELIMITER.$ENV{INPATH}.$DELIMITER."bin".$DELIMITER ; -} - -#%sl_modules = fetch_sourcelanguage_dirlist(); - - -if ( $mode eq "merge" ) { - if ( ! $no_gsicheck ){ - merge_gsicheck(); - } - splitfile( $sdffile ); - if ( ! $no_gsicheck ){ - unlink $sdffile; # remove temp file! - } -} -elsif( $mode eq "extract" ) { - collectfiles( $outputfile ); -} -else { - usage(); -} - -exit(0); - -######################################################### -sub splitfile{ - - my $lastFile = ''; - my $currentFile = ''; - my $cur_sdffile = ''; - my $last_sdffile = ''; - my $delim; - my $badDelim; - my $start = 'TRUE'; - my %index = (); - my %block; - - STDOUT->autoflush( 1 ); - - #print STDOUT "Open File $sdffile\n"; - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - -# my %lang_hash; - my %string_hash_ooo; - my %string_hash_so; - my %so_modules; - $so_modules{ "extras_full" } = "TRUE"; - - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - next if( $prj eq "binfilter" ); # Don't merge strings into binfilter module - chomp( $line ); - - if( is_openoffice_module( $prj ) ) - { - $string_hash_ooo { $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line; - } - else - { - $string_hash_so{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line; - } - } - } - close( MYFILE ); - - if( !defined $ENV{SRC_ROOT} ){ - print "Error, no SRC_ROOT in env found.\n"; - exit( -1 ); - } - my $src_root = $ENV{SRC_ROOT}; - #print $WIN eq "TRUE" ? $src_root."\\l10n_so\n" : $src_root."/l10n_so\n"; - my $so_l10n_path = $WIN eq "TRUE" ? $src_root."\\l10n_so\\source" : $src_root."/l10n_so/source"; - my $ooo_l10n_path = $WIN eq "TRUE" ? $src_root."\\l10n\\source" : $src_root."/l10n/source"; - - #print "$so_l10n_path\n"; - #print "$ooo_l10n_path\n"; - - write_sdf( \%string_hash_so , $so_l10n_path ); - write_sdf( \%string_hash_ooo , $ooo_l10n_path ); - -} -sub check_modules_scm -{ - #my @ooo_modules; - #my @so_modules; - my $src_path = $ENV{ SRC_ROOT } ; - my $last_dir = getcwd(); - chdir $src_path ; - my @modules = <*/.svn/entries>; - - foreach my $module ( @modules ) - { - #print "$module \n"; - if( open ( FILE , "<$module" ) ) - { - while( ) - { - - my @path = split ( "/" , $module ) ; - - if( /svn.services.openoffice.org/ ) - { - my $mod = $path[ 0 ]; - #push @ooo_modules , $mod; - $is_ooo_module{ $mod } = "true"; - # print "$module -> ooo "; - } - elsif ( /jumbo2.germany.sun.com/ ) - { - my $mod = $path[ 0 ]; - #push @so_modules , $mod; - # print "$module -> so "; - #$so_lookup_hash{ $mod } = "true"; - } - #else - #{ - # print "ERROR: Is $module a SO or OOo module? Can not parese the $module/.svn/entries file ... please check mwsfinnish/merge/splitsdf.pl line 280\n"; - # exit -1; - #} - } - } - } - chdir $last_dir ; - #print "OOO\n"; - #print @ooo_modules; - #print "\nSO\n"; - #print @so_modules; -} - - -#sub parse -#{ -# my $command = "$CVS_BINARY -d:pserver:anoncvs\@anoncvs.services.openoffice.org:/cvs co -c"; -# my $output = `$command`; -# my $rc = $? << 8; -# if ( $output eq "" || $rc < 0 ){ -# print STDERR "ERROR: Can not fetch cvs alias list, please login to the cvs server and press at the password prompt just return\ncvs -d:pserver:anoncvs\@anoncvs.services.openoffice.org:/cvs login\n"; -# exit ( -1 ); -# } -# my @list = split /\n/ , $output ; -# foreach my $string( @list ) -# { -# -# # print "Found '$1'\n" , if( $string =~ /^(\w*)/ && $1 ne "" ); -# -# $is_ooo_module{ $1 } = "TRUE", if( $string =~ /^(\w*)/ && $1 ne "" ); -# } -# # foreach my $key( keys( %is_ooo_module ) ) -# #{ -# # print "$key\n"; -# #} -#} -sub is_openoffice_module -{ - my $module = shift; - return "TRUE", if ( $force_ooo_module || defined $is_ooo_module{ $module } ); - return ""; -} - -sub write_sdf -{ - my $string_hash = shift; - my $l10n_file = shift; - - foreach my $lang( keys( %{ $string_hash } ) ) - { - my @sdf_file; - - # mkdir!!!! - my $current_l10n_file = $WIN eq "TRUE" ? $l10n_file."\\$lang\\localize.sdf" : $l10n_file."/$lang/localize.sdf"; - print "Writing '$current_l10n_file'\n"; - if( open DESTFILE , "< $current_l10n_file" ){ - - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - if ( defined $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } ) - { - # Changed String! - push @sdf_file , $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } ; - $string_hash->{ $lang }{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = undef; - } - else - { - # No new string - push @sdf_file , $line; - } - } - } - } - close( DESTFILE ); - #Now just append the enw strings - #FIXME!!! Implement insertion in the correct order - foreach my $key ( keys ( %{ $string_hash->{ $lang } } ) ) - { - push @sdf_file , $string_hash->{ $lang }{ $key } , if ( defined $string_hash->{ $lang }{ $key } ); - #print "WARNING: Not defined = ".$string_hash->{ $lang }{ $key }."\n", if( ! defined $string_hash->{ $lang }{ $key } ); - } - - # Write the new file - my ( $TMPFILE , $tmpfile ) = File::Temp::tempfile(); - if( open DESTFILE , "+> $tmpfile " ){ - print DESTFILE get_license_header(); - foreach my $string( @sdf_file ){ - print DESTFILE "$string\n"; - } - close ( DESTFILE ); - if( move( $current_l10n_file , $current_l10n_file.".backup" ) ){ - if( copy( $tmpfile , $current_l10n_file ) ){ - unlink $l10n_file.".backup"; - } else { print STDERR "Can't open/create '$l10n_file', original file is renamed to $l10n_file.backup\n"; } - } else { print STDERR "Can't open/create '$l10n_file'\n"; } - }else{ - print STDERR "WARNING: Can't open/create '$l10n_file'\n"; - } - unlink $tmpfile; - } -} - -######################################################### - -sub get_license_header{ - return -"#\n". -"# #### ### # # ### ##### ##### #### ##### ##### \n". -"# # # # # ## # # # # # # # # # \n". -"# # # # # # # # # # # ### # # # # \n". -"# # # # # # ## # # # # # # # # \n". -"# #### ### # # ### # ##### #### ##### # \n". -"#\n". -"# DO NOT EDIT! This file will be overwritten by localisation process\n". -"#\n". -"#*************************************************************************\n". -"#\n". -"# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n". -"# \n". -"# Copyright 2008 by Sun Microsystems, Inc.\n". -"#\n". -"# OpenOffice.org - a multi-platform office productivity suite\n". -"#\n". -"# \$RCSfile:". -"localize.pl,v \$\n". -"#\n". -"# \$Revision: ". -"1.17.4.1 \$\n". -"#\n". -"# This file is part of OpenOffice.org.\n". -"#\n". -"# OpenOffice.org is free software: you can redistribute it and/or modify\n". -"# it under the terms of the GNU Lesser General Public License version 3\n". -"# only, as published by the Free Software Foundation.\n". -"#\n". -"# OpenOffice.org is distributed in the hope that it will be useful,\n". -"# but WITHOUT ANY WARRANTY; without even the implied warranty of\n". -"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n". -"# GNU Lesser General Public License version 3 for more details\n". -"# (a copy is included in the LICENSE file that accompanied this code).\n". -"#\n". -"# You should have received a copy of the GNU Lesser General Public License\n". -"# version 3 along with OpenOffice.org. If not, see\n". -"# \n". -"# for a copy of the LGPLv3 License.\n". -"#\n". -"#*************************************************************************\n"; -} -######## Check input sdf file and use only the correct part -sub merge_gsicheck{ - my $command = ''; - my ( $TMPHANDLE , $tmpfile ) = File::Temp::tempfile(); - close ( $TMPHANDLE ); - - if( $ENV{WRAPCMD} ){ - $command = "$ENV{WRAPCMD} gsicheck"; - }else{ - $command = "gsicheck"; - } - my $errfile = $sdffile.".err"; - $command .= " -k -c -wcf $tmpfile -wef $errfile -l \"\" $sdffile"; - #my $rc = system( $command ); - my $output = `$command`; - my $rc = $? << 8; - if ( $output ne "" ){ - print STDOUT "### gsicheck ###\n"; - print STDOUT "### The file $errfile have been written containing the errors in your sdf file. Those lines will not be merged: ###\n\n"; - print STDOUT "$output\n"; - print STDOUT "################\n"; - - }else{ - # Remove the 0 Byte file - unlink $errfile; - } - $sdffile = $tmpfile; -} -######################################################### -# find search function -sub wanted -{ - my $file = $File::Find::name; - if( -f $file && $file =~ /.*localize.sdf$/ && !( $file =~ /.*\.svn.*/ ) ) { - push @sdfparticles , $file; - if( $bVerbose eq "1" ) { print STDOUT "$file\n"; } - else { print "."; } - } -} - -sub add_paths -{ - my $langhash_ref = shift; - my $root_dir = $ENV{ SRC_ROOT }; - my $ooo_l10n_dir = "$root_dir"."$DELIMITER"."l10n"."$DELIMITER"."source"; - my $so_l10n_dir = "$root_dir"."$DELIMITER"."l10n_so"."$DELIMITER"."source"; - - if( -e $ooo_l10n_dir ) - { - foreach my $lang ( keys( %{ $langhash_ref } ) ) - { - my $loc_file = "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; - if( -e $loc_file ) - { - push @sdfparticles , "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; - } - else { print "WARNING: $loc_file not found ....\n"; } - } - } - else { die "ERROR: Can not find directory $ooo_l10n_dir!!!" } - if( -e $so_l10n_dir ) - { - foreach my $lang ( keys( %{ $langhash_ref } ) ) - { - my $loc_file = "$so_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; - if( -e $loc_file ) - { - push @sdfparticles , "$ooo_l10n_dir"."$DELIMITER"."$lang"."$DELIMITER"."localize.sdf"; - } - else { #print "WARNING: $loc_file not found ....\n"; - } - } - - } -} -sub collectfiles{ - print STDOUT "### Localize\n"; - my $localizehash_ref; - my ( $bAll , $bUseLocalize, $langhash_ref , $bHasSourceLanguage , $bFakeEnglish ) = parseLanguages(); - - # Enable autoflush on STDOUT - # $| = 1; - STDOUT->autoflush( 1 ); - - ### Search sdf particles - #print STDOUT "### Searching sdf particles\n"; - my $working_path = getcwd(); - #chdir $srcpath; - #find ( { wanted => \&wanted , follow => 1 }, getcwd() ); - #chdir $working_path; - add_paths( $langhash_ref ); - #my $nFound = $#sdfparticles +1; - #print "\n $nFound files found !\n"; - - my ( $LOCALIZEPARTICLE , $localizeSDF ) = File::Temp::tempfile(); - close( $LOCALIZEPARTICLE ); - - my ( $ALLPARTICLES_MERGED , $particleSDF_merged ) = File::Temp::tempfile(); - close( $ALLPARTICLES_MERGED ); - my ( $LOCALIZE_LOG , $my_localize_log ) = File::Temp::tempfile(); - close( $LOCALIZE_LOG ); - - ## Get the localize en-US extract - if( $bAll || $bUseLocalize ){ - print "### Fetching source language strings\n"; - my $command = ""; - my $args = ""; - - if( $ENV{WRAPCMD} ){ - $command = $ENV{WRAPCMD}.$binpath."localize_sl"; - }else{ - $command = $binpath."localize_sl"; - } - print $command; - # -e - # if ( -x $command ){ - if( $command ){ - if( !$bVerbose ){ $args .= " -QQ "; } - $args .= " -e -f $localizeSDF -l "; - my $bFlag=""; - if( $bAll ) {$args .= " en-US";} - else{ - my @list; - foreach my $isokey ( keys( %{ $langhash_ref } ) ){ - push @list , $isokey; - if( $langhash_ref->{ $isokey } ne "" ){ - push @list , $langhash_ref->{ $isokey }; - } - } - remove_duplicates( \@list ); - foreach my $isokey ( @list ){ - switch :{ - ( $isokey=~ /^en-US$/i ) - && do{ - if( $bFlag eq "TRUE" ){ $args .= ",en-US"; } - else { - $args .= "en-US"; $bFlag = "TRUE"; - } - }; - - } #switch - } #foreach - } # if - } # if -# if ( !$bVerbose ){ -# if ( $WIN eq "TRUE" ) { $args .= " > $my_localize_log"; } -# else { $args .= " >& $my_localize_log"; } -# } - if ( $bVerbose ) { print STDOUT $command.$args."\n"; } - - my $rc = system( $command.$args ); - - if( $rc < 0 ){ print STDERR "ERROR: localize rc = $rc\n"; exit( -1 ); } - ( $localizehash_ref ) = read_file( $localizeSDF , $langhash_ref ); - - } - ## Get sdf particles -#***************** - open ALLPARTICLES_MERGED , "+>> $particleSDF_merged" - or die "Can't open $particleSDF_merged"; - - ## Fill fackback hash - my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); - my %block; - my $cur_fallback; - if( !$bAll) { - foreach my $cur_lang ( keys( %{ $langhash_ref } ) ){ - #print STDOUT "DBG: G1 cur_lang=$cur_lang\n"; - $cur_fallback = $langhash_ref->{ $cur_lang }; - if( $cur_fallback ne "" ){ - # Insert fallback strings - #print STDOUT "DBG: Renaming $cur_fallback to $cur_lang in fallbackhash\n"; - rename_language( $fallbackhashhash_ref , $cur_fallback , $cur_lang ); - } - foreach my $currentfile ( @sdfparticles ){ - if ( open MYFILE , "< $currentfile" ) { - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - - if ( $lang eq $cur_lang ){ - # Overwrite fallback strings with collected strings - #if( ( !has_two_sourcelanguages( $cur_lang) && $cur_lang eq "de" ) || $cur_lang ne "en-US" ){ - $fallbackhashhash_ref->{ $cur_lang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - #} - - } - } - } - }else { print STDERR "WARNING: Can't open file $currentfile"; } - } - - foreach my $line ( keys( %{$fallbackhashhash_ref->{ $cur_lang } } )) { - if( #$cur_lang ne "de" && - $cur_lang ne "en-US" ){ - print ALLPARTICLES_MERGED ( $fallbackhashhash_ref->{ $cur_lang }{ $line }, "\n" ); - } - } - } - } else { - foreach my $currentfile ( @sdfparticles ){ - if ( open MYFILE , "< $currentfile" ) { - while( ){ - print ALLPARTICLES_MERGED ( $_, "\n" ); # recheck de / en-US ! - } - } - else { print STDERR "WARNING: Can't open file $currentfile"; } - } - } - close ALLPARTICLES_MERGED; -#*************** - - # Hash of array - my %output; - my @order; - - ## Join both - if( $outputfile ){ - if( open DESTFILE , "+> $outputfile" ){ - if( !open LOCALIZEPARTICLE , "< $localizeSDF" ) { print STDERR "ERROR: Can't open file $localizeSDF\n"; } - if( !open ALLPARTICLES_MERGED , "< $particleSDF_merged" ) { print STDERR "ERROR: Can't open file $particleSDF_merged\n"; } - - # Insert localize - my $extract_date=""; - while ( ){ - if( /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - my $timestamp = defined $18 ? $18 : ''; - - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - #my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - - if( $use_default_date ) - { - $extract_date = "$default_date\n" ; - } - elsif( $extract_date eq "" ) { - $extract_date = $timestamp ; - $extract_date =~ tr/\r\n//d; - $extract_date .= "\n"; - } - - if( $bAll ){ print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } - else { - foreach my $sLang ( keys( %{ $langhash_ref } ) ){ - if( $sLang=~ /all/i ) { - push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - } - #if( $sLang eq "de" && $lang eq "de" ) { - # push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - #} - if( $sLang eq "en-US" && $lang eq "en-US" ) { - push @order , $prj.$gid.$lid.$file.$type.$plattform.$helpid; - if( !$bFakeEnglish ){ push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - } - - } - } - } - } - # Insert particles - while ( ){ - if( /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $prj = defined $3 ? $3 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - my $timestamp = defined $18 ? $18 : ''; - - #my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - #my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - - if( $use_default_date ) - { - $extract_date = "$default_date\n" ; - } - elsif( $extract_date eq "" ) - { - $extract_date = $timestamp; - } - - if( ! ( $prj =~ /binfilter/i ) ) { - push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - } - } - } - - # Write! - foreach my $curkey ( @order ){ - foreach my $curlist ( $output{ $curkey } ){ - foreach my $line ( @{$curlist} ){ - print DESTFILE $line; - } - } - } - - }else { print STDERR "Can't open $outputfile";} - } - close DESTFILE; - close LOCALIZEPARTICLE; - close ALLPARTICLES_MERGED; - - #print STDOUT "DBG: \$localizeSDF $localizeSDF \$particleSDF_merged $particleSDF_merged\n"; - unlink $localizeSDF , $particleSDF_merged , $my_localize_log; - - #sort_outfile( $outputfile ); - #remove_obsolete( $outputfile ) , if $bHasSourceLanguage ne ""; - } - -######################################################### -sub remove_obsolete{ - my $outfile = shift; - my @lines; - my $enusleftpart; - my @good_lines; - - print STDOUT "### Removing obsolete strings\n"; - - # Kick out all strings without en-US reference - if ( open ( SORTEDFILE , "< $outfile" ) ){ - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $language = defined $12 ? $12 : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - my $leftpart = $prj.$gid.$lid.$file.$type.$plattform.$helpid; - - if( $language eq "en-US" ){ # source string found, 1. entry - $enusleftpart = $leftpart; - push @good_lines , $line; - }else{ - if( !defined $enusleftpart or !defined $leftpart ){ - print STDERR "BADLINE: $line\n"; - print STDERR "\$enusleftpart = $enusleftpart\n"; - print STDERR "\$leftpart = $leftpart\n"; - } - if( $enusleftpart eq $leftpart ){ # matching language - push @good_lines , $line; - } - #else{ - # print STDERR "OUT: \$enusleftpart=$enusleftpart \$leftpart=$leftpart \$line=$line\n"; - #} - } - } - } - close SORTEDFILE; - } else { print STDERR "ERROR: Can't open file $outfile\n";} - - # Write file - if ( open ( SORTEDFILE , "> $outfile" ) ){ - foreach my $newline ( @good_lines ) { - print SORTEDFILE $newline; - } - close SORTEDFILE; - } else { print STDERR "ERROR: Can't open file $outfile\n";} - -} -######################################################### -sub sort_outfile{ - my $outfile = shift; - print STDOUT "### Sorting ... $outfile ..."; - my @lines; - my @sorted_lines; - - - #if ( open ( SORTEDFILE , "< $outputfile" ) ){ - if ( open ( SORTEDFILE , "< $outfile" ) ){ - my $line; - while ( ){ - $line = $_; - if( $line =~ /^[^\#]/ ){ - push @lines , $line; - } - } - close SORTEDFILE; - @sorted_lines = sort { - my $xa_lang = ""; - my $xa_left_part = ""; - my $xa_right_part = ""; - my $xa_timestamp = ""; - my $xb_lang = ""; - my $xb_left_part = ""; - my $xb_right_part = ""; - my $xb_timestamp = ""; - my $xa = ""; - my $xb = ""; - my @alist; - my @blist; - - if( $a=~ /$sdf_regex/ ){ - $xa_left_part = defined $2 ? $2 : ''; - $xa_lang = defined $12 ? $12 : ''; - $xa_right_part = defined $13 ? $13 : ''; - $xa_left_part = remove_last_column( $xa_left_part ); - - } - if( $b=~ /$sdf_regex/ ){ - $xb_left_part = defined $2 ? $2 : ''; - $xb_lang = defined $12 ? $12 : ''; - $xb_right_part = defined $13 ? $13 : ''; - $xb_left_part = remove_last_column( $xb_left_part ); - - - } - if( ( $xa_left_part cmp $xb_left_part ) == 0 ){ # Left part equal - if( ( $xa_lang cmp $xb_lang ) == 0 ){ # Lang equal - return ( $xa_right_part cmp $xb_right_part ); # Right part compare - } - elsif( $xa_lang eq "en-US" ) { return -1; } # en-US wins - elsif( $xb_lang eq "en-US" ) { return 1; } # en-US wins - else { return $xa_lang cmp $xb_lang; } # lang compare - } - else { - return $xa_left_part cmp $xb_left_part; # Left part compare - } - } @lines; - - if ( open ( SORTEDFILE , "> $outfile" ) ){ - print SORTEDFILE get_license_header(); - foreach my $newline ( @sorted_lines ) { - print SORTEDFILE $newline; - #print STDOUT $newline; - } - } - close SORTEDFILE; - } else { print STDERR "WARNING: Can't open file $outfile\n";} - print "done\n"; - -} -######################################################### -sub remove_last_column{ - my $string = shift; - my @alist = split ( "\t" , $string ); - pop @alist; - return join( "\t" , @alist ); -} - -######################################################### -sub rename_language{ - my $fallbackhashhash_ref = shift; - my $cur_fallback = shift; - my $cur_lang = shift; - my $line; - - foreach my $key( keys ( %{ $fallbackhashhash_ref->{ $cur_fallback } } ) ){ - $line = $fallbackhashhash_ref->{ $cur_fallback }{ $key }; - if( $line =~ /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - - $fallbackhashhash_ref->{ $cur_lang }{ $key } = $leftpart."\t".$cur_lang."\t".$rightpart; - } - } -} - -############################################################ -sub remove_duplicates{ - my $list_ref = shift; - my %tmphash; - foreach my $key ( @{ $list_ref } ){ $tmphash{ $key } = '' ; } - @{$list_ref} = keys( %tmphash ); -} - -############################################################## -sub fetch_fallback{ - my $sdfparticleslist_ref = shift; - my $localizeSDF = shift; - my $langhash_ref = shift; - my %fallbackhashhash; - my $cur_lang; - my @langlist; - - foreach my $key ( keys ( %{ $langhash_ref } ) ){ - $cur_lang = $langhash_ref->{ $key }; - if ( $cur_lang ne "" ) { - push @langlist , $cur_lang; - } - } - remove_duplicates( \@langlist ); - foreach $cur_lang ( @langlist ){ - if( $cur_lang eq "en-US" ){ - read_fallbacks_from_source( $localizeSDF , $cur_lang , \%fallbackhashhash ); - } - } - - # remove de / en-US - my @tmplist; - foreach $cur_lang( @langlist ){ - if( $cur_lang ne "en-US" ){ - push @tmplist , $cur_lang; - - } - } - @langlist = @tmplist; - if ( $#langlist +1 ){ - read_fallbacks_from_particles( $sdfparticleslist_ref , \@langlist , \%fallbackhashhash ); - - } - return (\%fallbackhashhash); -} - -######################################################### -sub write_file{ - - my $localizeFile = shift; - my $index_ref = shift; - - if( open DESTFILE , "+> $localizeFile" ){ - foreach my $key( %{ $index_ref } ){ - print DESTFILE ($index_ref->{ $key }, "\n" ); - } - close DESTFILE; - }else { - print STDERR "Can't open/create '$localizeFile'"; - } -} - -######################################################### -sub read_file{ - - my $sdffile = shift; - my $langhash_ref = shift; - my %block = (); - - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $plattform = defined $10 ? $10 : ''; - my $lang = defined $12 ? $12 : ''; - my $helpid = defined $9 ? $9 : ''; - - foreach my $isolang ( keys ( %{ $langhash_ref } ) ){ - if( $isolang=~ /$lang/i || $isolang=~ /all/i ) { $block{$prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; } - } - } - } - return (\%block); -} - -######################################################### -sub read_fallbacks_from_particles{ - - my $sdfparticleslist_ref = shift; - my $isolanglist_ref = shift; - my $fallbackhashhash_ref = shift; - my $block_ref; - foreach my $currentfile ( @{ $sdfparticleslist_ref } ){ - if ( open MYFILE , "< $currentfile" ) { - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - - foreach my $isolang ( @{$isolanglist_ref} ){ - if( $isolang=~ /$lang/i ) { - $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - } - } - } - } - }else { print STDERR "WARNING: Can't open file $currentfile"; } - } -} - -######################################################### -sub read_fallbacks_from_source{ - - my $sdffile = shift; - my $isolang = shift; - my $fallbackhashhash_ref = shift; - my $block_ref; - # read fallback for single file - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $helpid = defined $9 ? $9 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - - chomp( $line ); - if( $isolang=~ /$lang/i ) { $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - } - } - } -} - -######################################################### -sub parseLanguages{ - - my $bAll; - my $bUseLocalize; - my $bHasSourceLanguage=""; - my $bFakeEnglish=""; - my %langhash; - my $iso=""; - my $fallback=""; - - #### -l all - if( $languages=~ /all/ ){ - $bAll = "TRUE"; - $bHasSourceLanguage = "TRUE"; - } - ### -l fr=de,de - elsif( $languages=~ /.*,.*/ ){ - my @tmpstr = split "," , $languages; - for my $lang ( @tmpstr ){ - if( $lang=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ - $iso = $1; - $fallback = $4; - - if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { - $bUseLocalize = "TRUE"; - } - if( ( $iso && $iso=~ /(en-US)/i ) ) { - $bHasSourceLanguage = "TRUE"; - } - if( $fallback ) { $langhash{ $iso } = $fallback; } - else { $langhash{ $iso } = ""; } - } - } - } - ### -l de - else{ - if( $languages=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ - $iso = $1; - $fallback = $4; - - if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { - $bUseLocalize = "TRUE"; - - } - if( ( $iso && $iso=~ /(en-US)/i ) ) { - $bHasSourceLanguage = "TRUE"; - } - - if( $fallback ) { $langhash{ $iso } = $fallback; } - else { $langhash{ $iso } = ""; } - } - } - # HACK en-US always needed! - if( !$bHasSourceLanguage ){ - #$bHasSourceLanguage = "TRUE"; - $bUseLocalize = "TRUE"; - $bFakeEnglish = "TRUE"; - $langhash{ "en-US" } = ""; - } - return ( $bAll , $bUseLocalize , \%langhash , $bHasSourceLanguage, $bFakeEnglish); -} - -######################################################### -sub parse_options{ - - my $help; - my $merge; - my $extract; - my $success = GetOptions('f=s' => \$sdffile , 'l=s' => \$languages , 's=s' => \$srcpath , 'h' => \$help , 'v' => \$bVerbose , - 'm' => \$merge , 'e' => \$extract , 'x' => \$no_sort , 'd' => \$use_default_date , 'c' => \$create_dirs , - 'n' => \$no_gsicheck , 'o' => \$force_ooo_module ); - $outputfile = $sdffile; - - #print STDOUT "DBG: lang = $languages\n"; - if( !$srcpath ){ - $srcpath = "$ENV{SRC_ROOT}"; - if( !$srcpath ){ - print STDERR "No path to the source root found!\n\n"; - usage(); - exit(1); - } - } - if( $help ){ - usage(); - exit(0); - } - if( !$success || $#ARGV > 1 || ( !$sdffile ) ){ - usage(); - exit(1); - } - if( $merge && $sdffile && ! ( -r $sdffile)){ - print STDERR "Can't open file '$sdffile'\n"; - exit(1); - } - if( !( $languages=~ /[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?(,[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?)*/ ) ){ - print STDERR "Please check the -l iso code\n"; - exit(1); - } - if( ( !$merge && !$extract ) || ( $merge && $extract ) ){ usage();exit( -1 );} - if( $extract ){ $mode = "extract"; } - else { $mode = "merge"; } -} -#my $multi_localize_files = ''; h -#my $module_to_merge = ''; i -#my $sort_sdf_before = ''; g - -######################################################### -sub usage{ - - print STDERR "Usage: localize.pl\n"; - print STDERR "Split or collect SDF files\n"; - print STDERR " merge: -m -f -l l1[=f1][,l2[=f2]][...] [ -s ] [ -c ]\n"; - print STDERR " extract: -e -f -l [ -s ] [-d]\n"; - print STDERR "Options:\n"; - print STDERR " -h help\n"; - print STDERR " -m Merge mode\n"; - print STDERR " -e Extract mode\n"; - print STDERR " -f To split a big SDF file into particles\n"; - print STDERR " To collect and join all particles to one big file\n"; - print STDERR " -s Path to the modules, if no \$SRC_ROOT is set\n"; - print STDERR " -l ( all | | =fallback ) comma seperated languages\n"; - print STDERR " -d Use default date in extracted sdf file\n"; - print STDERR " -c Create needed directories\n"; - print STDERR " -g Sort sdf file before mergeing\n"; - print STDERR " -h File with localize.sdf's\n!"; - print STDERR " -n No gsicheck\n"; - print STDERR " -i Module to merge\n"; - print STDERR " -o force using ooo localization from the l10n module instead of l10n_so; \n"; - print STDERR " useful if the type can't be detected by the .svn tags; \n"; - print STDERR " -v Verbose\n"; - print STDERR "\nExample:\n"; - print STDERR "\nlocalize -e -l en-US,pt-BR=en-US -f my.sdf\n( Extract en-US and pt-BR with en-US fallback )\n"; - print STDERR "\nlocalize -m -l cs -f my.sdf\n( Merge cs translation into the sourcecode ) \n"; -} - -# my $line = defined $_ ? $_ : ''; -# my $leftpart = defined $2 ? $2 : ''; -# my $prj = defined $3 ? $3 : ''; -# my $file = defined $4 ? $4 : ''; -# my $dummy = defined $5 ? $5 : ''; -# my $type = defined $6 ? $6 : ''; -# my $gid = defined $7 ? $7 : ''; -# my $lid = defined $8 ? $8 : ''; -# my $helpid = defined $9 ? $9 : ''; -# my $plattform = defined $10 ? $10 : ''; -# my $width = defined $11 ? $11 : ''; -# my $lang = defined $12 ? $12 : ''; -# my $rightpart = defined $13 ? $13 : ''; -# my $text = defined $14 ? $14 : ''; -# my $helptext = defined $15 ? $15 : ''; -# my $quickhelptext = defined $16 ? $16 : ''; -# my $title = defined $17 ? $17 : ''; -# my $timestamp = defined $18 ? $18 : ''; - diff --git a/transex3/scripts/localize_old.pl b/transex3/scripts/localize_old.pl deleted file mode 100755 index 151399d22002..000000000000 --- a/transex3/scripts/localize_old.pl +++ /dev/null @@ -1,1130 +0,0 @@ -: -eval 'exec perl -wS $0 ${1+"$@"}' - if 0; - - -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: localize.pl,v $ -# -# $Revision: 1.18 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -use strict; -use Getopt::Long; -use IO::Handle; -use File::Find; -use File::Temp; -use File::Copy; -use File::Glob qw(:glob csh_glob); -use Cwd; - -# ver 1.1 -# -#### module lookup -#use lib ("$ENV{SOLARENV}/bin/modules", "$ENV{COMMON_ENV_TOOLS}/modules"); - -#### module lookup -# OOo conform -my @lib_dirs; -BEGIN { - if ( !defined($ENV{SOLARENV}) ) { - die "No environment found (environment variable SOLARENV is undefined)"; - } - push(@lib_dirs, "$ENV{SOLARENV}/bin/modules"); - push(@lib_dirs, "$ENV{COMMON_ENV_TOOLS}/modules") if defined($ENV{COMMON_ENV_TOOLS}); -} -use lib (@lib_dirs); - -#### globals #### -my $sdffile = ''; -my $no_sort = ''; -my $outputfile = ''; -my $mode = ''; -my $bVerbose="0"; -my $srcpath = ''; -my $WIN; -my $languages; -#my %sl_modules; # Contains all modules where en-US and de is source language -my $use_default_date = '0'; - - # ( leftpart ) ( rightpart ) - # prj file dummy type gid lid helpid pform width lang text helptext qhelptext title timestamp -my $sdf_regex = "((([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*))\t([^\t]*)\t(([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t)([^\t]*))"; -my $file_types = "(src|hrc|xcs|xcu|lng|ulf|xrm|xhp|xcd|xgf|xxl|xrb)"; -# Always use this date to prevent cvs conflicts -my $default_date = "2002-02-02 02:02:02"; - -#### main #### -parse_options(); - -if ( defined $ENV{USE_SHELL} && $ENV{USE_SHELL} eq '4nt' ) { - $WIN = 'TRUE'; -} - else { - $WIN = ''; -} - -#%sl_modules = fetch_sourcelanguage_dirlist(); - - -if ( $mode eq "merge" ) { - merge_gsicheck(); - splitfile( $sdffile ); - unlink $sdffile; # remove temp file! -} -elsif( $mode eq "extract" ) { - collectfiles( $outputfile ); -} -else { - usage(); -} - -exit(0); - -######################################################### -sub splitfile{ - - my $lastFile = ''; - my $currentFile = ''; - my $cur_sdffile = ''; - my $last_sdffile = ''; - my $delim; - my $badDelim; - my $start = 'TRUE'; - my %index = (); - my %block; - - STDOUT->autoflush( 1 ); - - #print STDOUT "Open File $sdffile\n"; - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - next if( $prj eq "binfilter" ); # Don't merge strings into binfilter module - chomp( $line ); - $currentFile = $srcpath . '\\' . $prj . '\\' . $file; - if ( $WIN ) { $currentFile =~ s/\//\\/g; } - else { $currentFile =~ s/\\/\//g; } - - $cur_sdffile = $currentFile; - #if( $cur_sdffile =~ /\.$file_types[\s]*$/ ){ - if( $WIN ) { $cur_sdffile =~ s/\\[^\\]*\.$file_types[\s]*$/\\localize.sdf/; } - else { $cur_sdffile =~ s/\/[^\/]*\.$file_types[\s]*$/\/localize.sdf/; } - #} - - # Set default date - if( $line =~ /(.*)\t[^\t\$]*$/ ){ - $line = $1."\t".$default_date; - } - - if( $start ){ - $start=''; - $lastFile = $currentFile; # ? - $last_sdffile = $cur_sdffile; - } - - if( $lang eq "en-US" ){} - elsif( $cur_sdffile eq $last_sdffile ) - { - $block{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; - } - else - { - writesdf( $lastFile , \%block ); - $lastFile = $currentFile; #? - $last_sdffile = $cur_sdffile; - %block = (); - #if( ! $lang eq "en-US" ) { - $block{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; - #} - - } - } #else { print STDOUT "splitfile REGEX kaputt\n";} - - } - writesdf( $lastFile , \%block ); - %block = (); - close( MYFILE ); - -} -######################################################### - -#sub fetch_sourcelanguage_dirlist -#{ -# -# my $working_path = getcwd(); -# my %sl_dirlist; -# -# chdir $srcpath; -# my @all_dirs = csh_glob( "*" ); -# -# foreach my $file ( @all_dirs ) -# { -# if( -d $file ) -# { -# my $module = $file; -# $file .= "/prj/l10n"; -# $file =~ s/\//\\/ , if( $WIN ) ; -# -# if( -f $file ) # Test file /prj/l10n -# { -# $sl_dirlist{ $module } = 1; -# if( $bVerbose eq "1" ) { print STDOUT "$module: de and en-US source language detected\n"; } -# } -# } -# } -# -# chdir $working_path; -# -# return %sl_dirlist; -#} - -#sub has_two_sourcelanguages -#{ -# my $module = shift; -# return defined $sl_modules{ $module } ; -#} -sub writesdf{ - - my $lastFile = shift; - my $blockhash_ref = shift; - my $localizeFile = $lastFile; - my %index=(); - - if( $localizeFile =~ /\.$file_types[\s]*$/ ){ - if( $WIN ) { $localizeFile =~ s/\\[^\\]*\.$file_types[\s]*$/\\localize.sdf/; } - else { $localizeFile =~ s/\/[^\/]*\.$file_types[\s]*$/\/localize.sdf/; } - }else { - print STDERR "Strange filetype found '$localizeFile'\n"; - return; - } - if( open DESTFILE , "< $localizeFile" ){ - - #or die "Can't open/create '\$localizeFile'"; - - #### Build hash - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - $index{ "$prj\t$file\t$type\t$gid\t$lid\t$helpid\t$plattform\t$lang" } = $line ; - - } #else { print STDOUT "writesdf REGEX kaputt $_\n";} - - } - close( DESTFILE ); - } - #### Copy new strings - my @mykeys = keys( %{ $blockhash_ref } ); - my $isDirty = "FALSE"; - foreach my $key( @mykeys ){ - if( ! defined $index{ $key } ){ - # Add new entry - $index{ $key } = $blockhash_ref->{ $key} ; - $isDirty = "TRUE"; - }elsif( $index{ $key } ne $blockhash_ref->{ $key } ){ - # Overwrite old entry - $index{ $key } = $blockhash_ref->{ $key }; - $isDirty = "TRUE"; - }else { - } - } - - #### Write file - - if( !$bVerbose ){ print STDOUT "."; } - if( $isDirty eq "TRUE" ){ - if( $bVerbose ){ print STDOUT "$localizeFile\n"; } - if( open DESTFILE , "+> $localizeFile" ){ - print DESTFILE get_license_header(); - @mykeys = sort keys( %index ); - foreach my $key( @mykeys ){ - print DESTFILE ( $index{ $key } , "\n" ); - } - close DESTFILE; - }else { - print STDOUT "WARNING: File $localizeFile is not writable , try to merge ...\n"; - my ( $TMPFILE , $tmpfile ) = File::Temp::tempfile(); - if( open DESTFILE , "+> $tmpfile " ){ - @mykeys = keys( %index ); - foreach my $key( @mykeys ){ - print DESTFILE ( $index{ $key } , "\n" ); - } - close DESTFILE; - if( move( $localizeFile , $localizeFile.".backup" ) ){ - if( copy( $tmpfile , $localizeFile ) ){ - unlink $localizeFile.".backup"; - } else { print STDERR "Can't open/create '$localizeFile', original file is renamed to $localizeFile.backup\n"; } - } else { print STDERR "Can't open/create '$localizeFile'\n"; } - }else{ - print STDERR "WARNING: Can't open/create '$localizeFile'\n"; - } - unlink $tmpfile; - } - } -# if( $no_sort eq '' ){ -# sort_outfile( $localizeFile ); -# } -} - -sub get_license_header{ - return -"#\n". -"# #### ### # # ### ##### ##### #### ##### ##### \n". -"# # # # # ## # # # # # # # # # \n". -"# # # # # # # # # # # ### # # # # \n". -"# # # # # # ## # # # # # # # # \n". -"# #### ### # # ### # ##### #### ##### # \n". -"#\n". -"# DO NOT EDIT! This file will be overwritten by localisation process\n". -"#\n". -"#*************************************************************************\n". -"#\n". -"# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n". -"# \n". -"# Copyright 2008 by Sun Microsystems, Inc.\n". -"#\n". -"# OpenOffice.org - a multi-platform office productivity suite\n". -"#\n". -"# \$RCSfile:". -"localize.pl,v \$\n". -"#\n". -"# \$Revision: ". -"1.17.4.1 \$\n". -"#\n". -"# This file is part of OpenOffice.org.\n". -"#\n". -"# OpenOffice.org is free software: you can redistribute it and/or modify\n". -"# it under the terms of the GNU Lesser General Public License version 3\n". -"# only, as published by the Free Software Foundation.\n". -"#\n". -"# OpenOffice.org is distributed in the hope that it will be useful,\n". -"# but WITHOUT ANY WARRANTY; without even the implied warranty of\n". -"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n". -"# GNU Lesser General Public License version 3 for more details\n". -"# (a copy is included in the LICENSE file that accompanied this code).\n". -"#\n". -"# You should have received a copy of the GNU Lesser General Public License\n". -"# version 3 along with OpenOffice.org. If not, see\n". -"# \n". -"# for a copy of the LGPLv3 License.\n". -"#\n". -"#*************************************************************************\n"; -} -######## Check input sdf file and use only the correct part -sub merge_gsicheck{ - my $command = ''; - my ( $TMPHANDLE , $tmpfile ) = File::Temp::tempfile(); - my ( $TMPHANDLE2 , $tmpfile2 ) = File::Temp::tempfile(); - close ( $TMPHANDLE ); - close ( $TMPHANDLE2 ); - - unlink $tmpfile2; - my $output2 = `cat $sdffile | sort > $tmpfile2`; - my $rc2 = $? << 8; - if( $rc2 ne 0 ){ - printf("ERROR: Failed -> cat $sdffile | sort > $tmpfile2\n$output2\n"); - exit( -1 ); - } - -# if( $ENV{WRAPCMD} ){ -# $command = "$ENV{WRAPCMD} gsicheck"; -# }else{ -# $command = "gsicheck"; -# } -# my $errfile = $tmpfile.".err"; -# $command .= " -k -c -wcf $tmpfile -wef $errfile -l \"\" $tmpfile2"; -# my $output = `$command`; -# my $rc = $? << 8; -# if ( $output ne "" ){ -# print STDOUT "### gsicheck ###\n"; -# print STDOUT "### The file $errfile have been written containing the errors in your sdf file. Those lines will not be merged: ###\n\n"; -# print STDOUT "$output\n"; -# print STDOUT "################\n"; -# -# }else{ -# # Remove the 0 Byte file -# unlink $errfile; -# } - $sdffile = $tmpfile2; -# unlink $tmpfile2; -} -######################################################### -sub collectfiles{ - print STDOUT "### Localize\n"; - my @sdfparticles; - my $localizehash_ref; - my ( $bAll , $bUseLocalize, $langhash_ref , $bHasSourceLanguage , $bFakeEnglish ) = parseLanguages(); - - # Enable autoflush on STDOUT - # $| = 1; - STDOUT->autoflush( 1 ); - - ### Search sdf particles - print STDOUT "### Searching sdf particles\n"; - my $working_path = getcwd(); - chdir $srcpath; - find sub { - my $file = $File::Find::name; - if( -f && $file =~ /.*localize.sdf$/ ) { - push @sdfparticles , $file; - if( $bVerbose eq "1" ) { print STDOUT "$file\n"; } - else { print "."; } - - } - } , getcwd() ;#"."; #$srcpath; - chdir $working_path; - - my $nFound = $#sdfparticles +1; - print "\n $nFound files found !\n"; - - my ( $LOCALIZEPARTICLE , $localizeSDF ) = File::Temp::tempfile(); - close( $LOCALIZEPARTICLE ); - - my ( $ALLPARTICLES_MERGED , $particleSDF_merged ) = File::Temp::tempfile(); - close( $ALLPARTICLES_MERGED ); - my ( $LOCALIZE_LOG , $my_localize_log ) = File::Temp::tempfile(); - close( $LOCALIZE_LOG ); - - ## Get the localize de,en-US extract - if( $bAll || $bUseLocalize ){ - print "### Fetching source language strings\n"; - my $command = ""; - my $args = ""; - - if( $ENV{WRAPCMD} ){ - $command = "$ENV{WRAPCMD} localize_sl"; - }else{ - $command = "localize_sl"; - } - - # -e - # if ( -x $command ){ - if( $command ){ - if( !$bVerbose ){ $args .= " -QQ -skip_links "; } - $args .= " -e -f $localizeSDF -l "; - my $bFlag=""; - if( $bAll ) {$args .= " en-US";} - else{ - my @list; - foreach my $isokey ( keys( %{ $langhash_ref } ) ){ - push @list , $isokey; - if( $langhash_ref->{ $isokey } ne "" ){ - push @list , $langhash_ref->{ $isokey }; - } - } - remove_duplicates( \@list ); - foreach my $isokey ( @list ){ - switch :{ - #( $isokey=~ /^de$/i ) - # && do{ - # if( $bFlag eq "TRUE" ){ $args .= ",de"; } - # else { - # $args .= "de"; $bFlag = "TRUE"; - # } - # }; - ( $isokey=~ /^en-US$/i ) - && do{ - if( $bFlag eq "TRUE" ){ $args .= ",en-US"; } - else { - $args .= "en-US"; $bFlag = "TRUE"; - } - }; - - } #switch - } #foreach - } # if - } # if -# if ( !$bVerbose ){ -# if ( $WIN eq "TRUE" ) { $args .= " > $my_localize_log"; } -# else { $args .= " >& $my_localize_log"; } -# } - if ( $bVerbose ) { print STDOUT $command.$args."\n"; } - - my $rc = system( $command.$args ); - - #my $output = `$command.$args`; - #my $rc = $? << 8; - - if( $rc < 0 ){ print STDERR "ERROR: localize rc = $rc\n"; exit( -1 ); } - ( $localizehash_ref ) = read_file( $localizeSDF , $langhash_ref ); - - } - ## Get sdf particles - open ALLPARTICLES_MERGED , "+>> $particleSDF_merged" - or die "Can't open $particleSDF_merged"; - - ## Fill fackback hash - my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); -# my( $fallbackhashhash_ref ) = fetch_fallback( \@sdfparticles , $localizeSDF , $langhash_ref ); - my %block; - my $cur_fallback; - if( !$bAll) { - foreach my $cur_lang ( keys( %{ $langhash_ref } ) ){ - #print STDOUT "DBG: G1 cur_lang=$cur_lang\n"; - $cur_fallback = $langhash_ref->{ $cur_lang }; - if( $cur_fallback ne "" ){ - # Insert fallback strings - #print STDOUT "DBG: Renaming $cur_fallback to $cur_lang in fallbackhash\n"; - rename_language( $fallbackhashhash_ref , $cur_fallback , $cur_lang ); - } - foreach my $currentfile ( @sdfparticles ){ - if ( open MYFILE , "< $currentfile" ) { - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - - if ( $lang eq $cur_lang ){ - # Overwrite fallback strings with collected strings - #if( ( !has_two_sourcelanguages( $cur_lang) && $cur_lang eq "de" ) || $cur_lang ne "en-US" ){ - $fallbackhashhash_ref->{ $cur_lang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - #} - - } - } - } - }else { print STDERR "WARNING: Can't open file $currentfile"; } - } - - foreach my $line ( keys( %{$fallbackhashhash_ref->{ $cur_lang } } )) { - if( #$cur_lang ne "de" && - $cur_lang ne "en-US" ){ - print ALLPARTICLES_MERGED ( $fallbackhashhash_ref->{ $cur_lang }{ $line }, "\n" ); - } - } - } - } else { - foreach my $currentfile ( @sdfparticles ){ - if ( open MYFILE , "< $currentfile" ) { - while( ){ - print ALLPARTICLES_MERGED ( $_, "\n" ); # recheck de / en-US ! - } - } - else { print STDERR "WARNING: Can't open file $currentfile"; } - } - } - close ALLPARTICLES_MERGED; - - - # Hash of array - my %output; - my @order; - - ## Join both - if( $outputfile ){ - if( open DESTFILE , "+> $outputfile" ){ - if( !open LOCALIZEPARTICLE , "< $localizeSDF" ) { print STDERR "ERROR: Can't open file $localizeSDF\n"; } - if( !open ALLPARTICLES_MERGED , "< $particleSDF_merged" ) { print STDERR "ERROR: Can't open file $particleSDF_merged\n"; } - - # Insert localize - my $extract_date=""; - while ( ){ - if( /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - my $timestamp = defined $18 ? $18 : ''; - - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - #my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - - if( $use_default_date ) - { - $extract_date = "$default_date\n" ; - } - elsif( $extract_date eq "" ) { - $extract_date = $timestamp ; - $extract_date =~ tr/\r\n//d; - $extract_date .= "\n"; - } - - if( $bAll ){ print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } - else { - foreach my $sLang ( keys( %{ $langhash_ref } ) ){ - if( $sLang=~ /all/i ) { - push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - } - #if( $sLang eq "de" && $lang eq "de" ) { - # push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - #} - if( $sLang eq "en-US" && $lang eq "en-US" ) { - push @order , $prj.$gid.$lid.$file.$type.$plattform.$helpid; - if( !$bFakeEnglish ){ push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; } - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date; - } - - } - } - } - } - # Insert particles - while ( ){ - if( /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $prj = defined $3 ? $3 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - my $timestamp = defined $18 ? $18 : ''; - - #my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - #my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - - if( $use_default_date ) - { - $extract_date = "$default_date\n" ; - } - elsif( $extract_date eq "" ) - { - $extract_date = $timestamp; - } - - if( ! ( $prj =~ /binfilter/i ) ) { - push @{ $output{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } } , $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - #print DESTFILE $leftpart."\t".$lang."\t".$rightpart.$extract_date ; - } - } - } - - # Write! - foreach my $curkey ( @order ){ - foreach my $curlist ( $output{ $curkey } ){ - foreach my $line ( @{$curlist} ){ - print DESTFILE $line; - } - } - } - - }else { print STDERR "Can't open $outputfile";} - } - close DESTFILE; - close LOCALIZEPARTICLE; - close ALLPARTICLES_MERGED; - - #print STDOUT "DBG: \$localizeSDF $localizeSDF \$particleSDF_merged $particleSDF_merged\n"; - unlink $localizeSDF , $particleSDF_merged , $my_localize_log; - - #sort_outfile( $outputfile ); - #remove_obsolete( $outputfile ) , if $bHasSourceLanguage ne ""; - } - -######################################################### -sub remove_obsolete{ - my $outfile = shift; - my @lines; - my $enusleftpart; - my @good_lines; - - print STDOUT "### Removing obsolete strings\n"; - - # Kick out all strings without en-US reference - if ( open ( SORTEDFILE , "< $outfile" ) ){ - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $language = defined $12 ? $12 : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - my $leftpart = $prj.$gid.$lid.$file.$type.$plattform.$helpid; - - if( $language eq "en-US" ){ # source string found, 1. entry - $enusleftpart = $leftpart; - push @good_lines , $line; - }else{ - if( !defined $enusleftpart or !defined $leftpart ){ - print STDERR "BADLINE: $line\n"; - print STDERR "\$enusleftpart = $enusleftpart\n"; - print STDERR "\$leftpart = $leftpart\n"; - } - if( $enusleftpart eq $leftpart ){ # matching language - push @good_lines , $line; - } - #else{ - # print STDERR "OUT: \$enusleftpart=$enusleftpart \$leftpart=$leftpart \$line=$line\n"; - #} - } - } - } - close SORTEDFILE; - } else { print STDERR "ERROR: Can't open file $outfile\n";} - - # Write file - if ( open ( SORTEDFILE , "> $outfile" ) ){ - foreach my $newline ( @good_lines ) { - print SORTEDFILE $newline; - } - close SORTEDFILE; - } else { print STDERR "ERROR: Can't open file $outfile\n";} - -} -######################################################### -sub sort_outfile{ - my $outfile = shift; - print STDOUT "### Sorting ... $outfile ..."; - my @lines; - my @sorted_lines; - - - #if ( open ( SORTEDFILE , "< $outputfile" ) ){ - if ( open ( SORTEDFILE , "< $outfile" ) ){ - my $line; - while ( ){ - $line = $_; - if( $line =~ /^[^\#]/ ){ - push @lines , $line; - } - } - close SORTEDFILE; - @sorted_lines = sort { - my $xa_lang = ""; - my $xa_left_part = ""; - my $xa_right_part = ""; - my $xa_timestamp = ""; - my $xb_lang = ""; - my $xb_left_part = ""; - my $xb_right_part = ""; - my $xb_timestamp = ""; - my $xa = ""; - my $xb = ""; - my @alist; - my @blist; - - if( $a=~ /$sdf_regex/ ){ - $xa_left_part = defined $2 ? $2 : ''; - $xa_lang = defined $12 ? $12 : ''; - $xa_right_part = defined $13 ? $13 : ''; - $xa_left_part = remove_last_column( $xa_left_part ); - - } - if( $b=~ /$sdf_regex/ ){ - $xb_left_part = defined $2 ? $2 : ''; - $xb_lang = defined $12 ? $12 : ''; - $xb_right_part = defined $13 ? $13 : ''; - $xb_left_part = remove_last_column( $xb_left_part ); - - - } - if( ( $xa_left_part cmp $xb_left_part ) == 0 ){ # Left part equal - if( ( $xa_lang cmp $xb_lang ) == 0 ){ # Lang equal - return ( $xa_right_part cmp $xb_right_part ); # Right part compare - } - elsif( $xa_lang eq "en-US" ) { return -1; } # en-US wins - elsif( $xb_lang eq "en-US" ) { return 1; } # en-US wins - else { return $xa_lang cmp $xb_lang; } # lang compare - } - else { - return $xa_left_part cmp $xb_left_part; # Left part compare - } - } @lines; - - if ( open ( SORTEDFILE , "> $outfile" ) ){ - print SORTEDFILE get_license_header(); - foreach my $newline ( @sorted_lines ) { - print SORTEDFILE $newline; - #print STDOUT $newline; - } - } - close SORTEDFILE; - } else { print STDERR "WARNING: Can't open file $outfile\n";} - print "done\n"; - -} -######################################################### -sub remove_last_column{ - my $string = shift; - my @alist = split ( "\t" , $string ); - pop @alist; - return join( "\t" , @alist ); -} - -######################################################### -sub rename_language{ - my $fallbackhashhash_ref = shift; - my $cur_fallback = shift; - my $cur_lang = shift; - my $line; - - foreach my $key( keys ( %{ $fallbackhashhash_ref->{ $cur_fallback } } ) ){ - $line = $fallbackhashhash_ref->{ $cur_fallback }{ $key }; - if( $line =~ /$sdf_regex/ ){ - my $leftpart = defined $2 ? $2 : ''; - my $lang = defined $12 ? $12 : ''; - my $rightpart = defined $13 ? $13 : ''; - - $fallbackhashhash_ref->{ $cur_lang }{ $key } = $leftpart."\t".$cur_lang."\t".$rightpart; - } - } -} - -############################################################ -sub remove_duplicates{ - my $list_ref = shift; - my %tmphash; - foreach my $key ( @{ $list_ref } ){ $tmphash{ $key } = '' ; } - @{$list_ref} = keys( %tmphash ); -} - -############################################################## -sub fetch_fallback{ - my $sdfparticleslist_ref = shift; - my $localizeSDF = shift; - my $langhash_ref = shift; - my %fallbackhashhash; - my $cur_lang; - my @langlist; - - foreach my $key ( keys ( %{ $langhash_ref } ) ){ - $cur_lang = $langhash_ref->{ $key }; - if ( $cur_lang ne "" ) { - push @langlist , $cur_lang; - } - } - remove_duplicates( \@langlist ); - foreach $cur_lang ( @langlist ){ - if( $cur_lang eq "en-US" ){ - read_fallbacks_from_source( $localizeSDF , $cur_lang , \%fallbackhashhash ); - } - } - - # remove de / en-US - my @tmplist; - foreach $cur_lang( @langlist ){ - if( $cur_lang ne "en-US" ){ - push @tmplist , $cur_lang; - - } - } - @langlist = @tmplist; - if ( $#langlist +1 ){ - read_fallbacks_from_particles( $sdfparticleslist_ref , \@langlist , \%fallbackhashhash ); - - } - return (\%fallbackhashhash); -} - -######################################################### -sub write_file{ - - my $localizeFile = shift; - my $index_ref = shift; - - if( open DESTFILE , "+> $localizeFile" ){ - foreach my $key( %{ $index_ref } ){ - print DESTFILE ($index_ref->{ $key }, "\n" ); - } - close DESTFILE; - }else { - print STDERR "Can't open/create '$localizeFile'"; - } -} - -######################################################### -sub read_file{ - - my $sdffile = shift; - my $langhash_ref = shift; - my %block = (); - - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $plattform = defined $10 ? $10 : ''; - my $lang = defined $12 ? $12 : ''; - my $helpid = defined $9 ? $9 : ''; - - foreach my $isolang ( keys ( %{ $langhash_ref } ) ){ - if( $isolang=~ /$lang/i || $isolang=~ /all/i ) { $block{$prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; } - } - } - } - return (\%block); -} - -######################################################### -sub read_fallbacks_from_particles{ - - my $sdfparticleslist_ref = shift; - my $isolanglist_ref = shift; - my $fallbackhashhash_ref = shift; - my $block_ref; - foreach my $currentfile ( @{ $sdfparticleslist_ref } ){ - if ( open MYFILE , "< $currentfile" ) { - while(){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - my $helpid = defined $9 ? $9 : ''; - - chomp( $line ); - - foreach my $isolang ( @{$isolanglist_ref} ){ - if( $isolang=~ /$lang/i ) { - $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - } - } - } - } - }else { print STDERR "WARNING: Can't open file $currentfile"; } - } -} - -######################################################### -sub read_fallbacks_from_source{ - - my $sdffile = shift; - my $isolang = shift; - my $fallbackhashhash_ref = shift; - my $block_ref; - # read fallback for single file - open MYFILE , "< $sdffile" - or die "Can't open '$sdffile'\n"; - - while( ){ - if( /$sdf_regex/ ){ - my $line = defined $_ ? $_ : ''; - my $prj = defined $3 ? $3 : ''; - my $file = defined $4 ? $4 : ''; - my $type = defined $6 ? $6 : ''; - my $gid = defined $7 ? $7 : ''; - my $lid = defined $8 ? $8 : ''; - my $helpid = defined $9 ? $9 : ''; - my $lang = defined $12 ? $12 : ''; - my $plattform = defined $10 ? $10 : ''; - - chomp( $line ); - if( $isolang=~ /$lang/i ) { $fallbackhashhash_ref->{ $isolang }{ $prj.$gid.$lid.$file.$type.$plattform.$helpid } = $line ; - } - } - } -} - -######################################################### -sub parseLanguages{ - - my $bAll; - my $bUseLocalize; - my $bHasSourceLanguage=""; - my $bFakeEnglish=""; - my %langhash; - my $iso=""; - my $fallback=""; - - #### -l all - if( $languages=~ /all/ ){ - $bAll = "TRUE"; - $bHasSourceLanguage = "TRUE"; - } - ### -l fr=de,de - elsif( $languages=~ /.*,.*/ ){ - my @tmpstr = split "," , $languages; - for my $lang ( @tmpstr ){ - if( $lang=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ - $iso = $1; - $fallback = $4; - - if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { - $bUseLocalize = "TRUE"; - } - if( ( $iso && $iso=~ /(en-US)/i ) ) { - $bHasSourceLanguage = "TRUE"; - } - if( $fallback ) { $langhash{ $iso } = $fallback; } - else { $langhash{ $iso } = ""; } - } - } - } - ### -l de - else{ - if( $languages=~ /([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)(=([a-zA-Z]{2,3}(-[a-zA-Z\-]*)*))?/ ){ - $iso = $1; - $fallback = $4; - - if( ( $iso && $iso=~ /(en-US)/i ) || ( $fallback && $fallback=~ /(en-US)/i ) ) { - $bUseLocalize = "TRUE"; - - } - if( ( $iso && $iso=~ /(en-US)/i ) ) { - $bHasSourceLanguage = "TRUE"; - } - - if( $fallback ) { $langhash{ $iso } = $fallback; } - else { $langhash{ $iso } = ""; } - } - } - # HACK en-US always needed! - if( !$bHasSourceLanguage ){ - #$bHasSourceLanguage = "TRUE"; - $bUseLocalize = "TRUE"; - $bFakeEnglish = "TRUE"; - $langhash{ "en-US" } = ""; - } - return ( $bAll , $bUseLocalize , \%langhash , $bHasSourceLanguage, $bFakeEnglish); -} - -######################################################### -sub parse_options{ - - my $help; - my $merge; - my $extract; - my $success = GetOptions('f=s' => \$sdffile , 'l=s' => \$languages , 's=s' => \$srcpath , 'h' => \$help , 'v' => \$bVerbose , - 'm' => \$merge , 'e' => \$extract , 'x' => \$no_sort , 'd' => \$use_default_date ); - $outputfile = $sdffile; - - #print STDOUT "DBG: lang = $languages\n"; - if( !$srcpath ){ - #$srcpath = "$ENV{SRC_ROOT}"; - if( !$srcpath ){ - print STDERR "No path to the source root found!\n\n"; - usage(); - exit(1); - } - } - if( $help || !$success || $#ARGV > 1 || ( !$sdffile ) ){ - usage(); - exit(1); - } - if( $merge && $sdffile && ! ( -r $sdffile)){ - print STDERR "Can't open file '$sdffile'\n"; - exit(1); - } - if( !( $languages=~ /[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?(,[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*(=[a-zA-Z]{2,3}(-[a-zA-Z\-]*)*)?)*/ ) ){ - print STDERR "Please check the -l iso code\n"; - exit(1); - } - if( ( !$merge && !$extract ) || ( $merge && $extract ) ){ usage();exit( -1 );} - if( $extract ){ $mode = "extract"; } - else { $mode = "merge"; } -} - -######################################################### -sub usage{ - - print STDERR "Usage: localize.pl\n"; - print STDERR "Split or collect SDF files\n"; - print STDERR " merge: -m -f -l l1[=f1][,l2[=f2]][...] [ -s ]\n"; - print STDERR " extract: -e -f -l [ -s ] [-d]\n"; - print STDERR "Options:\n"; - print STDERR " -h help\n"; - print STDERR " -m Merge mode\n"; - print STDERR " -e Extract mode\n"; - print STDERR " -f To split a big SDF file into particles\n"; - print STDERR " To collect and join all particles to one big file\n"; - print STDERR " -s Path to the modules, if no \$SRC_ROOT is set\n"; - print STDERR " -l ( all | | =fallback ) comma seperated languages\n"; - print STDERR " -d Use default date in extracted sdf file\n"; - print STDERR " -v Verbose\n"; - print STDERR "\nExample:\n"; - print STDERR "\nlocalize -e -l en-US,pt-BR=en-US -f my.sdf\n( Extract en-US and pt-BR with en-US fallback )\n"; - print STDERR "\nlocalize -m -l cs -f my.sdf\n( Merge cs translation into the sourcecode ) \n"; -} - -# my $line = defined $_ ? $_ : ''; -# my $leftpart = defined $2 ? $2 : ''; -# my $prj = defined $3 ? $3 : ''; -# my $file = defined $4 ? $4 : ''; -# my $dummy = defined $5 ? $5 : ''; -# my $type = defined $6 ? $6 : ''; -# my $gid = defined $7 ? $7 : ''; -# my $lid = defined $8 ? $8 : ''; -# my $helpid = defined $9 ? $9 : ''; -# my $plattform = defined $10 ? $10 : ''; -# my $width = defined $11 ? $11 : ''; -# my $lang = defined $12 ? $12 : ''; -# my $rightpart = defined $13 ? $13 : ''; -# my $text = defined $14 ? $14 : ''; -# my $helptext = defined $15 ? $15 : ''; -# my $quickhelptext = defined $16 ? $16 : ''; -# my $title = defined $17 ? $17 : ''; -# my $timestamp = defined $18 ? $18 : ''; - diff --git a/transex3/source/cfg_yy_wrapper.c b/transex3/source/cfg_yy_wrapper.c deleted file mode 100644 index ac678d17f399..000000000000 --- a/transex3/source/cfg_yy_wrapper.c +++ /dev/null @@ -1,2 +0,0 @@ -// Helper to suppress warnings in lex generated c code, see #i57362# -#include "cfg_yy.c" diff --git a/transex3/source/cfglex.l b/transex3/source/cfglex.l deleted file mode 100644 index dd2d9a45ab59..000000000000 --- a/transex3/source/cfglex.l +++ /dev/null @@ -1,232 +0,0 @@ -%{ -/* - * lexer for parsing cfg source files - * - */ - - -/* enlarge token buffer to tokenize whole strings */ -#undef YYLMAX -#define YYLMAX 64000 - -/* to enable debug output define LEXDEBUG */ -#define LEXDEBUG 1 -#ifdef LEXDEBUG -#define OUTPUT fprintf -#else -#define OUTPUT(Par1,Par2); -#endif - -/* table of possible token ids */ -#include "tokens.h" -#include -#include - -#if defined __GNUC__ -#pragma GCC system_header -#elif defined __SINPRO_CC -#pragma disable_warn -#elif defined _MSC_VER -#pragma warning(push, 1) -#endif - -/* external functions (C++ code, declared as extren "C" */ -extern int WorkOnTokenSet( int, char* ); -extern int InitCfgExport( char * , char *); -extern int EndCfgExport(); -extern int GetError(); -extern int SetError(); -extern char *GetOutputFile( int argc, char* argv[]); -extern FILE *GetCfgFile(); -extern int isQuiet(); -extern void removeTempFile(); -extern char* getFilename(); -/* forwards */ -void YYWarning(); - -int bText=0; -%} - -%p 24000 -%e 1200 -%n 500 - -%% - -\<[^\>]*"xml:lang="\""x-no-translate"\"[^\<]*\/\> { - bText = 0; - WorkOnTokenSet( CFG_TOKEN_NO_TRANSLATE, yytext ); -} - -\<.*\/\> { - bText = 0; - WorkOnTokenSet( ANYTOKEN, yytext ); -} - -\<[^\>]*"xml:lang="\".*\"[^\<]*\> { - bText = 1; - WorkOnTokenSet( CFG_TEXT_START, yytext ); -} - - -\<[^\/\!][^\>]*\> { - bText = 0; - WorkOnTokenSet( CFG_TAG, yytext ); -} - -"]*\> { - bText = 0; - WorkOnTokenSet( CFG_TAG, yytext ); -} - - -\<\!\-\- { - char c1 = 0, c2 = 0, c3 = input(); - char pChar[2]; - pChar[1] = 0x00; - pChar[0] = c3; - - WorkOnTokenSet( COMMEND, yytext ); - WorkOnTokenSet( COMMEND, pChar ); - - for(;;) { - if ( c3 == EOF ) - break; - if ( c1 == '-' && c2 == '-' && c3 == '>' ) - break; - c1 = c2; - c2 = c3; - c3 = input(); - pChar[0] = c3; - WorkOnTokenSet( COMMEND, pChar ); - } -} - -\<\/[^\>]*\> { - bText = 0; - WorkOnTokenSet( CFG_CLOSETAG, yytext ); -} - -\<[^\>\!]*\> { - bText = 0; - if ( yytext[ 1 ] == '!' && yytext[ 2 ] == '-' && yytext[ 3 ] == '-' ) - WorkOnTokenSet( COMMEND, yytext ); - else - WorkOnTokenSet( CFG_UNKNOWNTAG, yytext ); -} - -.|\n { - if ( bText == 1 ) - WorkOnTokenSet( CFG_TEXTCHAR, yytext ); - else - WorkOnTokenSet( UNKNOWNCHAR, yytext ); -} - - -%% - -/*****************************************************************************/ -int yywrap(void) -/*****************************************************************************/ -{ - return 1; -} - -/*****************************************************************************/ -void YYWarning( char *s ) -/*****************************************************************************/ -{ - /* write warning to stderr */ - fprintf( stderr, - "Warning: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); -} - -/*****************************************************************************/ -#ifdef GCC -void yyerror ( char *s, ... ) -#else -void yyerror ( char *s ) -#endif -/*****************************************************************************/ -{ - /* write error to stderr */ - fprintf( stderr, - "Error: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); - SetError(); -} - -/*****************************************************************************/ -int -#ifdef WNT -_cdecl -#endif -main( int argc, char* argv[]) -/*****************************************************************************/ -{ - /* error level */ - int nRetValue = 0; - char *pOutput; - FILE *pFile; - - pOutput = GetOutputFile( argc, argv ); - if( !isQuiet() ){ - fprintf( stdout, "\nCfgEx 0.9 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); - fprintf( stdout, "======================================================================\n" ); - } - - if ( !pOutput ) { - fprintf( stdout, "Syntax: CFGEX[-p Prj][-r PrjRoot]-i FileIn [-o FileOut][-m DataBase][-e][-b][-u][-f][-d DoneFile][-g[:dtd] ][-L l1,l2,...]\n" ); - fprintf( stdout, " Prj: Project\n" ); - fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); - fprintf( stdout, " FileIn: Source files (*.src)\n" ); - fprintf( stdout, " FileOut: Destination file (*.*)\n" ); - fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); - fprintf( stdout, " -QQ: quiet output\n" ); - fprintf( stdout, " -e: Disable writing errorlog\n" ); - fprintf( stdout, " -b: Break when Token \"HelpText\" found in source\n" ); - fprintf( stdout, " -u: [english] and [german] are allowed, Id is Taken from DataBase \n" ); - fprintf( stdout, " -f: force extraction and merge even if only one language is existent\n" ); - fprintf( stdout, " -g[:dtd]: enables generation of properties (dtds if :dtd is set) - in this case FileOut is the output path\n" ); - fprintf( stdout, " -d: enables generation of *.don if work is done\n" ); - fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); - fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); - fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); - fprintf( stdout, " Example: -L de,es=en-US\n" ); - fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); - return 1; - } - - pFile = GetCfgFile(); - InitCfgExport( pOutput , getFilename() ); - if ( !pFile ) - return 1; - - yyin = pFile; - - /* create global instance of class CfgExport */ - //InitCfgExport( pOutput ); - - /* start parser */ - yylex(); - - /* get error info. and end export */ - nRetValue = GetError(); - EndCfgExport(); - - if( !isQuiet() ){ - fprintf( stdout, "\n===================================\n\n" ); - } - - removeTempFile(); -/* return error level */ - return nRetValue; -} - -/*""]*"-->" { - bText = 0; - WorkOnTokenSet( COMMEND, yytext ); -}*/ -/*" { - bText = 0; - WorkOnTokenSet( CFG_TAG, yytext ); -}*/ diff --git a/transex3/source/cfgmerge.cxx b/transex3/source/cfgmerge.cxx deleted file mode 100644 index 0607c9e9bb06..000000000000 --- a/transex3/source/cfgmerge.cxx +++ /dev/null @@ -1,886 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: cfgmerge.cxx,v $ - * $Revision: 1.46 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -#include - -// local includes -#include "export.hxx" -#include "cfgmerge.hxx" -#include "tokens.h" -#include "utf8conv.hxx" - -extern "C" { int yyerror( char * ); } -extern "C" { int YYWarning( char * ); } - -// defines to parse command line -#define STATE_NON 0x0001 -#define STATE_INPUT 0x0002 -#define STATE_OUTPUT 0x0003 -#define STATE_PRJ 0x0004 -#define STATE_ROOT 0x0005 -#define STATE_MERGESRC 0x0006 -#define STATE_ERRORLOG 0x0007 -#define STATE_UTF8 0x0008 -#define STATE_LANGUAGES 0X0009 -#define STATE_ISOCODE99 0x000A -#define STATE_FORCE 0x000B - -// set of global variables -BOOL bEnableExport; -BOOL bMergeMode; -BOOL bErrorLog; -BOOL bForce; -BOOL bUTF8; -bool bQuiet; -ByteString sPrj; -ByteString sPrjRoot; -ByteString sInputFileName; -ByteString sActFileName; -ByteString sFullEntry; -ByteString sOutputFile; -ByteString sMergeSrc; -String sUsedTempFile; - -CfgParser *pParser; - -extern "C" { -// the whole interface to lexer is in this extern "C" section - -/*****************************************************************************/ -extern char *GetOutputFile( int argc, char* argv[]) -/*****************************************************************************/ -{ - bEnableExport = FALSE; - bMergeMode = FALSE; - bErrorLog = TRUE; - bForce = FALSE; - bUTF8 = TRUE; - bQuiet = false; - sPrj = ""; - sPrjRoot = ""; - sInputFileName = ""; - sActFileName = ""; - - USHORT nState = STATE_NON; - BOOL bInput = FALSE; - - // parse command line - for( int i = 1; i < argc; i++ ) { - ByteString sSwitch( argv[ i ] ); - sSwitch.ToUpperAscii(); - - if ( sSwitch == "-I" ) { - nState = STATE_INPUT; // next token specifies source file - } - else if ( sSwitch == "-O" ) { - nState = STATE_OUTPUT; // next token specifies the dest file - } - else if ( sSwitch == "-P" ) { - nState = STATE_PRJ; // next token specifies the cur. project - } - else if ( sSwitch == "-R" ) { - nState = STATE_ROOT; // next token specifies path to project root - } - else if ( sSwitch == "-M" ) { - nState = STATE_MERGESRC; // next token specifies the merge database - } - else if ( sSwitch == "-E" ) { - nState = STATE_ERRORLOG; - bErrorLog = FALSE; - } - else if ( sSwitch == "-UTF8" ) { - nState = STATE_UTF8; - bUTF8 = TRUE; - } - else if ( sSwitch == "-NOUTF8" ) { - nState = STATE_UTF8; - bUTF8 = FALSE; - } - else if ( sSwitch == "-F" ) { - nState = STATE_FORCE; - bForce = TRUE; - } - else if ( sSwitch == "-QQ" ) { - bQuiet = true; - } - else if ( sSwitch == "-L" ) { - nState = STATE_LANGUAGES; - } - else if ( sSwitch.ToUpperAscii() == "-ISO99" ) { - nState = STATE_ISOCODE99; - } - else { - switch ( nState ) { - case STATE_NON: { - return NULL; // no valid command line - } - case STATE_INPUT: { - sInputFileName = argv[ i ]; - bInput = TRUE; // source file found - } - break; - case STATE_OUTPUT: { - sOutputFile = argv[ i ]; // the dest. file - } - break; - case STATE_PRJ: { - sPrj = ByteString( argv[ i ]); -// sPrj.ToLowerAscii(); // the project - } - break; - case STATE_ROOT: { - sPrjRoot = ByteString( argv[ i ]); // path to project root - } - break; - case STATE_MERGESRC: { - sMergeSrc = ByteString( argv[ i ]); - bMergeMode = TRUE; // activate merge mode, cause merge database found - } - break; - case STATE_LANGUAGES: { - Export::sLanguages = ByteString( argv[ i ]); - } - break; - } - } - } - - if ( bInput ) { - // command line is valid - bEnableExport = TRUE; - char *pReturn = new char[ sOutputFile.Len() + 1 ]; - strcpy( pReturn, sOutputFile.GetBuffer()); // #100211# - checked - return pReturn; - } - - // command line is not valid - return NULL; -} -int isQuiet(){ - if( bQuiet ) return 1; - else return 0; -} -/*****************************************************************************/ -int InitCfgExport( char *pOutput , char* pFilename ) -/*****************************************************************************/ -{ - // instanciate Export - ByteString sOutput( pOutput ); - ByteString sFilename( pFilename ); - Export::InitLanguages(); - - if ( bMergeMode ) - pParser = new CfgMerge( sMergeSrc, sOutputFile, sFilename ); - else if ( sOutputFile.Len()) - pParser = new CfgExport( sOutputFile, sPrj, sActFileName ); - - return 1; -} - -/*****************************************************************************/ -int EndCfgExport() -/*****************************************************************************/ -{ - delete pParser; - - return 1; -} - -void removeTempFile(){ - if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ - DirEntry aTempFile( sUsedTempFile ); - aTempFile.Kill(); - } -} -extern const char* getFilename() -{ - return sInputFileName.GetBuffer(); -} -/*****************************************************************************/ -extern FILE *GetCfgFile() -/*****************************************************************************/ -{ - FILE *pFile = 0; - // look for valid filename - if ( sInputFileName.Len()) { - if( Export::fileHasUTF8ByteOrderMarker( sInputFileName ) ){ - DirEntry aTempFile = Export::GetTempFile(); - DirEntry aSourceFile( String( sInputFileName , RTL_TEXTENCODING_ASCII_US ) ); - aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); - String sTempFile = aTempFile.GetFull(); - Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); - pFile = fopen( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ).GetBuffer(), "r" ); - sUsedTempFile = sTempFile; - }else{ - // able to open file? - pFile = fopen( sInputFileName.GetBuffer(), "r" ); - sUsedTempFile = String::CreateFromAscii(""); - } - if ( !pFile ){ - fprintf( stderr, "Error: Could not open file %s\n", - sInputFileName.GetBuffer()); - exit( 13 ); - } - else { - // this is a valid file which can be opened, so - // create path to project root - DirEntry aEntry( String( sInputFileName, RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - sFullEntry= ByteString( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( sPrjRoot ); - ByteString sPrjEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - // create file name, beginnig with project root - // (e.g.: source\ui\src\menue.src) -// printf("sFullEntry = %s\n",sFullEntry.GetBuffer()); - sActFileName = sFullEntry.Copy( sPrjEntry.Len() + 1 ); -// printf("sActFileName = %s\n",sActFileName.GetBuffer()); - if( !bQuiet ) - fprintf( stdout, "\nProcessing File %s ...\n", sInputFileName.GetBuffer()); - - sActFileName.SearchAndReplaceAll( "/", "\\" ); - - return pFile; - } - } - // this means the file could not be opened - return NULL; -} - -/*****************************************************************************/ -int WorkOnTokenSet( int nTyp, char *pTokenText ) -/*****************************************************************************/ -{ - pParser->Execute( nTyp, pTokenText ); - - return 1; -} - - -/*****************************************************************************/ -int SetError() -/*****************************************************************************/ -{ - return 1; -} - -/*****************************************************************************/ -int GetError() -/*****************************************************************************/ -{ - return 0; -} -} - -// -// class CfgStackData -// - -CfgStackData* CfgStack::Push( const ByteString &rTag, const ByteString &rId ) -{ - CfgStackData *pD = new CfgStackData( rTag, rId ); - Insert( pD, LIST_APPEND ); - return pD; -} - -// -// class CfgStack -// - -/*****************************************************************************/ -CfgStack::~CfgStack() -/*****************************************************************************/ -{ - for ( ULONG i = 0; i < Count(); i++ ) - delete GetObject( i ); -} - -/*****************************************************************************/ -ByteString CfgStack::GetAccessPath( ULONG nPos ) -/*****************************************************************************/ -{ - if ( nPos == LIST_APPEND ) - nPos = Count() - 1; - - ByteString sReturn; - for ( ULONG i = 0; i <= nPos; i++ ) { - if ( i ) - sReturn += "."; - sReturn += GetStackData( i )->GetIdentifier(); - } - - return sReturn; -} - -/*****************************************************************************/ -CfgStackData *CfgStack::GetStackData( ULONG nPos ) -/*****************************************************************************/ -{ - if ( nPos == LIST_APPEND ) - nPos = Count() - 1; - - return GetObject( nPos ); -} - -// -// class CfgParser -// - -/*****************************************************************************/ -CfgParser::CfgParser() -/*****************************************************************************/ - : pStackData( NULL ), - bLocalize( FALSE ) -{ -} - -/*****************************************************************************/ -CfgParser::~CfgParser() -/*****************************************************************************/ -{ -} - - -/*****************************************************************************/ -BOOL CfgParser::IsTokenClosed( const ByteString &rToken ) -/*****************************************************************************/ -{ - return rToken.GetChar( rToken.Len() - 2 ) == '/'; -} - -/*****************************************************************************/ -void CfgParser::AddText( - ByteString &rText, - const ByteString &rIsoLang, - const ByteString &rResTyp -) -/*****************************************************************************/ -{ - USHORT nTextLen = 0; - while ( rText.Len() != nTextLen ) { - nTextLen = rText.Len(); - rText.SearchAndReplaceAll( "\n", " " ); - rText.SearchAndReplaceAll( "\r", " " ); - rText.SearchAndReplaceAll( "\t", " " ); - rText.SearchAndReplaceAll( " ", " " ); - } - pStackData->sResTyp = rResTyp; - WorkOnText( rText, rIsoLang ); - - pStackData->sText[ rIsoLang ] = rText; -} - - -/*****************************************************************************/ -void CfgParser::WorkOnRessourceEnd() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -int CfgParser::ExecuteAnalyzedToken( int nToken, char *pToken ) -/*****************************************************************************/ -{ - ByteString sToken( pToken ); - - if ( sToken == " " || sToken == "\t" ) - sLastWhitespace += sToken; - - ByteString sTokenName; - ByteString sTokenId; - - BOOL bOutput = TRUE; - - switch ( nToken ) { - case CFG_TOKEN_PACKAGE: - case CFG_TOKEN_COMPONENT: - case CFG_TOKEN_TEMPLATE: - case CFG_TOKEN_CONFIGNAME: - case CFG_TOKEN_OORNAME: - case CFG_TOKEN_OORVALUE: - case CFG_TAG: - case ANYTOKEN: - case CFG_TEXT_START: - { - sTokenName = sToken.GetToken( 1, '<' ).GetToken( 0, '>' ).GetToken( 0, ' ' ); - - if ( !IsTokenClosed( sToken )) { - ByteString sSearch; - switch ( nToken ) { - case CFG_TOKEN_PACKAGE: - sSearch = "package-id="; - break; - case CFG_TOKEN_COMPONENT: - sSearch = "component-id="; - break; - case CFG_TOKEN_TEMPLATE: - sSearch = "template-id="; - break; - case CFG_TOKEN_CONFIGNAME: - sSearch = "cfg:name="; - break; - case CFG_TOKEN_OORNAME: - sSearch = "oor:name="; - bLocalize = TRUE; - break; - case CFG_TOKEN_OORVALUE: - sSearch = "oor:value="; - break; - case CFG_TEXT_START: { - if ( sCurrentResTyp != sTokenName ) { - WorkOnRessourceEnd(); - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - pStackData->sText[ sCur ] = ByteString(""); - } - } - sCurrentResTyp = sTokenName; - - ByteString sTemp = sToken.Copy( sToken.Search( "xml:lang=" )); - sCurrentIsoLang = sTemp.GetToken( 1, '\"' ).GetToken( 0, '\"' ); - - if ( sCurrentIsoLang == NO_TRANSLATE_ISO ) - bLocalize = FALSE; - - pStackData->sTextTag = sToken; - - sCurrentText = ""; - } - break; - } - if ( sSearch.Len()) { - ByteString sTemp = sToken.Copy( sToken.Search( sSearch )); - sTokenId = sTemp.GetToken( 1, '\"' ).GetToken( 0, '\"' ); - } - pStackData = aStack.Push( sTokenName, sTokenId ); - - if ( sSearch == "cfg:name=" ) { - ByteString sTemp( sToken ); - sTemp.ToUpperAscii(); - bLocalize = (( sTemp.Search( "CFG:TYPE=\"STRING\"" ) != STRING_NOTFOUND ) && - ( sTemp.Search( "CFG:LOCALIZED=\"TRUE\"" ) != STRING_NOTFOUND )); - } - } - else if ( sTokenName == "label" ) { - if ( sCurrentResTyp != sTokenName ) { - WorkOnRessourceEnd(); - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - pStackData->sText[ sCur ] = ByteString(""); - } - } - sCurrentResTyp = sTokenName; - } - } - break; - case CFG_CLOSETAG: - sTokenName = sToken.GetToken( 1, '/' ).GetToken( 0, '>' ).GetToken( 0, ' ' ); - if ( aStack.GetStackData() && ( aStack.GetStackData()->GetTagType() == sTokenName )) { - if ( ! sCurrentText.Len()) - WorkOnRessourceEnd(); - aStack.Pop(); - pStackData = aStack.GetStackData(); - } - else { - ByteString sError( "Missplaced close tag: " ); - ByteString sInFile(" in file "); - sError += sToken; - sError += sInFile; - sError += sFullEntry; - Error( sError ); - exit ( 13 ); - } - break; - - case CFG_TEXTCHAR: - sCurrentText += sToken; - bOutput = FALSE; - break; - - case CFG_TOKEN_NO_TRANSLATE: - bLocalize = FALSE; - break; - } - - if ( sCurrentText.Len() && nToken != CFG_TEXTCHAR ) { - AddText( sCurrentText, sCurrentIsoLang, sCurrentResTyp ); - Output( sCurrentText ); - sCurrentText = ""; - pStackData->sEndTextTag = sToken; - } - - if ( bOutput ) - Output( sToken ); - - if ( sToken != " " && sToken != "\t" ) - sLastWhitespace = ""; - - return 1; -} - -/*****************************************************************************/ -void CfgExport::Output( const ByteString& rOutput ) -/*****************************************************************************/ -{ - // Dummy operation to suppress warnings caused by poor class design - ByteString a( rOutput ); -} - -/*****************************************************************************/ -int CfgParser::Execute( int nToken, char * pToken ) -/*****************************************************************************/ -{ - ByteString sToken( pToken ); - - switch ( nToken ) { - case CFG_TAG: - if ( sToken.Search( "package-id=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_PACKAGE, pToken ); - else if ( sToken.Search( "component-id=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_COMPONENT, pToken ); - else if ( sToken.Search( "template-id=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_TEMPLATE, pToken ); - else if ( sToken.Search( "cfg:name=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_OORNAME, pToken ); - else if ( sToken.Search( "oor:name=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_OORNAME, pToken ); - else if ( sToken.Search( "oor:value=" ) != STRING_NOTFOUND ) - return ExecuteAnalyzedToken( CFG_TOKEN_OORVALUE, pToken ); - break; - } - return ExecuteAnalyzedToken( nToken, pToken ); -} - - -/*****************************************************************************/ -void CfgParser::Error( const ByteString &rError ) -/*****************************************************************************/ -{ -// ByteString sError( rError ); -// sError.Append("Error: In file "); -// sError.Append( sActFileName ); - yyerror(( char * ) rError.GetBuffer()); -} - - -// -// class CfgOutputParser -// - -/*****************************************************************************/ -CfgOutputParser::CfgOutputParser( const ByteString &rOutputFile ) -/*****************************************************************************/ -{ - pOutputStream = - new SvFileStream( - String( rOutputFile, RTL_TEXTENCODING_ASCII_US ), - STREAM_STD_WRITE | STREAM_TRUNC - ); - pOutputStream->SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); - - if ( !pOutputStream->IsOpen()) { - ByteString sError( "ERROR: Unable to open output file: " ); - sError += rOutputFile; - Error( sError ); - delete pOutputStream; - pOutputStream = NULL; - exit( 13 ); - } -} - -/*****************************************************************************/ -CfgOutputParser::~CfgOutputParser() -/*****************************************************************************/ -{ - if ( pOutputStream ) { - pOutputStream->Close(); - delete pOutputStream; - } -} - -// -// class CfgExport -// - -/*****************************************************************************/ -CfgExport::CfgExport( - const ByteString &rOutputFile, - const ByteString &rProject, - const ByteString &rFilePath -) -/*****************************************************************************/ - : CfgOutputParser( rOutputFile ), - sPrj( rProject ), - sPath( rFilePath ) -{ - Export::InitLanguages( false ); - aLanguages = Export::GetLanguages(); -} - -/*****************************************************************************/ -CfgExport::~CfgExport() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -void CfgExport::WorkOnRessourceEnd() -/*****************************************************************************/ -{ - if ( pOutputStream && bLocalize ) { - if (( pStackData->sText[ ByteString("en-US") ].Len() - ) || - ( bForce && - ( pStackData->sText[ ByteString("de") ].Len() || - pStackData->sText[ ByteString("en-US") ].Len() ))) - { - ByteString sFallback = pStackData->sText[ ByteString("en-US") ]; - - //if ( pStackData->sText[ ByteString("en-US") ].Len()) - // sFallback = pStackData->sText[ ByteString("en-US") ]; - - ByteString sLocalId = pStackData->sIdentifier; - ByteString sGroupId; - if ( aStack.Count() == 1 ) { - sGroupId = sLocalId; - sLocalId = ""; - } - else { - sGroupId = aStack.GetAccessPath( aStack.Count() - 2 ); - } - - ByteString sTimeStamp( Export::GetTimeStamp()); - - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sText = pStackData->sText[ sCur ]; - if ( !sText.Len()) - sText = sFallback; - - Export::UnquotHTML( sText ); - - ByteString sOutput( sPrj ); sOutput += "\t"; - sOutput += sPath; - sOutput += "\t0\t"; - sOutput += pStackData->sResTyp; sOutput += "\t"; - sOutput += sGroupId; sOutput += "\t"; - sOutput += sLocalId; sOutput += "\t\t\t0\t"; - sOutput += sCur; - sOutput += "\t"; - - sOutput += sText; sOutput += "\t\t\t\t"; - sOutput += sTimeStamp; - - //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sPrj ) ) ) - pOutputStream->WriteLine( sOutput ); - } - } - } -} - -/*****************************************************************************/ -void CfgExport::WorkOnText( - ByteString &rText, - const ByteString &rIsoLang -) -/*****************************************************************************/ -{ - if( rIsoLang.Len() ) Export::UnquotHTML( rText ); -} - - -// -// class CfgMerge -// - -/*****************************************************************************/ -CfgMerge::CfgMerge( - const ByteString &rMergeSource, const ByteString &rOutputFile, - ByteString &rFilename ) -/*****************************************************************************/ - : CfgOutputParser( rOutputFile ), - pMergeDataFile( NULL ), - pResData( NULL ), - bGerman( FALSE ), - sFilename( rFilename ), - bEnglish( FALSE ) -{ - if ( rMergeSource.Len()){ - pMergeDataFile = new MergeDataFile( - rMergeSource, sInputFileName , bErrorLog, RTL_TEXTENCODING_MS_1252, true ); - if( Export::sLanguages.EqualsIgnoreCaseAscii("ALL") ){ - Export::SetLanguages( pMergeDataFile->GetLanguages() ); - aLanguages = pMergeDataFile->GetLanguages(); - } - else aLanguages = Export::GetLanguages(); - }else - aLanguages = Export::GetLanguages(); -} - -/*****************************************************************************/ -CfgMerge::~CfgMerge() -/*****************************************************************************/ -{ - delete pMergeDataFile; - delete pResData; -} - -/*****************************************************************************/ -void CfgMerge::WorkOnText( - ByteString &rText, - const ByteString& nLangIndex -) -/*****************************************************************************/ -{ - - if ( pMergeDataFile && bLocalize ) { - if ( !pResData ) { - ByteString sLocalId = pStackData->sIdentifier; - ByteString sGroupId; - if ( aStack.Count() == 1 ) { - sGroupId = sLocalId; - sLocalId = ""; - } - else { - sGroupId = aStack.GetAccessPath( aStack.Count() - 2 ); - } - - ByteString sPlatform( "" ); - - pResData = new ResData( sPlatform, sGroupId , sFilename ); - pResData->sId = sLocalId; - pResData->sResTyp = pStackData->sResTyp; - } - - //if ( nLangIndex.EqualsIgnoreCaseAscii("de") ) - // bGerman = TRUE; - if (( nLangIndex.EqualsIgnoreCaseAscii("en-US") )) - bEnglish = TRUE; - - PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrysCaseSensitive( pResData ); - if ( pEntrys ) { - ByteString sContent; - pEntrys->GetText( sContent, STRING_TYP_TEXT, nLangIndex ); - - if ( Export::isAllowed( nLangIndex ) && - ( sContent != "-" ) && ( sContent.Len())) - { -#ifdef MERGE_SOURCE_LANGUAGES - if( nLangIndex.EqualsIgnoreCaseAscii("de") || nLangIndex.EqualsIgnoreCaseAscii("en-US") ) - rText = sContent; -#endif - Export::QuotHTML( rText ); - } - } - } -} - -/*****************************************************************************/ -void CfgMerge::Output( const ByteString& rOutput ) -/*****************************************************************************/ -{ - if ( pOutputStream ) - pOutputStream->Write( rOutput.GetBuffer(), rOutput.Len()); -} - -ULONG CfgStack::Push( CfgStackData *pStackData ) -{ - Insert( pStackData, LIST_APPEND ); - return Count() - 1; -} - -/*****************************************************************************/ -void CfgMerge::WorkOnRessourceEnd() -/*****************************************************************************/ -{ - - if ( pMergeDataFile && pResData && bLocalize && (( bEnglish ) || bForce )) { - PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrysCaseSensitive( pResData ); - if ( pEntrys ) { - ByteString sCur; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sContent; - pEntrys->GetText( sContent, STRING_TYP_TEXT, sCur , TRUE ); - if ( - // (!sCur.EqualsIgnoreCaseAscii("de") ) && - ( !sCur.EqualsIgnoreCaseAscii("en-US") ) && - - ( sContent != "-" ) && ( sContent.Len())) - { - - ByteString sText = sContent; - Export::QuotHTML( sText ); - - ByteString sAdditionalLine( "\t" ); - - ByteString sTextTag = pStackData->sTextTag; - ByteString sTemp = sTextTag.Copy( sTextTag.Search( "xml:lang=" )); - - ByteString sSearch = sTemp.GetToken( 0, '\"' ); - sSearch += "\""; - sSearch += sTemp.GetToken( 1, '\"' ); - sSearch += "\""; - - ByteString sReplace = sTemp.GetToken( 0, '\"' ); - sReplace += "\""; - sReplace += sCur; - sReplace += "\""; - - sTextTag.SearchAndReplace( sSearch, sReplace ); - - sAdditionalLine += sTextTag; - sAdditionalLine += sText; - sAdditionalLine += pStackData->sEndTextTag; - - sAdditionalLine += "\n"; - sAdditionalLine += sLastWhitespace; - - Output( sAdditionalLine ); - } - } - } - } - delete pResData; - pResData = NULL; - bGerman = FALSE; - bEnglish = FALSE; -} diff --git a/transex3/source/directory.cxx b/transex3/source/directory.cxx deleted file mode 100644 index ed0fe27d22c2..000000000000 --- a/transex3/source/directory.cxx +++ /dev/null @@ -1,276 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: directory.cxx,v $ - * $Revision: 1.6 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include "tools/string.hxx" -#include -#include -#include - -namespace transex -{ - -Directory::Directory( const rtl::OUString sFullpath ) : bSkipLinks( false ) -{ - sFullName = sFullpath; -} - -Directory::Directory( const rtl::OUString sFullPath , const rtl::OUString sEntry ) : bSkipLinks( false ) -{ - sFullName = sFullPath; - sDirectoryName = sEntry; -} - - -Directory::Directory( const ByteString sFullPath ) : bSkipLinks( false ) -{ - sDirectoryName = rtl::OUString( sFullPath.GetBuffer() , RTL_TEXTENCODING_UTF8 , sFullPath.Len() ); -} - -bool Directory::lessDir ( const Directory& rKey1, const Directory& rKey2 ) -{ - rtl::OUString sName1( ( static_cast< Directory >( rKey1 ) ).getDirectoryName() ); - rtl::OUString sName2( ( static_cast< Directory >( rKey2 ) ).getDirectoryName() ); - - return sName1.compareTo( sName2 ) < 0 ; -} - - -void Directory::dump() -{ - - for( std::vector< transex::File >::iterator iter = aFileVec.begin() ; iter != aFileVec.end() ; ++iter ) - { - std::cout << "FILE " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n"; - } - - for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() ; ++iter ) - { - std::cout << "DIR " << rtl::OUStringToOString( (*iter).getFullName().getStr() , RTL_TEXTENCODING_UTF8 , (*iter).getFullName().getLength() ).getStr() << "\n"; - } - -} - -void Directory::scanSubDir( int nLevels ) -{ - readDirectory( sFullName ); - dump(); - if( nLevels > 0 ) { - for( std::vector< transex::Directory >::iterator iter = aDirVec.begin() ; iter != aDirVec.end() || nLevels > 0 ; ++iter , nLevels-- ) - { - ( *iter ).scanSubDir(); - } - } -} - -void Directory::setSkipLinks( bool is_skipped ) -{ - bSkipLinks = is_skipped; -} - -void Directory::readDirectory() -{ - readDirectory( sFullName ); -} - -#ifdef WNT -#include -#include -#include - -void Directory::readDirectory ( const rtl::OUString& sFullpath ) -{ - BOOL fFinished; - HANDLE hList; - TCHAR szDir[MAX_PATH+1]; - TCHAR szSubDir[MAX_PATH+1]; - WIN32_FIND_DATA FileData; - - rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ); - const char *dirname = sFullpathext.getStr(); - - // Get the proper directory path - sprintf(szDir, "%s\\*", dirname); - - // Get the first file - hList = FindFirstFile(szDir, &FileData); - if (hList == INVALID_HANDLE_VALUE) - { - //FindClose(hList); - //printf("No files found %s\n", szDir ); return; - } - else - { - fFinished = FALSE; - while (!fFinished) - { - - sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName); - rtl::OString myfile( FileData.cFileName ); - rtl::OString mydir( szSubDir ); - - if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - if ( (strcmp(FileData.cFileName, ".") != 0 ) && - (strcmp(FileData.cFileName, "..") != 0 ) ) - { - //sprintf(szSubDir, "%s\\%s", dirname, FileData.cFileName); - transex::Directory aDir( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ), - rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) ); - aDirVec.push_back( aDir ); - } - } - else - { - transex::File aFile( rtl::OStringToOUString( mydir , RTL_TEXTENCODING_UTF8 , mydir.getLength() ), - rtl::OStringToOUString( myfile , RTL_TEXTENCODING_UTF8 , myfile.getLength() ) ); - aFileVec.push_back( aFile ); - } - if (!FindNextFile(hList, &FileData)) - { - if (GetLastError() == ERROR_NO_MORE_FILES) - { - fFinished = TRUE; - } - } - } - } - - FindClose(hList); - - ::std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile ); - ::std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir ); -} - -#else - -class dirholder -{ -private: - DIR *mpDir; -public: - dirholder(DIR *pDir) : mpDir(pDir) {} - int close() { int nRet = mpDir ? closedir(mpDir) : 0; mpDir = NULL; return nRet; } - ~dirholder() { close(); } -}; - -void Directory::readDirectory( const rtl::OUString& sFullpath ) -{ - struct stat statbuf; - struct stat statbuf2; - struct dirent *dirp; - DIR *dir; - //int ret; - //char *ptr; - - if( sFullpath.getLength() < 1 ) return; - - rtl::OString sFullpathext = rtl::OUStringToOString( sFullpath , RTL_TEXTENCODING_UTF8 , sFullpath.getLength() ).getStr(); - //printf("%s\n",sFullpathext.getStr()); - const char* path = sFullpathext.getStr(); - - // stat - if( stat( path , &statbuf ) < 0 ){ printf("warning: Can not stat %s" , path ); return; }// error } - - if( S_ISDIR(statbuf.st_mode ) == 0 ) { return; }// error } return; // not dir - - if( (dir = opendir( path ) ) == NULL ) {printf("readerror 2 in %s \n",path); return; } // error } return; // error - dirholder aHolder(dir); - - sFullpathext += rtl::OString( "/" ); - - const rtl::OString sDot ( "." ) ; - const rtl::OString sDDot( ".." ); - - if ( chdir( path ) == -1 ) { printf("chdir error in %s \n",path); return; } // error - - while( ( dirp = readdir( dir ) ) != NULL ) - { - rtl::OString sEntryName( dirp->d_name ); - - if( sEntryName.equals( sDot ) || sEntryName.equals( sDDot ) ) - continue; - - // add dir entry - rtl::OString sEntity = sFullpathext; - sEntity += sEntryName; - - // stat new entry - if( lstat( sEntity.getStr() , &statbuf2 ) < 0 ) - { - printf("error on entry %s\n" , sEntity.getStr() ) ; // error - continue; - } - - // add file / dir to vector - switch( statbuf2.st_mode & S_IFMT ) - { - case S_IFREG: - { - rtl::OString sFile = sFullpathext; - sFile += sEntryName ; - transex::File aFile( rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) , - rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() ) - ); - - aFileVec.push_back( aFile ) ; - break; - } - case S_IFLNK: - { - if( bSkipLinks ) break; - } - case S_IFDIR: - { - rtl::OString sDir = sFullpathext; - sDir += sEntryName ; - - transex::Directory aDir( - rtl::OStringToOUString( sEntity , RTL_TEXTENCODING_UTF8 , sEntity.getLength() ) , - rtl::OStringToOUString( sEntryName , RTL_TEXTENCODING_UTF8 , sEntryName.getLength() ) - ) ; - aDirVec.push_back( aDir ) ; - break; - } - } - } - if ( chdir( ".." ) == -1 ) { printf("chdir error in .. \n"); return; } // error - if( aHolder.close() < 0 ) return ; // error - - std::sort( aFileVec.begin() , aFileVec.end() , File::lessFile ); - std::sort( aDirVec.begin() , aDirVec.end() , Directory::lessDir ); - -} - -#endif -} diff --git a/transex3/source/export.cxx b/transex3/source/export.cxx deleted file mode 100644 index 5294d902d2ee..000000000000 --- a/transex3/source/export.cxx +++ /dev/null @@ -1,2660 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: export.cxx,v $ - * $Revision: 1.57 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -#include -#include "export.hxx" -#include "tokens.h" -#include "utf8conv.hxx" -#include - -extern "C" { int yyerror( char * ); } -extern "C" { int YYWarning( char * ); } - -Export *pExport = 0L; - -// defines to parse command line -#define STATE_NON 0x0001 -#define STATE_INPUT 0x0002 -#define STATE_OUTPUT 0x0003 -#define STATE_PRJ 0x0004 -#define STATE_ROOT 0x0005 -#define STATE_MERGESRC 0x0006 -#define STATE_ERRORLOG 0x0007 -#define STATE_BREAKHELP 0x0008 -#define STATE_UNMERGE 0x0009 -#define STATE_UTF8 0x000A -#define STATE_LANGUAGES 0X000B - -// set of global variables -DECLARE_LIST( FileList, ByteString * ) -FileList aInputFileList; -BOOL bEnableExport; -BOOL bMergeMode; -BOOL bErrorLog; -BOOL bBreakWhenHelpText; -BOOL bUnmerge; -BOOL bUTF8; -bool bQuiet; -ByteString sPrj; -ByteString sPrjRoot; -ByteString sActFileName; -ByteString sOutputFile; -ByteString sMergeSrc; -ByteString sTempFile; -ByteString sFile; -MergeDataFile *pMergeDataFile; -FILE *pTempFile; - - -ByteString sStrBuffer; -bool bMarcro = false; - -extern "C" { -// the whole interface to lexer is in this extern "C" section - - -/*****************************************************************************/ -extern char *GetOutputFile( int argc, char* argv[]) -/*****************************************************************************/ -{ - bEnableExport = FALSE; - bMergeMode = FALSE; - bErrorLog = TRUE; - bBreakWhenHelpText = FALSE; - bUnmerge = FALSE; - bUTF8 = TRUE; - sPrj = ""; - sPrjRoot = ""; - sActFileName = ""; - Export::sLanguages = ""; - Export::sForcedLanguages = ""; - sTempFile = ""; - pTempFile = NULL; - bQuiet = false; - USHORT nState = STATE_NON; - BOOL bInput = FALSE; - - // parse command line - for( int i = 1; i < argc; i++ ) { - ByteString sSwitch( argv[ i ] ); - - if (sSwitch == "-i" || sSwitch == "-I" ) { - nState = STATE_INPUT; // next tokens specifies source files - } - else if (sSwitch == "-o" || sSwitch == "-O" ) { - nState = STATE_OUTPUT; // next token specifies the dest file - } - else if (sSwitch == "-p" || sSwitch == "-P" ) { - nState = STATE_PRJ; // next token specifies the cur. project - } - else if (sSwitch == "-qq" || sSwitch == "-QQ" ) { - bQuiet = true; - } - - else if (sSwitch == "-r" || sSwitch == "-R" ) { - nState = STATE_ROOT; // next token specifies path to project root - } - else if (sSwitch == "-m" || sSwitch == "-M" ) { - nState = STATE_MERGESRC; // next token specifies the merge database - } - else if (sSwitch == "-e" || sSwitch == "-E" ) { - nState = STATE_ERRORLOG; - bErrorLog = FALSE; - } - else if (sSwitch == "-b" || sSwitch == "-B" ) { - nState = STATE_BREAKHELP; - bBreakWhenHelpText = TRUE; - } - else if (sSwitch == "-u" || sSwitch == "-U" ) { - nState = STATE_UNMERGE; - bUnmerge = TRUE; - bMergeMode = TRUE; - } - else if ( sSwitch.ToUpperAscii() == "-UTF8" ) { - nState = STATE_UTF8; - bUTF8 = TRUE; - } - else if ( sSwitch.ToUpperAscii() == "-NOUTF8" ) { - nState = STATE_UTF8; - bUTF8 = FALSE; - } - else if ( sSwitch == "-l" || sSwitch == "-L" ) { - nState = STATE_LANGUAGES; - } - else { - switch ( nState ) { - case STATE_NON: { - return NULL; // no valid command line - } - case STATE_INPUT: { - aInputFileList.Insert( new ByteString( argv[ i ]), LIST_APPEND ); - bInput = TRUE; // min. one source file found - } - break; - case STATE_OUTPUT: { - sOutputFile = ByteString( argv[ i ]); // the dest. file - } - break; - case STATE_PRJ: { - sPrj = ByteString( argv[ i ]); - } - break; - case STATE_ROOT: { - sPrjRoot = ByteString( argv[ i ]); // path to project root - } - break; - case STATE_MERGESRC: { - sMergeSrc = ByteString( argv[ i ]); - bMergeMode = TRUE; // activate merge mode, cause merge database found - } - break; - case STATE_LANGUAGES: { - Export::sLanguages = ByteString( argv[ i ]); - } - break; - } - } - } - if( bUnmerge ) sMergeSrc = ByteString(); - if ( bInput ) { - // command line is valid - bEnableExport = TRUE; - char *pReturn = new char[ sOutputFile.Len() + 1 ]; - strcpy( pReturn, sOutputFile.GetBuffer()); // #100211# - checked - return pReturn; - } - - // command line is not valid - return NULL; -} -/*****************************************************************************/ -int isQuiet(){ -/*****************************************************************************/ - if( bQuiet ) return 1; - else return 0; -} -/*****************************************************************************/ -int InitExport( char *pOutput , char* pFilename ) -/*****************************************************************************/ -{ - // instanciate Export - ByteString sOutput( pOutput ); - ByteString sFilename( pFilename ); - - if ( bMergeMode && !bUnmerge ) { - // merge mode enabled, so read database - pExport = new Export(sOutput, bEnableExport, sPrj, sPrjRoot, sMergeSrc , sFilename ); - } - else - // no merge mode, only export - pExport = new Export( sOutput, bEnableExport, sPrj, sPrjRoot , sFilename ); - return 1; -} - -/*****************************************************************************/ -int EndExport() -/*****************************************************************************/ -{ - delete pExport; - return 1; -} - -extern const char* getFilename() -{ - return (*(aInputFileList.GetObject( 0 ))).GetBuffer(); -} -/*****************************************************************************/ -extern FILE *GetNextFile() -/*****************************************************************************/ -{ - // look for next valid filename in input file list - if ( sTempFile.Len()) { - fclose( pTempFile ); - String sTemp( sTempFile, RTL_TEXTENCODING_ASCII_US ); - DirEntry aTemp( sTemp ); - aTemp.Kill(); - } - - while ( aInputFileList.Count()) { - ByteString sFileName( *(aInputFileList.GetObject( 0 ))); - - ByteString sOrigFile( sFileName ); - - sFileName = Export::GetNativeFile( sFileName ); - delete aInputFileList.GetObject(( ULONG ) 0 ); - aInputFileList.Remove(( ULONG ) 0 ); - - if ( sFileName == "" ) { - fprintf( stderr, "ERROR: Could not precompile File %s\n", - sOrigFile.GetBuffer()); - return GetNextFile(); - } - - sTempFile = sFileName; - Export::RemoveUTF8ByteOrderMarkerFromFile( sFileName ); - - // able to open file? - FILE *pFile = fopen( sFileName.GetBuffer(), "r" ); - if ( !pFile ) - fprintf( stderr, "Error: Could not open File %s\n", - sFileName.GetBuffer()); - else { - pTempFile = pFile; - - // this is a valid file which can be opened, so - // create path to project root - DirEntry aEntry( String( sOrigFile, RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - ByteString sFullEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( sPrjRoot ); - ByteString sPrjEntry( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - // create file name, beginnig with project root - // (e.g.: source\ui\src\menue.src) - sActFileName = sFullEntry.Copy( sPrjEntry.Len() + 1 ); - - if( !bQuiet ) fprintf( stdout, "\nProcessing File %s ...\n", sOrigFile.GetBuffer()); - - sActFileName.SearchAndReplaceAll( "/", "\\" ); - sFile = sActFileName; - - if ( pExport ) { - // create instance of class export - pExport->Init(); - } - // return the valid file handle - return pFile; - } - } - // this means the file could not be opened - return NULL; -} - -int Parse( int nTyp, const char *pTokenText ){ - pExport->Execute( nTyp , pTokenText ); - return 1; -} -void Close(){ - pExport->pParseQueue->Close(); -} -/*****************************************************************************/ -int WorkOnTokenSet( int nTyp, char *pTokenText ) -/*****************************************************************************/ -{ - - pExport->pParseQueue->Push( QueueEntry( nTyp , ByteString( pTokenText ) ) ); - return 1; -} - -} // extern - -extern "C" { -/*****************************************************************************/ -int SetError() -/*****************************************************************************/ -{ - // set error at global instance of class Export - pExport->SetError(); - return 1; -} -} - -extern "C" { -/*****************************************************************************/ -int GetError() -/*****************************************************************************/ -{ - // get error at global instance of class Export - if ( pExport->GetError()) - return 1; - return FALSE; -} -} - -// -// class ResData -// - -void ResData::Dump(){ - printf("**************\nResData\n"); - printf("sPForm = %s , sResTyp = %s , sId = %s , sGId = %s , sHelpId = %s\n",sPForm.GetBuffer() - ,sResTyp.GetBuffer(),sId.GetBuffer(),sGId.GetBuffer(),sHelpId.GetBuffer()); - - ByteString a("*pStringList"); - ByteString b("*pUIEntries"); - ByteString c("*pFilterList"); - ByteString d("*pItemList"); - ByteString e("*pPairedList"); - ByteString f("sText"); - - Export::DumpMap( f , sText ); - - if( pStringList ) Export::DumpExportList( a , *pStringList ); - if( pUIEntries ) Export::DumpExportList( b , *pUIEntries ); - if( pFilterList ) Export::DumpExportList( c , *pFilterList ); - if( pItemList ) Export::DumpExportList( d , *pItemList ); - if( pPairedList ) Export::DumpExportList( e , *pPairedList ); - printf("\n"); -} - -void ResData::addFallbackData( ByteString& sId_in , const ByteString& sText_in ){ - //printf(" ResData::addFallbackData ( sId = %s , sText = %s )\n", sId_in.GetBuffer() , sText_in.GetBuffer() ); - aFallbackData[ sId_in ] = sText_in; -} -bool ResData::getFallbackData( ByteString& sId_in , ByteString& sText_inout ){ - sText_inout = aFallbackData[ sId_in ]; - //printf("ResData::getFallbackData( sId = %s , return sText = %s \n" , sId_in.GetBuffer(), sText_inout.GetBuffer()); - return sText_inout.Len() > 0; -} - -void ResData::addMergedLanguage( ByteString& sLang ){ - aMergedLanguages[ sLang ]=ByteString("1"); -} -bool ResData::isMerged( ByteString& sLang ){ - return aMergedLanguages[ sLang ].Equals("1"); -} - -/*****************************************************************************/ -BOOL ResData::SetId( const ByteString &rId, USHORT nLevel ) -/*****************************************************************************/ -{ - if ( nLevel > nIdLevel ) - { - nIdLevel = nLevel; - sId = rId; - - if ( bChild && bChildWithText ) { - ByteString sError( "ResId after child definition" ); - yyerror( sError.GetBufferAccess()); - sError.ReleaseBufferAccess(); - SetError(); - } - - if ( sId.Len() > 255 ) { - ByteString sWarning( "LocalId > 255 chars, truncating..." ); - YYWarning( sWarning.GetBufferAccess()); - sWarning.ReleaseBufferAccess(); - sId.Erase( 255 ); - sId.EraseTrailingChars( ' ' ); - sId.EraseTrailingChars( '\t' ); - } - - return TRUE; - } - - return FALSE; -} - -// -// class Export -// - -/*****************************************************************************/ -Export::Export( const ByteString &rOutput, BOOL bWrite, - const ByteString &rPrj, const ByteString &rPrjRoot , const ByteString& rFile ) -/*****************************************************************************/ - : - pWordTransformer( NULL ), - aCharSet( RTL_TEXTENCODING_MS_1252 ), - bDefine( FALSE ), - bNextMustBeDefineEOL( FALSE ), - nLevel( 0 ), - nList( LIST_NON ), - nListIndex( 0 ), - nListLevel( 0 ), - bSkipFile( false ), - sProject( sPrj ), - sRoot( sPrjRoot ), - bEnableExport( bWrite ), - bMergeMode( bUnmerge ), - bError( FALSE ), - bReadOver( FALSE ), - bDontWriteOutput( FALSE ), - sFilename( rFile ) -{ - pParseQueue = new ParserQueue( *this ); - (void) rPrj; - (void) rPrjRoot; - (void) rFile; - - if( !isInitialized ) InitLanguages(); - // used when export is enabled - - // open output stream - if ( bEnableExport ) { - aOutput.Open( String( rOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); - if( !aOutput.IsOpen() ) { - printf("ERROR : Can't open file %s\n",rOutput.GetBuffer()); - exit ( -1 ); - } - aOutput.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); - - aOutput.SetLineDelimiter( LINEEND_CRLF ); - } -} - -/*****************************************************************************/ -Export::Export( const ByteString &rOutput, BOOL bWrite, - const ByteString &rPrj, const ByteString &rPrjRoot, - const ByteString &rMergeSource , const ByteString& rFile ) -/*****************************************************************************/ - : - pWordTransformer( NULL ), - aCharSet( RTL_TEXTENCODING_MS_1252 ), - bDefine( FALSE ), - bNextMustBeDefineEOL( FALSE ), - nLevel( 0 ), - nList( LIST_NON ), - nListIndex( 0 ), - nListLevel( 0 ), - bSkipFile( false ), - sProject( sPrj ), - sRoot( sPrjRoot ), - bEnableExport( bWrite ), - bMergeMode( TRUE ), - sMergeSrc( rMergeSource ), - bError( FALSE ), - bReadOver( FALSE ), - bDontWriteOutput( FALSE ), - sFilename( rFile ) -{ - (void) rPrj; - (void) rPrjRoot; - (void) rFile; - pParseQueue = new ParserQueue( *this ); - if( !isInitialized ) InitLanguages( bMergeMode ); - // used when merge is enabled - - // open output stream - if ( bEnableExport ) { - aOutput.Open( String( rOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); - aOutput.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); - aOutput.SetLineDelimiter( LINEEND_CRLF ); - } - -} - -/*****************************************************************************/ -void Export::Init() -/*****************************************************************************/ -{ - // resets the internal status, used before parseing another file - sActPForm = ""; - bDefine = FALSE; - bNextMustBeDefineEOL = FALSE; - nLevel = 0; - nList = LIST_NON; - nListLang = ByteString( String::CreateFromAscii(""),RTL_TEXTENCODING_ASCII_US ); - nListIndex = 0; - while ( aResStack.Count()) { - delete aResStack.GetObject(( ULONG ) 0 ); - aResStack.Remove(( ULONG ) 0 ); - } -} - -/*****************************************************************************/ -Export::~Export() -/*****************************************************************************/ -{ - if( pParseQueue ) - delete pParseQueue; - // close output stream - if ( bEnableExport ) - aOutput.Close(); - while ( aResStack.Count()) { - delete aResStack.GetObject(( ULONG ) 0 ); - aResStack.Remove(( ULONG ) 0 ); - } - - if ( bMergeMode && !bUnmerge ) { - if ( !pMergeDataFile ) - pMergeDataFile = new MergeDataFile( sMergeSrc,sFile , bErrorLog, aCharSet);//, bUTF8 ); - - //pMergeDataFile->WriteErrorLog( sActFileName ); - delete pMergeDataFile; - } -} - -/*****************************************************************************/ -int Export::Execute( int nToken, const char * pToken ) -/*****************************************************************************/ -{ - - ByteString sToken( pToken ); - ByteString sOrig( sToken ); -/* printf("+---------------\n"); - printf("sToken = %s\n",sToken.GetBuffer()); - printf("nToken = %d\n",nToken); - printf("+---------------\n"); */ - BOOL bWriteToMerged = bMergeMode; - - if ( nToken == CONDITION ) { - ByteString sTestToken( pToken ); - sTestToken.EraseAllChars( '\t' ); - sTestToken.EraseAllChars( ' ' ); - if (( !bReadOver ) && ( sTestToken.Search( "#ifndef__RSC_PARSER" ) == 0 )) - bReadOver = TRUE; - else if (( bReadOver ) && ( sTestToken.Search( "#endif" ) == 0 )) - bReadOver = FALSE; - } - if ((( nToken < FILTER_LEVEL ) || ( bReadOver )) && - (!(( bNextMustBeDefineEOL ) && ( sOrig == "\n" )))) { - // this tokens are not mandatory for parsing, so ignore them ... - if ( bMergeMode ) - WriteToMerged( sOrig , false ); // ... ore whrite them directly to dest. - return 0; - } - - ResData *pResData = NULL; - if ( nLevel ) { - // res. exists at cur. level - pResData = aResStack.GetObject( nLevel-1 ); - } - else if (( nToken != RESSOURCE ) && - ( nToken != RESSOURCEEXPR ) && - ( nToken != SMALRESSOURCE ) && - ( nToken != LEVELUP ) && - ( nToken != NORMDEFINE ) && - ( nToken != RSCDEFINE ) && - ( nToken != CONDITION ) && - ( nToken != PRAGMA )) - { - // no res. exists at cur. level so return - if ( bMergeMode ) - WriteToMerged( sOrig , false ); - return 0; - } - // #define NO_LOCALIZE_EXPORT - if( bSkipFile ){ - if ( bMergeMode ) { - WriteToMerged( sOrig , false ); - } - return 1; - } - - - if ( bDefine ) { - if (( nToken != EMPTYLINE ) && ( nToken != LEVELDOWN ) && ( nToken != LEVELUP )) { - // cur. res. defined in macro - if ( bNextMustBeDefineEOL ) { - if ( nToken != RSCDEFINELEND ) { - // end of macro found, so destroy res. - bDefine = FALSE; - if ( bMergeMode ) { - /*if ( bDontWriteOutput && bUnmerge ) { - bDontWriteOutput = FALSE; - bNextMustBeDefineEOL = FALSE; - bDefine = TRUE; - }*/ - MergeRest( pResData ); - } - bNextMustBeDefineEOL = FALSE; - Execute( LEVELDOWN, "" ); - } - else { - // next line also in macro definition - bNextMustBeDefineEOL = FALSE; - if ( bMergeMode ) - WriteToMerged( sOrig , false ); - return 1; - } - } - else if (( nToken != LISTASSIGNMENT ) && ( nToken != UIENTRIES )){ - // cur. line has macro line end - ByteString sTmpLine( sToken ); - sTmpLine.EraseAllChars( '\t' ); sTmpLine.EraseAllChars( ' ' ); - #if 0 - // impossible, unsigned is never negative - if( sTmpLine.Len() < 0 ){ - if ( sTmpLine.GetChar(( USHORT )( sTmpLine.Len() - 1 )) != '\\' ) - bNextMustBeDefineEOL = TRUE; - } - #endif - } - } - } - - BOOL bExecuteDown = FALSE; - if ( nToken != LEVELDOWN ) { - USHORT nOpen = 0; - USHORT nClose = 0; - BOOL bReadOver1 = FALSE; - USHORT i = 0; - for ( i = 0; i < sToken.Len(); i++ ) { - if ( sToken.GetChar( i ) == '\"' ) - bReadOver1 = !bReadOver1; - if ( !bReadOver1 && ( sToken.GetChar( i ) == '{' )) - nOpen++; - } - - bReadOver1 = FALSE; - for ( i = 0; i < sToken.Len(); i++ ) { - if ( sToken.GetChar( i ) == '\"' ) - bReadOver1 = !bReadOver1; - if ( !bReadOver1 && ( sToken.GetChar( i ) == '}' )) - nClose++; - } - - if ( nOpen < nClose ) - bExecuteDown = TRUE; - } - switch ( nToken ) { - - case NORMDEFINE: - //printf("sToken = '%s'",sToken.GetBuffer()); - while( sToken.SearchAndReplace( "\r", " " ) != STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; - if( sToken.EqualsIgnoreCaseAscii( "#define NO_LOCALIZE_EXPORT" ) ){ - bSkipFile = true; - return 0; - } - if ( bMergeMode ) - WriteToMerged( sOrig , false ); - - return 0; - - - case RSCDEFINE: - bDefine = TRUE; // res. defined in macro - - case RESSOURCE: - case RESSOURCEEXPR: { - bDontWriteOutput = FALSE; - if ( nToken != RSCDEFINE ) - bNextMustBeDefineEOL = FALSE; - // this is the beginning of a new res. - nLevel++; - if ( nLevel > 1 ) { - aResStack.GetObject( nLevel - 2 )->bChild = TRUE; - } - - // create new instance for this res. and fill mandatory fields - - pResData = new ResData( sActPForm, FullId() , sFilename ); - aResStack.Insert( pResData, LIST_APPEND ); - ByteString sBackup( sToken ); - sToken.EraseAllChars( '\n' ); - sToken.EraseAllChars( '\r' ); - sToken.EraseAllChars( '{' ); - while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - sToken.EraseTrailingChars( ' ' ); - ByteString sT = sToken.GetToken( 0, ' ' ); - pResData->sResTyp = sT.ToLowerAscii(); - ByteString sId( sToken.Copy( pResData->sResTyp.Len() + 1 )); - ByteString sCondition; - if ( sId.Search( "#" ) != STRING_NOTFOUND ) { - // between ResTyp, Id and paranthes is a precomp. condition - sCondition = "#"; - sCondition += sId.GetToken( 1, '#' ); - sId = sId.GetToken( 0, '#' ); - } - sId = sId.GetToken( 0, '/' ); - CleanValue( sId ); - sId = sId.EraseAllChars( '\t' ); - pResData->SetId( sId, ID_LEVEL_IDENTIFIER ); - if ( sCondition.Len()) { - ByteString sEmpty( "" ); - Execute( CONDITION, sEmpty.GetBufferAccess()); // execute the - // precomp. - // condition - sEmpty.ReleaseBufferAccess(); - } - } - break; - case SMALRESSOURCE: { - bDontWriteOutput = FALSE; - // this is the beginning of a new res. - bNextMustBeDefineEOL = FALSE; - nLevel++; - if ( nLevel > 1 ) { - aResStack.GetObject( nLevel - 2 )->bChild = TRUE; - } - - // create new instance for this res. and fill mandatory fields - - pResData = new ResData( sActPForm, FullId() , sFilename ); - aResStack.Insert( pResData, LIST_APPEND ); - sToken.EraseAllChars( '\n' ); - sToken.EraseAllChars( '\r' ); - sToken.EraseAllChars( '{' ); - sToken.EraseAllChars( '\t' ); - sToken.EraseAllChars( ' ' ); - sToken.EraseAllChars( '\\' ); - pResData->sResTyp = sToken.ToLowerAscii(); - } - break; - case LEVELUP: { - // push - if ( nList ) - nListLevel++; - if ( nList ) - break; - - bDontWriteOutput = FALSE; - ByteString sLowerTyp; - if ( pResData ) - sLowerTyp = "unknown"; - nLevel++; - if ( nLevel > 1 ) { - aResStack.GetObject( nLevel - 2 )->bChild = TRUE; - } - - ResData *pNewData = new ResData( sActPForm, FullId() , sFilename ); - pNewData->sResTyp = sLowerTyp; - aResStack.Insert( pNewData, LIST_APPEND ); - } - break; - case LEVELDOWN: { - // pop - if ( !nList ) { - bDontWriteOutput = FALSE; - if ( nLevel ) { - if ( bDefine && (nLevel == 1 )) { - bDefine = FALSE; - bNextMustBeDefineEOL = FALSE; - } - WriteData( pResData ); - delete aResStack.GetObject( nLevel - 1 ); - aResStack.Remove( nLevel - 1 ); - nLevel--; - } - } - else { - if ( bDefine ) - bNextMustBeDefineEOL = TRUE; - if ( !nListLevel ) { - if ( bMergeMode ) - MergeRest( pResData, MERGE_MODE_LIST ); - nList = LIST_NON; - } - else - nListLevel--; - } - } - break; - case ASSIGNMENT: { - bDontWriteOutput = FALSE; - // interpret different types of assignement - ByteString sKey = sToken.GetToken( 0, '=' ); - sKey.EraseAllChars( ' ' ); - sKey.EraseAllChars( '\t' ); - ByteString sValue = sToken.GetToken( 1, '=' ); - CleanValue( sValue ); - if ( sKey.ToUpperAscii() == "IDENTIFIER" ) { - ByteString sId( sValue.EraseAllChars( '\t' )); - pResData->SetId( sId.EraseAllChars( ' ' ), ID_LEVEL_IDENTIFIER ); - } - else if ( sKey == "HELPID" ) { - pResData->sHelpId = sValue; - } - else if ( sKey == "STRINGLIST" ) { - //if ( bUnmerge ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - //} - - pResData->bList = TRUE; - nList = LIST_STRING; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - else if ( sKey == "FILTERLIST" ) { - //if ( bUnmerge ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - //} - pResData->bList = TRUE; - nList = LIST_FILTER; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - else if ( sKey == "UIENTRIES" ) { - //if ( bUnmerge ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" ));} - pResData->bList = TRUE; - nList = LIST_UIENTRIES; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - if (( sToken.Search( "{" ) != STRING_NOTFOUND ) && - ( sToken.GetTokenCount( '{' ) > sToken.GetTokenCount( '}' ))) - { - //WorkOnTokenSet( LEVELUP, pTkn ); - Parse( LEVELUP, "" ); - } - //if ( bUnmerge && ( nListLang.EqualsIgnoreCaseAscii("de") || nListLang.EqualsIgnoreCaseAscii("en-US") ) && ListExists( pResData, nList )) - // bDontWriteOutput = TRUE; - } - break; - case UIENTRIES: - case LISTASSIGNMENT: { - bDontWriteOutput = FALSE; - ByteString sTmpToken( sToken); - sTmpToken.EraseAllChars(' '); - USHORT nPos = 0; - //nPos = sTmpToken.ToLowerAscii().Search("[de]="); - nPos = sTmpToken.ToLowerAscii().Search("[en-us]="); - if( nPos != STRING_NOTFOUND ) { - //if ( bUnmerge ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - //} - ByteString sKey = sTmpToken.Copy( 0 , nPos ); - sKey.EraseAllChars( ' ' ); - sKey.EraseAllChars( '\t' ); - ByteString sValue = sToken.GetToken( 1, '=' ); - CleanValue( sValue ); - if ( sKey.ToUpperAscii() == "STRINGLIST" ) { - pResData->bList = TRUE; - nList = LIST_STRING; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - else if ( sKey == "FILTERLIST" ) { - pResData->bList = TRUE; - nList = LIST_FILTER; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - // PairedList - else if ( sKey == "PAIREDLIST" ) { - pResData->bList = TRUE; - nList = LIST_PAIRED; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - - else if ( sKey == "ITEMLIST" ) { - pResData->bList = TRUE; - nList = LIST_ITEM; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - else if ( sKey == "UIENTRIES" ) { - pResData->bList = TRUE; - nList = LIST_UIENTRIES; - //ByteString sLang("en-US" , RTL_TEXTENCODING_ASCII_US ); - nListLang = SOURCE_LANGUAGE; - nListIndex = 0; - nListLevel = 0; - } - /*if ( bUnmerge && ( nListLang.EqualsIgnoreCaseAscii( "de" ) - || nListLang.EqualsIgnoreCaseAscii("en-US" ) ) - && ListExists( pResData, nList )) - bDontWriteOutput = TRUE;*/ - } - else { - // new res. is a String- or FilterList - ByteString sKey = sToken.GetToken( 0, '[' ); - sKey.EraseAllChars( ' ' ); - sKey.EraseAllChars( '\t' ); - if ( sKey.ToUpperAscii() == "STRINGLIST" ) - nList = LIST_STRING; - else if ( sKey == "FILTERLIST" ) - nList = LIST_FILTER; - else if ( sKey == "PAIREDLIST" ) - nList = LIST_PAIRED; // abcd - else if ( sKey == "ITEMLIST" ) - nList = LIST_ITEM; - else if ( sKey == "UIENTRIES" ) - nList = LIST_UIENTRIES; - if ( nList ) { - ByteString sLang=sToken.GetToken( 1, '[' ).GetToken( 0, ']' ); - CleanValue( sLang ); - nListLang = sLang; - /*if (( bUnmerge ) && ( !nListLang.EqualsIgnoreCaseAscii("de")) && ( !nListLang.EqualsIgnoreCaseAscii("en-US"))) - bDontWriteOutput = TRUE;*/ - nListIndex = 0; - nListLevel = 0; - /*if ( bUnmerge && nListLang.EqualsIgnoreCaseAscii("de") && ListExists( pResData, nList ) ) - bDontWriteOutput = TRUE;*/ - } - } - } - break; - case TEXT: - case _LISTTEXT: - case LISTTEXT: { - // this is an entry for a String- or FilterList - if ( nList ) { - SetChildWithText(); - ByteString sEntry( sToken.GetToken( 1, '\"' )); - if ( sToken.GetTokenCount( '\"' ) > 3 ) - sEntry += "\""; - if ( sEntry == "\\\"" ) - sEntry = "\""; - //sEntry = sEntry.Convert( aCharSet, RTL_TEXTENCODING_MS_1252 ); - //sEntry = sEntry.Convert( RTL_TEXTENCODING_MS_1252, RTL_TEXTENCODING_UTF8 ); - InsertListEntry( sEntry, sOrig ); - if ( bMergeMode && ( sEntry != "\"" )) { - PrepareTextToMerge( sOrig, nList, nListLang, pResData ); - } - } - } - break; - case LONGTEXTLINE: - case TEXTLINE: - bDontWriteOutput = FALSE; - if ( nLevel ) { - CutComment( sToken ); - - // this is a text line!!! - ByteString sKey = sToken.GetToken( 0, '=' ).GetToken( 0, '[' ); - sKey.EraseAllChars( ' ' ); - sKey.EraseAllChars( '\t' ); - ByteString sText( GetText( sToken, nToken )); - if ( !bMergeMode ) - sText = sText.Convert( aCharSet, RTL_TEXTENCODING_MS_1252 ); - ByteString sLang; - if ( sToken.GetToken( 0, '=' ).Search( "[" ) != STRING_NOTFOUND ) { - sLang = sToken.GetToken( 0, '=' ).GetToken( 1, '[' ).GetToken( 0, ']' ); - CleanValue( sLang ); - } - ByteString nLangIndex = sLang; - ByteString sOrigKey = sKey; - if ( sText.Len() && sLang.Len() ) { - if (( sKey.ToUpperAscii() == "TEXT" ) || - ( sKey == "MESSAGE" ) || - ( sKey == "CUSTOMUNITTEXT" ) || - ( sKey == "SLOTNAME" ) || - ( sKey == "UINAME" )) - { - //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ) - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - - SetChildWithText(); - //if ( nLangIndex.EqualsIgnoreCaseAscii("en-US") ) - if ( Export::isSourceLanguage( nLangIndex ) ) - pResData->SetId( sText, ID_LEVEL_TEXT ); - - pResData->bText = TRUE; - pResData->sTextTyp = sOrigKey; - if ( bMergeMode ) { - PrepareTextToMerge( sOrig, STRING_TYP_TEXT, nLangIndex, pResData ); - //if ( bUnmerge ) - // pResData->sText[ nLangIndex ] = sText; - } - else { - if ( pResData->sText[ nLangIndex ].Len()) { - ByteString sError( "Language " ); - sError += nLangIndex; - sError += " defined twice"; - } - pResData->sText[ nLangIndex ] = sText; - } - } - else if ( sKey == "HELPTEXT" ) { - //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - // } - SetChildWithText(); - pResData->bHelpText = TRUE; - if ( bBreakWhenHelpText ) { - ByteString sError( "\"HelpText\" found in source\n" ); - YYWarning( sError.GetBufferAccess()); - sError.ReleaseBufferAccess(); - SetError(); - } - if ( bMergeMode ) - PrepareTextToMerge( sOrig, STRING_TYP_HELPTEXT, nLangIndex, pResData ); - //if ( bUnmerge ) - // pResData->sHelpText[ nLangIndex ] = sText; - else { - if ( pResData->sHelpText[ nLangIndex ].Len()) { - ByteString sError( "Language " ); - sError += nLangIndex; - sError += " defined twice"; - } - pResData->sHelpText[ nLangIndex ] = sText; - } - } - else if ( sKey == "QUICKHELPTEXT" ) { - //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - // } - SetChildWithText(); - pResData->bQuickHelpText = TRUE; - if ( bMergeMode ) - PrepareTextToMerge( sOrig, STRING_TYP_QUICKHELPTEXT, nLangIndex, pResData ); - //if ( bUnmerge ) - // pResData->sQuickHelpText[ nLangIndex ] = sText; - else { - if ( pResData->sQuickHelpText[ nLangIndex ].Len()) { - ByteString sError( "Language " ); - sError += nLangIndex; - sError += " defined twice"; - } - pResData->sQuickHelpText[ nLangIndex ] = sText; - } - } - else if ( sKey == "TITLE" ) { - //if ( bUnmerge && sToken.GetToken( 0, '=' ).Search( "[" ) == STRING_NOTFOUND ){ - // ( sOrig.SearchAndReplace( "=", "[ de ] =" )); - // } - SetChildWithText(); - pResData->bTitle = TRUE; - if ( bMergeMode ) - PrepareTextToMerge( sOrig, STRING_TYP_TITLE, nLangIndex, pResData ); - //if ( bUnmerge ) - // pResData->sTitle[ nLangIndex ] = sText; - else { - if ( pResData->sTitle[ nLangIndex ].Len()) { - ByteString sError( "Language " ); - sError += nLangIndex; - sError += " defined twice"; - } - pResData->sTitle[ nLangIndex ] = sText; - } - } - else if ( sKey == "ACCESSPATH" ) { - pResData->SetId( sText, ID_LEVEL_ACCESSPATH ); - } - else if ( sKey == "FIELDNAME" ) { - pResData->SetId( sText, ID_LEVEL_FIELDNAME ); - } - } - } - break; - case NEWTEXTINRES: { - bDontWriteOutput = TRUE; - // this means something like // ### Achtung : Neuer Text ... - /*ByteString sLang( "GERMAN" ); - ByteString sText = sToken.GetToken( 2, ':' ).GetToken( 0, '*' ); - CleanValue( sText ); - if ( sText.Len()) - pResData->sText[ sLang ] = sText;*/ - } - break; - case APPFONTMAPPING: { - bDontWriteOutput = FALSE; - // this is a AppfontMapping, so look if its a definition - // of field size - ByteString sKey = sToken.GetToken( 0, '=' ); - sKey.EraseAllChars( ' ' ); - sKey.EraseAllChars( '\t' ); - ByteString sMapping = sToken.GetToken( 1, '=' ); - sMapping = sMapping.GetToken( 1, '(' ); - sMapping = sMapping.GetToken( 0, ')' ); - sMapping.EraseAllChars( ' ' ); - sMapping.EraseAllChars( '\t' ); - if ( sKey.ToUpperAscii() == "SIZE" ) { - pResData->nWidth = ( USHORT ) sMapping.GetToken( 0, ',' ).ToInt64(); - } - else if ( sKey == "POSSIZE" ) { - pResData->nWidth = ( USHORT ) sMapping.GetToken( 2, ',' ).ToInt64(); - } - } - break; - case RSCDEFINELEND: - bDontWriteOutput = FALSE; - break; - case CONDITION: { - bDontWriteOutput = FALSE; - while( sToken.SearchAndReplace( "\r", " " ) != STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; - ByteString sCondition = sToken.GetToken( 0, ' ' ); - if ( sCondition == "#ifndef" ) { - sActPForm = "!defined "; - sActPForm += sToken.GetToken( 1, ' ' ); - } - else if ( sCondition == "#ifdef" ) { - sActPForm = "defined "; - sActPForm += sToken.GetToken( 1, ' ' ); - } - else if ( sCondition == "#if" ) { - sActPForm = sToken.Copy( 4 ); - while ( sActPForm.SearchAndReplace( "||", "\\or" ) != STRING_NOTFOUND ) {}; - } - else if ( sCondition == "#elif" ) { - sActPForm = sToken.Copy( 6 ); - while ( sActPForm.SearchAndReplace( "||", "\\or" ) != STRING_NOTFOUND ) {}; - } - else if ( sCondition == "#else" ) { - sActPForm = sCondition; - } - else if ( sCondition == "#endif" ) { - sActPForm = ""; - } - else break; - if ( nLevel ) { - WriteData( pResData, TRUE ); - pResData->sPForm = sActPForm; - } - } - break; - case EMPTYLINE : { - bDontWriteOutput = FALSE; - if ( bDefine ) { - bNextMustBeDefineEOL = FALSE; - bDefine = FALSE; - while ( nLevel ) - Parse( LEVELDOWN, "" ); - //WorkOnTokenSet( LEVELDOWN, pTkn ); - } - } - break; - case PRAGMA : { - bDontWriteOutput = FALSE; - while( sToken.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( " ", " " ) != STRING_NOTFOUND ) {}; - sToken.EraseLeadingChars( ' ' ); - sToken.EraseTrailingChars( ' ' ); - - ByteString sCharset = sToken.GetToken( 1, ' ' ); - ByteString sSet = sToken.GetToken( 2, ' ' ); - if (( sCharset.ToUpperAscii() == "CHARSET_IBMPC" ) || - ( sCharset == "RTL_TEXTENCODING_IBM_850" ) || - (( sCharset == "CHARSET" ) && ( sSet.ToUpperAscii() == "IBMPC" ))) - { - aCharSet = RTL_TEXTENCODING_IBM_850; - } - else if (( sCharset == "CHARSET_ANSI" ) || - ( sCharset == "RTL_TEXTENCODING_MS_1252" ) || - (( sCharset == "CHARSET" ) && ( sSet.ToUpperAscii() == "ANSI" ))) - { - aCharSet = RTL_TEXTENCODING_MS_1252; - } - } - break; - case TEXTREFID : { - bDontWriteOutput = TRUE; - /*ByteString sK = sToken.GetToken( 0, '=' ); - ByteString sKey = sK.EraseAllChars( '\t' ).EraseAllChars( ' ' ); - ByteString sT = sToken.GetToken( 1, '=' ).GetToken( 0, ';' ); - USHORT nRefId = ( USHORT ) sT.EraseAllChars( '\t' ).EraseAllChars( ' ' ).ToInt32(); - if (( sKey.ToUpperAscii() == "TEXT" ) || - ( sKey == "MESSAGE" ) || - ( sKey == "CUSTOMUNITTEXT" ) || - ( sKey == "SLOTNAME" ) || - ( sKey == "UINAME" )) - pResData->nTextRefId = nRefId; - else if ( sKey == "HELPTEXT" ) - pResData->nHelpTextRefId = nRefId; - else if ( sKey == "QUICKHELPTEXT" ) - pResData->nQuickHelpTextRefId = nRefId; - else if ( sKey == "TITLE" ) - pResData->nTitleRefId = nRefId;*/ - } - } - if ( bWriteToMerged ) { - // the current token must be written to dest. without merging - - if( bDefine && sOrig.Len() > 2 ){ - for( USHORT n = 0 ; n < sOrig.Len() ; n++ ){ - if( sOrig.GetChar( n ) == '\n' && sOrig.GetChar( n-1 ) != '\\'){ - sOrig.Insert('\\' , n++ ); - } - } - } - WriteToMerged( sOrig , false); - } - - if ( bExecuteDown ) { - Parse( LEVELDOWN, "" ); - //WorkOnTokenSet( LEVELDOWN, pTkn ); - } - - return 1; -} - -/*****************************************************************************/ -void Export::CutComment( ByteString &rText ) -/*****************************************************************************/ -{ - if ( rText.Search( "//" ) != STRING_NOTFOUND ) { - ByteString sWork( rText ); - sWork.SearchAndReplaceAll( "\\\"", "XX" ); - USHORT i = 0; - BOOL bInner = FALSE; - - while ( i < sWork.Len() - 1 ) { - if ( sWork.GetChar( i ) == '\"' ) - bInner = !bInner; - else if - (( sWork.GetChar( i ) == '/' ) && - ( !bInner ) && - ( sWork.GetChar( i + 1 ) == '/' )) - { - rText.Erase( i ); - return; - } - i++; - } - } -} - -void Export::UnmergeUTF8( ByteString& sOrig ){ - USHORT nPos1 = sOrig.Search('\"'); - USHORT nPos2 = sOrig.SearchBackward('\"'); - if( nPos1 > 0 && nPos2 > 0 && nPos1 < nPos2){ - ByteString sPart = sOrig.Copy(nPos1+1 , nPos2-1); - ByteString sPartUTF8 = sPart; - sPartUTF8.Convert( RTL_TEXTENCODING_MS_1252 , RTL_TEXTENCODING_UTF8 ); - sOrig.SearchAndReplace( sPart , sPartUTF8 ); - } -} - -/*****************************************************************************/ -BOOL Export::ListExists( ResData *pResData, USHORT nLst ) -/*****************************************************************************/ -{ - switch ( nLst ) { - case LIST_STRING: return pResData->pStringList != NULL; - case LIST_FILTER: return pResData->pFilterList != NULL; - case LIST_ITEM: return pResData->pItemList != NULL; - case LIST_PAIRED: return pResData->pPairedList != NULL; - case LIST_UIENTRIES: return pResData->pUIEntries != NULL; - } - return FALSE; -} - -/*****************************************************************************/ -BOOL Export::WriteData( ResData *pResData, BOOL bCreateNew ) -/*****************************************************************************/ -{ - if ( bMergeMode ) { - MergeRest( pResData ); - return TRUE; - } - - if ( bUnmerge ) - return TRUE; - -/* ByteStringHashMap::iterator pos3 = pResData->sText.begin(); - ByteStringHashMap::iterator end3 = pResData->sText.end(); - for(;pos3!=end3;++pos3){ - - printf("[%s]=%s\n", pos3->first.GetBuffer(), pos3->second.GetBuffer() ); - }*/ - // mandatory to export: en-US - - if (( //pResData->sText[ ByteString("de") ].Len() && - ( pResData->sText[ SOURCE_LANGUAGE ].Len())) - || - ( //pResData->sHelpText[ ByteString("de") ].Len() && - ( pResData->sHelpText[ SOURCE_LANGUAGE ].Len())) - || - ( //pResData->sQuickHelpText[ ByteString("de") ].Len() && - ( pResData->sQuickHelpText[ SOURCE_LANGUAGE ].Len())) - || - ( //pResData->sTitle[ ByteString("de") ].Len() && - ( pResData->sTitle[ SOURCE_LANGUAGE ].Len()))) - - { - FillInFallbacks( pResData ); - - ByteString sGID = pResData->sGId; - ByteString sLID; - if ( !sGID.Len()) - sGID = pResData->sId; - else - sLID = pResData->sId; - - ByteString sXText; - ByteString sXHText; - ByteString sXQHText; - ByteString sXTitle; - - ByteString sTimeStamp( Export::GetTimeStamp()); - ByteString sCur; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - if ( !sCur.EqualsIgnoreCaseAscii("x-comment") ){ - if ( pResData->sText[ sCur ].Len()) - sXText = pResData->sText[ sCur ]; - else { - sXText = pResData->sText[ SOURCE_LANGUAGE ]; - /*if ( !sXText.Len()) - sXText = pResData->sText[ ByteString("en") ]; - if ( !sXText.Len()) - sXText = pResData->sText[ ByteString("de") ];*/ - } - - if ( pResData->sHelpText[ sCur ].Len()) - sXHText = pResData->sHelpText[ sCur ]; - else { - sXHText = pResData->sHelpText[ SOURCE_LANGUAGE ]; - /*if ( !sXHText.Len()) - sXHText = pResData->sHelpText[ ByteString("en") ]; - if ( !sXText.Len()) - sXHText = pResData->sHelpText[ ByteString("de") ];*/ - } - - if ( pResData->sQuickHelpText[ sCur ].Len()) - sXQHText = pResData->sQuickHelpText[ sCur ]; - else { - sXQHText = pResData->sQuickHelpText[ SOURCE_LANGUAGE ]; - /*if ( !sXQHText.Len()) - sXQHText = pResData->sQuickHelpText[ ByteString("en") ]; - if ( !sXQHText.Len()) - sXQHText = pResData->sQuickHelpText[ ByteString("de") ];*/ - } - - if ( pResData->sTitle[ sCur ].Len()) - sXTitle = pResData->sTitle[ sCur ]; - else { - sXTitle = pResData->sTitle[ SOURCE_LANGUAGE ]; - /*if ( !sXTitle.Len()) - sXTitle = pResData->sTitle[ ByteString("en") ]; - if ( !sXTitle.Len()) - sXTitle = pResData->sTitle[ ByteString("de") ];*/ - } - - if ( !sXText.Len()) - sXText = "-"; - - if ( !sXHText.Len()) { - /*if ( pResData->sHelpText[ ByteString("de") ].Len()) - sXHText = pResData->sHelpText[ ByteString("de") ];*/ - if ( pResData->sHelpText[ SOURCE_LANGUAGE ].Len()) - sXHText = pResData->sHelpText[ SOURCE_LANGUAGE ]; - /*else if ( pResData->sHelpText[ ByteString("en") ].Len()) - sXHText = pResData->sHelpText[ ByteString("en") ];*/ - } - } - else - sXText = pResData->sText[ sCur ]; - - if ( bEnableExport ) { - ByteString sOutput( sProject ); sOutput += "\t"; - if ( sRoot.Len()) - sOutput += sActFileName; - sOutput += "\t0\t"; - sOutput += pResData->sResTyp; sOutput += "\t"; - sOutput += sGID; sOutput += "\t"; - sOutput += sLID; sOutput += "\t"; - sOutput += pResData->sHelpId; sOutput += "\t"; - sOutput += pResData->sPForm; sOutput += "\t"; - sOutput += ByteString::CreateFromInt64( pResData->nWidth ); sOutput += "\t"; - sOutput += sCur; sOutput += "\t"; - - - sOutput += sXText; sOutput += "\t"; - sOutput += sXHText; sOutput += "\t"; - sOutput += sXQHText; sOutput+= "\t"; - sOutput += sXTitle; sOutput += "\t"; - sOutput += sTimeStamp; - - // if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sProject ) ) ) - aOutput.WriteLine( sOutput ); - } - - if ( bCreateNew ) { - pResData->sText[ sCur ] = ""; - pResData->sHelpText[ sCur ] = ""; - pResData->sQuickHelpText[ sCur ]= ""; - pResData->sTitle[ sCur ] = ""; - } - } - } - FillInFallbacks( pResData ); - if ( pResData->pStringList ) { - ByteString sList( "stringlist" ); - WriteExportList( pResData, pResData->pStringList, sList, bCreateNew ); - if ( bCreateNew ) - pResData->pStringList = 0; - } - if ( pResData->pFilterList ) { - ByteString sList( "filterlist" ); - WriteExportList( pResData, pResData->pFilterList, sList, bCreateNew ); - if ( bCreateNew ) - pResData->pFilterList = 0; - } - if ( pResData->pItemList ) { - ByteString sList( "itemlist" ); - WriteExportList( pResData, pResData->pItemList, sList, bCreateNew ); - if ( bCreateNew ) - pResData->pItemList = 0; - } - if ( pResData->pPairedList ) { - ByteString sList( "pairedlist" ); - WriteExportList( pResData, pResData->pPairedList, sList, bCreateNew ); - if ( bCreateNew ) - pResData->pItemList = 0; - } - if ( pResData->pUIEntries ) { - ByteString sList( "uientries" ); - WriteExportList( pResData, pResData->pUIEntries, sList, bCreateNew ); - if ( bCreateNew ) - pResData->pUIEntries = 0; - } - return TRUE; -} -ByteString Export::GetPairedListID( const ByteString& sText ){ -// < "STRING" ; IDENTIFIER ; > ; - ByteString sIdent = sText.GetToken( 1, ';' ); - sIdent.ToUpperAscii(); - while( sIdent.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - sIdent.EraseTrailingChars( ' ' ); - sIdent.EraseLeadingChars( ' ' ); - return sIdent; -} -ByteString Export::GetPairedListString( const ByteString& sText ){ -// < "STRING" ; IDENTIFIER ; > ; - ByteString sString = sText.GetToken( 0, ';' ); - while( sString.SearchAndReplace( "\t", " " ) != STRING_NOTFOUND ) {}; - sString.EraseTrailingChars( ' ' ); - ByteString s1 = sString.Copy( sString.Search( '\"' )+1 ); - sString = s1.Copy( 0 , s1.SearchBackward( '\"' ) ); - sString.EraseTrailingChars( ' ' ); - sString.EraseLeadingChars( ' ' ); - return sString; -} -ByteString Export::StripList( const ByteString& sText ){ - ByteString s1 = sText.Copy( sText.Search( '\"' ) + 1 ); - return s1.Copy( 0 , s1.SearchBackward( '\"' ) ); -} - -/*****************************************************************************/ -BOOL Export::WriteExportList( ResData *pResData, ExportList *pExportList, - const ByteString &rTyp, BOOL bCreateNew ) -/*****************************************************************************/ -{ - ByteString sGID = pResData->sGId; - if ( !sGID.Len()) - sGID = pResData->sId; - else { - sGID += "."; - sGID += pResData->sId; - sGID.EraseTrailingChars( '.' ); - } - - ByteString sTimeStamp( Export::GetTimeStamp()); - ByteString sCur; - for ( ULONG i = 0; pExportList != NULL && i < pExportList->Count(); i++ ) { - ExportListEntry *pEntry = pExportList->GetObject( i ); - // mandatory for export: german and eng. and/or enus - //ByteString a("Export::WriteExportList::pEntry"); - //Export::DumpMap( a, *pEntry ); - - ByteString sLID( ByteString::CreateFromInt64( i + 1 )); - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - if ( //1 ) - //(*pEntry)[ ByteString("de") ].Len() && - (*pEntry)[ SOURCE_LANGUAGE ].Len() ) - //|| - // (*pEntry)[ ByteString("en") ].Len())) - { - if ( bEnableExport ) - { - ByteString sText((*pEntry)[ SOURCE_LANGUAGE ] ); - - // Strip PairList Line String - if( rTyp.EqualsIgnoreCaseAscii("pairedlist") ){ - sLID = GetPairedListID( sText ); - if ((*pEntry)[ sCur ].Len()) - sText = (*pEntry)[ sCur ]; - sText = GetPairedListString( sText ); - } - else{ - //if ((*pEntry)[ sCur ].Len()){ - // if( sCur.EqualsIgnoreCaseAscii("de") ){ - // sText = StripList( (*pEntry)[ sCur ] ); - // } - // else - sText = StripList( (*pEntry)[ sCur ] ); - if( sText == "\\\"" ) - sText = "\""; - //} - } - - ByteString sOutput( sProject ); sOutput += "\t"; - if ( sRoot.Len()) - sOutput += sActFileName; - sOutput += "\t0\t"; - sOutput += rTyp; sOutput += "\t"; - sOutput += sGID; sOutput += "\t"; - sOutput += sLID; sOutput += "\t\t"; - sOutput += pResData->sPForm; sOutput += "\t0\t"; - sOutput += sCur; sOutput += "\t"; - - sOutput += sText; sOutput += "\t\t\t\t"; - sOutput += sTimeStamp; - - //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( sProject ) ) ) - aOutput.WriteLine( sOutput ); - - } - } - } - if ( bCreateNew ) - delete [] pEntry; - } - if ( bCreateNew ) - delete pExportList; - - return TRUE; -} - -/*****************************************************************************/ -ByteString Export::FullId() -/*****************************************************************************/ -{ - ByteString sFull; - if ( nLevel > 1 ) { - sFull = aResStack.GetObject( 0 )->sId; - for ( USHORT i = 1; i < nLevel - 1; i++ ) { - ByteString sToAdd = aResStack.GetObject( i )->sId; - if ( sToAdd.Len()) { - sFull += "."; - sFull += sToAdd; - } - } - } - if ( sFull.Len() > 255 ) { - ByteString sError( "GroupId > 255 chars" ); - printf("GroupID = %s\n",sFull.GetBuffer()); - yyerror( sError.GetBufferAccess()); - sError.ReleaseBufferAccess(); - } - - return sFull; -} - -/*****************************************************************************/ -void Export::InsertListEntry( const ByteString &rText, const ByteString &rLine ) -/*****************************************************************************/ -{ - ResData *pResData = aResStack.GetObject( nLevel-1 ); - - ExportList *pList = NULL; - if ( nList == LIST_STRING ) { - pList = pResData->pStringList; - if ( !pList ) { - pResData->pStringList = new ExportList(); - pList = pResData->pStringList; - nListIndex = 0; - } - } - else if ( nList == LIST_FILTER ) { - pList = pResData->pFilterList; - if ( !pList ) { - pResData->pFilterList = new ExportList(); - pList = pResData->pFilterList; - nListIndex = 0; - } - } - else if ( nList == LIST_ITEM ) { - pList = pResData->pItemList; - if ( !pList ) { - pResData->pItemList = new ExportList(); - pList = pResData->pItemList; - nListIndex = 0; - } - } - else if ( nList == LIST_PAIRED ) { - pList = pResData->pPairedList; - if ( !pList ) { - pResData->pPairedList = new ExportList(); - pList = pResData->pPairedList; - nListIndex = 0; - } - } - else if ( nList == LIST_UIENTRIES ) { - pList = pResData->pUIEntries; - if ( !pList ) { - pResData->pUIEntries = new ExportList(); - pList = pResData->pUIEntries; - nListIndex = 0; - } - } - else - return; - - if ( nListIndex + 1 > pList->Count()) { - ExportListEntry *pNew = new ExportListEntry(); - (*pNew)[ LIST_REFID ] = ByteString::CreateFromInt32( REFID_NONE ); - pList->Insert( pNew, LIST_APPEND ); - } - ExportListEntry *pCurEntry = pList->GetObject( nListIndex ); - - // For paired list use the line to set proper lid - if( nList == LIST_PAIRED ){ - (*pCurEntry)[ nListLang ] = rLine; - }else - (*pCurEntry)[ nListLang ] = rText; - - // Remember en-US fallback string, so each list has the same amount of elements - //if ( nListLang.EqualsIgnoreCaseAscii("en-US") ) { - if ( Export::isSourceLanguage( nListLang ) ) { - if( nList == LIST_PAIRED ){ - const ByteString sPlist("pairedlist"); - ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sId , GetPairedListID( rLine ) , sFilename ); - pResData->addFallbackData( sKey , rText ); - } - // new fallback - else{ - const ByteString sPlist("list"); - ByteString a( pResData->sGId ); - a.Append( "." ); - a.Append( pResData->sId ); - sal_Int64 x = nListIndex+1; - ByteString b( ByteString::CreateFromInt64( x ) ); - ByteString sKey = MergeDataFile::CreateKey( sPlist , a , b , sFilename ); - pResData->addFallbackData( sKey , rText ); - } - // new fallback - } - - //if ( nListLang.EqualsIgnoreCaseAscii("en-US") ) { - if ( Export::isSourceLanguage( nListLang ) ) { - if( nList == LIST_PAIRED ){ - (*pCurEntry)[ SOURCE_LANGUAGE ] = rLine; - } - else - (*pCurEntry)[ SOURCE_LANGUAGE ] = rLine; - - pList->NewSourceLanguageListEntry(); - } - - //printf("Export::InsertListEntry ResData.id = %s ResData.ListData = %s\n",pResData->sId.GetBuffer() ,(*pCurEntry)[ nListLang ].GetBuffer()); - nListIndex++; -} - -/*****************************************************************************/ -void Export::CleanValue( ByteString &rValue ) -/*****************************************************************************/ -{ - while ( rValue.Len()) { - if (( rValue.GetChar( 0 ) == ' ' ) || ( rValue.GetChar( 0 ) == '\t' )) - rValue = rValue.Copy( 1 ); - else - break; - } - - if ( rValue.Len()) { - for ( USHORT i = rValue.Len() - 1; i > 0; i-- ) { - if (( rValue.GetChar( i ) == ' ' ) || ( rValue.GetChar( i ) == '\t' ) || - ( rValue.GetChar( i ) == '\n' ) || ( rValue.GetChar( i ) == ';' ) || - ( rValue.GetChar( i ) == '{' ) || ( rValue.GetChar( i ) == '\\' ) || - ( rValue.GetChar( i ) == '\r' )) - rValue.Erase( i ); - else - break; - } - } -} - - -/*****************************************************************************/ -ByteString Export::GetText( const ByteString &rSource, int nToken ) -/*****************************************************************************/ -#define TXT_STATE_NON 0x000 -#define TXT_STATE_TEXT 0x001 -#define TXT_STATE_MACRO 0x002 -{ - ByteString sReturn; - switch ( nToken ) { - case TEXTLINE: - case LONGTEXTLINE: { - ByteString sTmp( rSource.Copy( rSource.Search( "=" ))); - CleanValue( sTmp ); - sTmp.EraseAllChars( '\n' ); - sTmp.EraseAllChars( '\r' ); - - while ( sTmp.SearchAndReplace( "\\\\\"", "-=<[BSlashBSlashHKom]>=-\"" ) - != STRING_NOTFOUND ) {}; - while ( sTmp.SearchAndReplace( "\\\"", "-=<[Hochkomma]>=-" ) - != STRING_NOTFOUND ) {}; - while ( sTmp.SearchAndReplace( "\\", "-=<[0x7F]>=-" ) - != STRING_NOTFOUND ) {}; - while ( sTmp.SearchAndReplace( "\\0x7F", "-=<[0x7F]>=-" ) - != STRING_NOTFOUND ) {}; - - USHORT nStart = 0; - USHORT nState = TXT_STATE_MACRO; - - nState = TXT_STATE_TEXT; - nStart = 1; - - - for ( USHORT i = nStart; i < sTmp.GetTokenCount( '\"' ); i++ ) { - ByteString sToken = sTmp.GetToken( i, '\"' ); - if ( sToken.Len()) { - if ( nState == TXT_STATE_TEXT ) { - sReturn += sToken; - nState = TXT_STATE_MACRO; - } - else { - while( sToken.SearchAndReplace( "\t", " " ) != - STRING_NOTFOUND ) {}; - while( sToken.SearchAndReplace( " ", " " ) != - STRING_NOTFOUND ) {}; - sToken.EraseLeadingChars( ' ' ); - sToken.EraseTrailingChars( ' ' ); - if ( sToken.Len()) { - sReturn += "\\\" "; - sReturn += sToken; - sReturn += " \\\""; - } - nState = TXT_STATE_TEXT; - } - } - } - - while ( sReturn.SearchAndReplace( "-=<[0x7F]>=-", "" ) - != STRING_NOTFOUND ) {}; - while ( sReturn.SearchAndReplace( "-=<[Hochkomma]>=-", "\"" ) - != STRING_NOTFOUND ) {}; - while ( sReturn.SearchAndReplace( "-=<[BSlashBSlashHKom]>=-", "\\\\" ) - != STRING_NOTFOUND ) {}; - - - while ( sReturn.SearchAndReplace( "\\\\", "-=<[BSlashBSlash]>=-" ) - != STRING_NOTFOUND ) {}; - while ( sReturn.SearchAndReplace( "-=<[BSlashBSlash]>=-", "\\" ) - != STRING_NOTFOUND ) {}; - - } - break; - } - return sReturn; -} - -/*****************************************************************************/ -void Export::WriteToMerged( const ByteString &rText , bool bSDFContent ) -/*****************************************************************************/ -{ - static ByteString SLASH ('\\'); - static ByteString RETURN ('\n'); - //printf("%s\n",rText.GetBuffer() ); - - #if 0 - // statement has no effect - if( pParseQueue->bMflag && !bSDFContent ) pParseQueue->bMflag; - #endif - - if ( !bDontWriteOutput || !bUnmerge ) { - ByteString sText( rText ); - while ( sText.SearchAndReplace( " \n", "\n" ) != STRING_NOTFOUND ) {}; - if( pParseQueue->bNextIsM && bSDFContent && sText.Len() > 2 ){ - for( USHORT n = 0 ; n < sText.Len() ; n++ ){ - if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ - sText.Insert('\\' , n++ ); - - } - } - } - else if( pParseQueue->bLastWasM && sText.Len() > 2 ){ - for( USHORT n = 0 ; n < sText.Len() ; n++ ){ - if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ - sText.Insert('\\' , n++ ); - } - if( sText.GetChar( n ) == '\n' )pParseQueue->bMflag=true; - } - } - else if( pParseQueue->bCurrentIsM && bSDFContent && sText.Len() > 2 ){ - for( USHORT n = 0 ; n < sText.Len() ; n++ ){ - if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ - sText.Insert('\\' , n++ ); - pParseQueue->bMflag=true; - } - } - } - else if( pParseQueue->bMflag ){ - for( USHORT n = 1 ; n < sText.Len() ; n++ ){ - if( sText.GetChar( n ) == '\n' && sText.GetChar( n-1 ) != '\\'){ - sText.Insert('\\' , n++ ); - } - } - } - for ( USHORT i = 0; i < sText.Len(); i++ ) { - if ( sText.GetChar( i ) != '\n' ){ - aOutput.Write( ByteString( sText.GetChar( i )).GetBuffer(), 1 ); - - } - else{ - aOutput.WriteLine( ByteString()); - } - - } - } -} - -/*****************************************************************************/ -void Export::ConvertMergeContent( ByteString &rText ) -/*****************************************************************************/ -{ - BOOL bNoOpen = ( rText.Search( "\\\"" ) != 0 ); - ByteString sClose( rText.Copy( rText.Len() - 2 )); - BOOL bNoClose = ( sClose != "\\\"" ); - ByteString sNew; - for ( USHORT i = 0; i < rText.Len(); i++ ) { - ByteString sChar( rText.GetChar( i )); - if ( sChar == "\\" ) { - if (( i + 1 ) < rText.Len()) { - ByteString sNext( rText.GetChar( i + 1 )); - if ( sNext == "\"" ) { - sChar = "\""; - i++; - } - else if ( sNext == "n" ) { - sChar = "\\n"; - i++; - } - else if ( sNext == "t" ) { - sChar = "\\t"; - i++; - } - else if ( sNext == "\'" ) { - sChar = "\\\'"; - i++; - } - else - sChar = "\\\\"; - } - else { - sChar = "\\\\"; - } - } - else if ( sChar == "\"" ) { - sChar = "\\\""; - } - else if ( sChar == "" ) { - sChar = "\\0x7F"; - } - sNew += sChar; - } - - rText = sNew; - - if ( bNoOpen ) { - ByteString sTmp( rText ); - rText = "\""; - rText += sTmp; - } - if ( bNoClose ) - rText += "\""; -} - -/*****************************************************************************/ -BOOL Export::PrepareTextToMerge( ByteString &rText, USHORT nTyp, - ByteString &nLangIndex, ResData *pResData ) -/*****************************************************************************/ -{ - // position to merge in: - USHORT nStart = 0; - USHORT nEnd = 0; - ByteString sOldId = pResData->sId; - ByteString sOldGId = pResData->sGId; - ByteString sOldTyp = pResData->sResTyp; - - ByteString sOrigText( rText ); - - switch ( nTyp ) { - case LIST_STRING : - case LIST_UIENTRIES : - case LIST_FILTER : - case LIST_PAIRED: - case LIST_ITEM : - { - if ( bUnmerge ) - return TRUE; - - ExportList *pList = NULL; - switch ( nTyp ) { - case LIST_STRING : { - pResData->sResTyp = "stringlist"; - pList = pResData->pStringList; - } - break; - case LIST_UIENTRIES : { - pResData->sResTyp = "uientries"; - pList = pResData->pUIEntries; - } - break; - case LIST_FILTER : { - pResData->sResTyp = "filterlist"; - pList = pResData->pFilterList; - } - break; - case LIST_ITEM : { - pResData->sResTyp = "itemlist"; - pList = pResData->pItemList; - } - break; - case LIST_PAIRED : { - pResData->sResTyp = "pairedlist"; - pList = pResData->pPairedList; - } - break; - - } - if ( pList ) { - ExportListEntry *pCurEntry = pList->GetObject( nListIndex - 1 ); - if ( pCurEntry ) { - //printf("%s\n",Export::DumpMap( "pCurEntry", *pCurEntry ).GetBuffer() ); - //ByteString a("pCurEntry"); - //Export::DumpMap( a , *pCurEntry ); - rText = (*pCurEntry)[ SOURCE_LANGUAGE ]; - if( nTyp == LIST_PAIRED ){ - pResData->addMergedLanguage( nLangIndex ); - } - } - } - - nStart = rText.Search( "\"" ); - if ( nStart == STRING_NOTFOUND ) { - rText = sOrigText; - return FALSE; - } - - BOOL bFound = FALSE; - for ( nEnd = nStart + 1; nEnd < rText.Len() && !bFound; nEnd++ ) { - if ( rText.GetChar( nEnd ) == '\"' ) - bFound = TRUE; - } - if ( !bFound ) { - rText = sOrigText; - return FALSE; - } - - nEnd --; - sLastListLine = rText; - if (( sLastListLine.Search( ">" ) != STRING_NOTFOUND ) && - ( sLastListLine.Search( "<" ) == STRING_NOTFOUND )) - { - ByteString sTmp = sLastListLine; - sLastListLine = "<"; - sLastListLine += sTmp; - } - if ( pResData->sResTyp.EqualsIgnoreCaseAscii( "pairedlist" ) ){ - pResData->sId = GetPairedListID( sLastListLine ); - } - else pResData->sId = ByteString::CreateFromInt32( nListIndex ); - - if ( pResData->sGId.Len()) - pResData->sGId += "."; - pResData->sGId += sOldId; - nTyp = STRING_TYP_TEXT; - } - break; - case STRING_TYP_TEXT : - case STRING_TYP_HELPTEXT : - case STRING_TYP_QUICKHELPTEXT : - case STRING_TYP_TITLE : - { - /*if ( bUnmerge ) { - if (( nLangIndex != ByteString("de") ) && - ( nLangIndex != ByteString("en-US") )) - { - bDontWriteOutput = TRUE; - } - return TRUE; - }*/ - - nStart = rText.Search( "=" ); - if ( nStart == STRING_NOTFOUND ) { - rText = sOrigText; - return FALSE; - } - - nStart++; - BOOL bFound = FALSE; - while(( nStart < rText.Len()) && !bFound ) { - if (( rText.GetChar( nStart ) != ' ' ) && ( rText.GetChar( nStart ) != '\t' )) - bFound = TRUE; - else - nStart ++; - } - - // no start position found - if ( !bFound ) { - rText = sOrigText; - return FALSE; - } - - // position to end mergeing in - nEnd = rText.Len() - 1; - bFound = FALSE; - - while (( nEnd > nStart ) && !bFound ) { - if (( rText.GetChar( nEnd ) != ' ' ) && ( rText.GetChar( nEnd ) != '\t' ) && - ( rText.GetChar( nEnd ) != '\n' ) && ( rText.GetChar( nEnd ) != ';' ) && - ( rText.GetChar( nEnd ) != '{' ) && ( rText.GetChar( nEnd ) != '\\' )) - { - bFound = TRUE; - } - else - nEnd --; - } - } - break; - } - - // search for merge data - if ( !pMergeDataFile ){ - pMergeDataFile = new MergeDataFile( sMergeSrc, sFile , bErrorLog, aCharSet);//, bUTF8 ); - - // Init Languages - ByteString sTmp = Export::sLanguages; - if( sTmp.ToUpperAscii().Equals("ALL") ) - SetLanguages( pMergeDataFile->GetLanguages() ); - else if( !isInitialized )InitLanguages(); - - } -// printf("*************DUMPING****************\n"); -// printf("%s\n",pMergeDataFile->Dump().GetBuffer()); -// printf("*************DUMPING****************\n"); - -// printf("Dumping ResData\n"); -// pResData->Dump(); - PFormEntrys *pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); - //printf("Dumping pEntrys\n"); - //if( pEntrys ) pEntrys->Dump(); - pResData->sId = sOldId; - pResData->sGId = sOldGId; - pResData->sResTyp = sOldTyp; - - if ( !pEntrys ) { - rText = sOrigText; - return FALSE; // no data found - } - - ByteString sContent; - pEntrys->GetText( sContent, nTyp, nLangIndex ); - //if ( !sContent.Len() && ( ! nLangIndex.EqualsIgnoreCaseAscii("en-US") )) { - if ( !sContent.Len() && ( ! Export::isSourceLanguage( nLangIndex ) )) { - rText = sOrigText; - return FALSE; // no data found - } - - //if ( nLangIndex.EqualsIgnoreCaseAscii("en-US") ) { - if ( Export::isSourceLanguage( nLangIndex ) ) { - return FALSE; - } - - ByteString sPostFix( rText.Copy( ++nEnd )); - rText.Erase( nStart ); - - //ConvertMergeContent( sContent, nTyp ); - ConvertMergeContent( sContent ); - - - - //printf("Merged %s\n",nLangIndex.GetBuffer()); - // merge new res. in text line - rText += sContent; - rText += sPostFix; - - return TRUE; -} - -/*****************************************************************************/ -void Export::MergeRest( ResData *pResData, USHORT nMode ) -/*****************************************************************************/ -{ - //if ( bUnmerge ) { return;} - - //pResData->Dump(); - - if ( !pMergeDataFile ){ - pMergeDataFile = new MergeDataFile( sMergeSrc, sFile ,bErrorLog, aCharSet);//, bUTF8 ); - - // Init Languages - ByteString sTmp = Export::sLanguages; - if( sTmp.ToUpperAscii().Equals("ALL") ) - SetLanguages( pMergeDataFile->GetLanguages() ); - else if( !isInitialized )InitLanguages(); - - } - switch ( nMode ) { - case MERGE_MODE_NORMAL : { - PFormEntrys *pEntry = pMergeDataFile->GetPFormEntrys( pResData ); - - bool bWriteNoSlash = false; - if ( pEntry && pResData->bText ) { - - BOOL bAddSemikolon = FALSE; - BOOL bFirst = TRUE; - ByteString sCur; - ByteString sTmp = Export::sLanguages; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sText; - BOOL bText = pEntry->GetText( sText, STRING_TYP_TEXT, sCur , TRUE ); - if ( bText && sText.Len() && sText != "-" ) { - ByteString sOutput; - if ( bNextMustBeDefineEOL) { - if ( bFirst ) - sOutput += "\t\\\n"; - else - sOutput += ";\t\\\n"; - } - bFirst=FALSE; - sOutput += "\t"; - sOutput += pResData->sTextTyp; - //if ( !sCur.EqualsIgnoreCaseAscii("en-US")) { - if ( ! Export::isSourceLanguage( sCur ) ) { - sOutput += "[ "; - sOutput += sCur; - sOutput += " ] "; - } - sOutput += "= "; - ConvertMergeContent( sText ); - sOutput += sText; - - if ( bDefine && bWriteNoSlash ) - sOutput += ";\n"; - - if ( bDefine ) - sOutput += ";\\\n"; - else if ( !bNextMustBeDefineEOL ) - sOutput += ";\n"; - else - bAddSemikolon = TRUE; - for ( USHORT j = 1; j < nLevel; j++ ) - sOutput += "\t"; - WriteToMerged( sOutput , true ); - } - } - - - if ( bAddSemikolon ) { - ByteString sOutput( ";" ); - WriteToMerged( sOutput , false ); - } - } - - if ( pEntry && pResData->bQuickHelpText ) { - BOOL bAddSemikolon = FALSE; - BOOL bFirst = TRUE; - ByteString sCur; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sText; - BOOL bText = pEntry->GetText( sText, STRING_TYP_QUICKHELPTEXT, sCur, TRUE ); - if ( bText && sText.Len() && sText != "-" ) { - ByteString sOutput; - if ( bNextMustBeDefineEOL) { - if ( bFirst ) - sOutput += "\t\\\n"; - else - sOutput += ";\t\\\n"; - } - bFirst=FALSE; - sOutput += "\t"; - sOutput += "QuickHelpText"; - //if ( !sCur.EqualsIgnoreCaseAscii("en-US") ) { - if ( ! Export::isSourceLanguage( sCur ) ) { - sOutput += "[ "; - sOutput += sCur; - sOutput += " ] "; - } - sOutput += "= "; - ConvertMergeContent( sText ); - sOutput += sText; - if ( bDefine ) - sOutput += ";\\\n"; - else if ( !bNextMustBeDefineEOL ) - sOutput += ";\n"; - else - bAddSemikolon = TRUE; - for ( USHORT j = 1; j < nLevel; j++ ) - sOutput += "\t"; - WriteToMerged( sOutput ,true ); - } - } - if ( bAddSemikolon ) { - ByteString sOutput( ";" ); - WriteToMerged( sOutput , false ); - } - } - - if ( pEntry && pResData->bTitle ) { - BOOL bAddSemikolon = FALSE; - BOOL bFirst = TRUE; - ByteString sCur; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sText; - BOOL bText = pEntry->GetText( sText, STRING_TYP_TITLE, sCur, TRUE ); - if ( bText && sText.Len() && sText != "-" ) { - ByteString sOutput; - if ( bNextMustBeDefineEOL) { - if ( bFirst ) - sOutput += "\t\\\n"; - else - sOutput += ";\t\\\n"; - } - bFirst=FALSE; - sOutput += "\t"; - sOutput += "Title"; - //if ( !sCur.EqualsIgnoreCaseAscii("en-US") ) { - if ( ! Export::isSourceLanguage( sCur ) ) { - sOutput += "[ "; - sOutput += sCur; - sOutput += " ] "; - } - sOutput += "= "; - ConvertMergeContent( sText ); - sOutput += sText; - if ( bDefine ) - sOutput += ";\\\n"; - else if ( !bNextMustBeDefineEOL ) - sOutput += ";\n"; - else - bAddSemikolon = TRUE; - for ( USHORT j = 1; j < nLevel; j++ ) - sOutput += "\t"; - WriteToMerged( sOutput ,true ); - } - } - if ( bAddSemikolon ) { - ByteString sOutput( ";" ); - WriteToMerged( sOutput ,false); - } - } - // Merge Lists - - if ( pResData->bList ) { - //printf("Dumping ResData\n"); - //pResData->Dump(); - - bool bPairedList = false; - ByteString sOldId = pResData->sId; - ByteString sOldGId = pResData->sGId; - ByteString sOldTyp = pResData->sResTyp; - if ( pResData->sGId.Len()) - pResData->sGId += "."; - pResData->sGId += sOldId; - ByteString sSpace; - for ( USHORT i = 1; i < nLevel-1; i++ ) - sSpace += "\t"; - for ( USHORT nT = LIST_STRING; nT <= LIST_UIENTRIES; nT++ ) { - ExportList *pList = NULL; - switch ( nT ) { - case LIST_STRING : pResData->sResTyp = "stringlist"; pList = pResData->pStringList; bPairedList = false; break; - case LIST_FILTER : pResData->sResTyp = "filterlist"; pList = pResData->pFilterList; bPairedList = false; break; - case LIST_UIENTRIES : pResData->sResTyp = "uientries"; pList = pResData->pUIEntries;bPairedList = false; break; - case LIST_ITEM : pResData->sResTyp = "itemlist"; pList = pResData->pItemList; bPairedList = false; break; - case LIST_PAIRED : pResData->sResTyp = "pairedlist"; pList = pResData->pPairedList; bPairedList = true; break; - } - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - USHORT nIdx = 1; - - // Set matching pairedlist identifier - if( bPairedList && pResData->pPairedList && ( nIdx == 1 ) ){ - ExportListEntry* pListE = ( ExportListEntry* ) pResData->pPairedList->GetObject( nIdx-1 ); - pResData->sId = GetPairedListID ( (*pListE)[ SOURCE_LANGUAGE ] ); - } - else - pResData->sId = ByteString("1"); - - PFormEntrys *pEntrys; - ULONG nLIndex = 0; - ULONG nMaxIndex = 0; - if ( pList ) - nMaxIndex = pList->GetSourceLanguageListEntryCount(); - pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); - while( pEntrys && ( nLIndex < nMaxIndex )) { - //printf("Lang %s, List Index %d\n",sCur.GetBuffer(),(int)nLIndex); - ByteString sText; - BOOL bText; - bText = pEntrys->GetText( sText, STRING_TYP_TEXT, sCur, TRUE ); - if( !bText ) - bText = pEntrys->GetText( sText , STRING_TYP_TEXT, SOURCE_LANGUAGE , FALSE ); - - // Use fallback, if data is missing in sdf file - //if( !bText && pResData->sResTyp.Equals( "pairedlist" ) ){ - if( !bText && bPairedList ){ - if( pResData->isMerged( sCur ) ) break; - const ByteString sPlist("pairedlist"); - ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sGId , pResData->sId , sFilename ); - bText = pResData->getFallbackData( sKey , sText ); - }else if ( !bText ){// new fallback - if( pResData->isMerged( sCur ) ) break; - const ByteString sPlist("list"); - ByteString sKey = MergeDataFile::CreateKey( sPlist , pResData->sGId , pResData->sId , sFilename ); - bText = pResData->getFallbackData( sKey , sText ); - } // new fallback - - if ( bText && sText.Len()) { - //if( pEntrys ) pEntrys->Dump(); - if ( nIdx == 1 ) { - ByteString sHead; - if ( bNextMustBeDefineEOL ) - sHead = "\\\n\t"; - sHead += sSpace; - switch ( nT ) { - case LIST_STRING : sHead += "StringList "; break; - case LIST_FILTER : sHead += "FilterList "; break; - case LIST_ITEM : sHead += "ItemList "; break; - case LIST_PAIRED : sHead += "PairedList "; break; - case LIST_UIENTRIES : sHead += "UIEntries "; break; - } - sHead += "[ "; - sHead += sCur; - sHead += " ] "; - //} - if ( bDefine || bNextMustBeDefineEOL ) { - sHead += "= \\\n"; - sHead += sSpace; - sHead += "\t{\\\n\t"; - } - else { - sHead += "= \n"; - sHead += sSpace; - sHead += "\t{\n\t"; - } - WriteToMerged( sHead , true); - } - ByteString sLine; - if ( pList && pList->GetObject( nLIndex )) - sLine = ( *pList->GetObject( nLIndex ))[ SOURCE_LANGUAGE ]; - if ( !sLine.Len()) - sLine = sLastListLine; - - if ( sLastListLine.Search( "<" ) != STRING_NOTFOUND ) { - if (( nT != LIST_UIENTRIES ) && - (( sLine.Search( "{" ) == STRING_NOTFOUND ) || - ( sLine.Search( "{" ) >= sLine.Search( "\"" ))) && - (( sLine.Search( "<" ) == STRING_NOTFOUND ) || - ( sLine.Search( "<" ) >= sLine.Search( "\"" )))) - { - sLine.SearchAndReplace( "\"", "< \"" ); - } - } - - USHORT nStart, nEnd; - nStart = sLine.Search( "\"" ); - - ByteString sPostFix; - if( !bPairedList ){ - nEnd = sLine.SearchBackward( '\"' ); - sPostFix = ByteString( sLine.Copy( ++nEnd )); - sLine.Erase( nStart ); - } - - - ConvertMergeContent( sText ); - - // merge new res. in text line - if( bPairedList ){ - sLine = MergePairedList( sLine , sText ); - } - else{ - sLine += sText; - sLine += sPostFix; - } - - ByteString sText1( "\t" ); - sText1 += sLine; - if ( bDefine || bNextMustBeDefineEOL ) - sText1 += " ;\\\n"; - else - sText1 += " ;\n"; - sText1 += sSpace; - sText1 += "\t"; - //printf("Writing '%s'\n",sText1.GetBuffer()); - WriteToMerged( sText1 ,true ); - - // Set matching pairedlist identifier - if ( bPairedList ){ - nIdx++; - ExportListEntry* pListE = ( ExportListEntry* ) pResData->pPairedList->GetObject( ( nIdx ) -1 ); - if( pListE ){ - pResData->sId = GetPairedListID ( (*pListE)[ SOURCE_LANGUAGE ] ); - } - } - else - pResData->sId = ByteString::CreateFromInt32( ++nIdx ); - } - else - break; - nLIndex ++; - PFormEntrys *oldEntry = pEntrys; - pEntrys = pMergeDataFile->GetPFormEntrys( pResData ); // <--- game over - if( !pEntrys ) - pEntrys = oldEntry; - } - if ( nIdx > 1 ) { - ByteString sFooter( sSpace.Copy( 1 )); - if ( bNextMustBeDefineEOL ) - sFooter += "};"; - else if ( !bDefine ) - sFooter += "};\n\t"; - else - sFooter += "\n\n"; - WriteToMerged( sFooter ,true ); - } - } - } - - pResData->sId = sOldId; - pResData->sGId = sOldGId; - pResData->sResTyp = sOldTyp; - } - } - break; - case MERGE_MODE_LIST : { - ExportList *pList = NULL; - switch ( nList ) { - // PairedList - case LIST_STRING : pList = pResData->pStringList; break; - case LIST_FILTER : pList = pResData->pFilterList; break; - case LIST_UIENTRIES : pList = pResData->pUIEntries; break; - case LIST_ITEM : pList = pResData->pItemList; break; - case LIST_PAIRED : pList = pResData->pPairedList; break; - - } - - nListIndex++; - ULONG nMaxIndex = 0; - if ( pList ) - nMaxIndex = pList->GetSourceLanguageListEntryCount(); - ByteString sLine; - if ( pList && pList->GetObject( nListIndex )) - sLine = ( *pList->GetObject( nListIndex ))[ SOURCE_LANGUAGE ]; - if ( !sLine.Len()) - sLine = sLastListLine; - - if ( sLastListLine.Search( "<" ) != STRING_NOTFOUND ) { - if (( nList != LIST_UIENTRIES ) && - (( sLine.Search( "{" ) == STRING_NOTFOUND ) || - ( sLine.Search( "{" ) >= sLine.Search( "\"" ))) && - (( sLine.Search( "<" ) == STRING_NOTFOUND ) || - ( sLine.Search( "<" ) >= sLine.Search( "\"" )))) - { - sLine.SearchAndReplace( "\"", "< \"" ); - } - } - - while( PrepareTextToMerge( sLine, nList, nListLang, pResData ) && ( nListIndex <= nMaxIndex )) { - ByteString sText( "\t" ); - sText += sLine; - sText += " ;"; - sText += "\n"; - for ( USHORT i = 0; i < nLevel; i++ ) - sText += "\t"; - WriteToMerged( sText ,false ); - nListIndex++; - if ( pList && pList->GetObject( nListIndex )) - sLine = ( *pList->GetObject( nListIndex ))[ SOURCE_LANGUAGE ]; - if ( !sLine.Len()) - sLine = sLastListLine; - sLine += " ;"; - } - } - break; - } - pParseQueue->bMflag = false; -} - -ByteString Export::MergePairedList( ByteString& sLine , ByteString& sText ){ -// < "xy" ; IDENTIFIER ; > - ByteString sPre = sLine.Copy( 0 , sLine.Search('\"') ); - ByteString sPost = sLine.Copy( sLine.SearchBackward('\"') + 1 , sLine.Len() ); - sPre.Append( sText ); - sPre.Append( sPost ); - return sPre; -} - -/*****************************************************************************/ -void Export::SetChildWithText() -/*****************************************************************************/ -{ - if ( aResStack.Count() > 1 ) { - for ( ULONG i = 0; i < aResStack.Count() - 1; i++ ) { - aResStack.GetObject( i )->bChildWithText = TRUE; - } - } -} - -void ParserQueue::Push( const QueueEntry& aEntry ){ -// printf("nTyp = %d ",aEntry.nTyp); - USHORT nLen = aEntry.sLine.Len(); - - if( !bStart ){ - aQueueCur->push( aEntry ); - if( nLen > 1 && aEntry.sLine.GetChar( nLen-1 ) == '\n' ) - bStart = true; - else if ( aEntry.nTyp != IGNOREDTOKENS ){ - if( nLen > 1 && ( aEntry.sLine.GetChar( nLen-1 ) == '\\') ){ - // Next is Macro - bCurrentIsM = true; - }else{ - // Next is no Macro - bCurrentIsM = false; - } - } - } - else{ - aQueueNext->push( aEntry ); - if( nLen > 1 && aEntry.sLine.GetChar( nLen-1 ) != '\n' ){ - if( nLen > 1 && ( aEntry.sLine.GetChar( nLen-1 ) == '\\') ){ - // Next is Macro - bNextIsM = true; - } - else{ - // Next is no Macro - bNextIsM = false; - } - }else if( nLen > 2 && aEntry.sLine.GetChar( nLen-1 ) == '\n' ){ - if( aEntry.nTyp != IGNOREDTOKENS ){ - if( nLen > 2 && ( aEntry.sLine.GetChar( nLen-2 ) == '\\') ){ - // Next is Macro - bNextIsM = true; - } - else{ - // Next is no Macro - bNextIsM = false; - } - } - // Pop current - Pop( *aQueueCur ); - bLastWasM = bCurrentIsM; - // next -> current - bCurrentIsM = bNextIsM; - aQref = aQueueCur; - aQueueCur = aQueueNext; - aQueueNext = aQref; - - } - - else{ - // Pop current - Pop( *aQueueCur ); - bLastWasM = bCurrentIsM; - // next -> current - bCurrentIsM = bNextIsM; - aQref = aQueueCur; - aQueueCur = aQueueNext; - aQueueNext = aQref; - } - } -} - -void ParserQueue::Close(){ - // Pop current - Pop( *aQueueCur ); - // next -> current - bLastWasM = bCurrentIsM; - bCurrentIsM = bNextIsM; - aQref = aQueueCur; - aQueueCur = aQueueNext; - aQueueNext = aQref; - bNextIsM = false; - Pop( *aQueueNext ); -}; -void ParserQueue::Pop( std::queue& aQueue ){ - while( !aQueue.empty() ){ - QueueEntry aEntry = aQueue.front(); - aQueue.pop(); - aExport.Execute( aEntry.nTyp , (char*) aEntry.sLine.GetBuffer() ); - } -} -ParserQueue::ParserQueue( Export& aExportObj ) - : - bCurrentIsM( false ), - bNextIsM( false ) , - bLastWasM( false ), - bMflag( false ) , - aExport( aExportObj ) , - bStart( false ) , - bStartNext( false ) -{ - aQueueNext = new std::queue; - aQueueCur = new std::queue; -} - - -ParserQueue::~ParserQueue(){ - if( aQueueNext ) delete aQueueNext; - if( aQueueCur ) delete aQueueCur; -} diff --git a/transex3/source/export2.cxx b/transex3/source/export2.cxx deleted file mode 100644 index 7815e80e033f..000000000000 --- a/transex3/source/export2.cxx +++ /dev/null @@ -1,741 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: export2.cxx,v $ - * $Revision: 1.43 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include "export.hxx" -#include "utf8conv.hxx" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -// -// class ResData(); -// - -/*****************************************************************************/ -ResData::~ResData() -/*****************************************************************************/ -{ - if ( pStringList ) { - // delete existing res. of type StringList - for ( ULONG i = 0; i < pStringList->Count(); i++ ) { - ExportListEntry* test = pStringList->GetObject( i ); - if( test != NULL ) delete test; - } - delete pStringList; - } - if ( pFilterList ) { - // delete existing res. of type FilterList - for ( ULONG i = 0; i < pFilterList->Count(); i++ ) { - ExportListEntry* test = pFilterList->GetObject( i ); - delete test; - } - delete pFilterList; - } - if ( pItemList ) { - // delete existing res. of type ItemList - for ( ULONG i = 0; i < pItemList->Count(); i++ ) { - ExportListEntry* test = pItemList->GetObject( i ); - delete test; - } - delete pItemList; - } - if ( pUIEntries ) { - // delete existing res. of type UIEntries - for ( ULONG i = 0; i < pUIEntries->Count(); i++ ) { - ExportListEntry* test = pUIEntries->GetObject( i ); - delete test; - } - delete pUIEntries; - } -} - -// -// class Export -// - -/*****************************************************************************/ -ByteString Export::sLanguages; -ByteString Export::sForcedLanguages; -//ByteString Export::sIsoCode99; -/*****************************************************************************/ - -void Export::DumpExportList( ByteString& sListName , ExportList& aList ){ - printf( "%s\n", sListName.GetBuffer() ); - ByteString l(""); - ExportListEntry* aEntry; - for( unsigned int x = 0; x < aList.Count() ; x++ ){ - aEntry = (ExportListEntry*) aList.GetObject( x ); - Export::DumpMap( l , *aEntry ); - } - printf("\n"); -} -ByteString Export::DumpMap( ByteString& sMapName , ByteStringHashMap& aMap ){ - ByteStringHashMap::const_iterator idbg; - ByteString sReturn; - - if( sMapName.Len() ) - printf("MapName %s\n", sMapName.GetBuffer()); - if( aMap.size() < 1 ) return ByteString(); - for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ - ByteString a( idbg->first ); - ByteString b( idbg->second ); - printf("[%s]= %s",a.GetBuffer(),b.GetBuffer()); - printf("\n"); - } - printf("\n"); - return sReturn; -} -/*****************************************************************************/ -void Export::SetLanguages( std::vector val ){ -/*****************************************************************************/ - aLanguages = val; - isInitialized = true; -} -/*****************************************************************************/ -std::vector Export::GetLanguages(){ -/*****************************************************************************/ - return aLanguages; -} -/*****************************************************************************/ -std::vector Export::GetForcedLanguages(){ -/*****************************************************************************/ - return aForcedLanguages; -} -std::vector Export::aLanguages = std::vector(); -std::vector Export::aForcedLanguages = std::vector(); - - -/*****************************************************************************/ -void Export::QuotHTMLXRM( ByteString &rString ) -/*****************************************************************************/ -{ - ByteString sReturn; - //BOOL bBreak = FALSE; - for ( USHORT i = 0; i < rString.Len(); i++ ) { - ByteString sTemp = rString.Copy( i ); - if ( sTemp.Search( ""; - i++; - } - } - - if ( i < rString.Len()) { - switch ( rString.GetChar( i )) { - case '<': - if( i+2 < rString.Len() && - (rString.GetChar( i+1 ) == 'b' || rString.GetChar( i+1 ) == 'B') && - rString.GetChar( i+2 ) == '>' ) - { - sReturn +=""; - i += 2; - } - else if( i+3 < rString.Len() && - rString.GetChar( i+1 ) == '/' && - (rString.GetChar( i+2 ) == 'b' || rString.GetChar( i+2 ) == 'B') && - rString.GetChar( i+3 ) == '>' ) - { - sReturn +=""; - i += 3; - } - else - sReturn += "<"; - break; - - case '>': - sReturn += ">"; - break; - - case '\"': - sReturn += """; - break; - - case '\'': - sReturn += "'"; - break; - - case '&': - if ((( i + 4 ) < rString.Len()) && - ( rString.Copy( i, 5 ) == "&" )) - sReturn += rString.GetChar( i ); - else - sReturn += "&"; - break; - - default: - sReturn += rString.GetChar( i ); - break; - } - } - } - rString = sReturn; -} -/*****************************************************************************/ -void Export::QuotHTML( ByteString &rString ) -/*****************************************************************************/ -{ - ByteString sReturn; - for ( USHORT i = 0; i < rString.Len(); i++ ) { - ByteString sTemp = rString.Copy( i ); - if ( sTemp.Search( ""; - i++; - } - } - if ( i < rString.Len()) { - switch ( rString.GetChar( i )) { - case '<': - sReturn += "<"; - break; - - case '>': - sReturn += ">"; - break; - - case '\"': - sReturn += """; - break; - - case '\'': - sReturn += "'"; - break; - - case '&': - if ((( i + 4 ) < rString.Len()) && - ( rString.Copy( i, 5 ) == "&" )) - sReturn += rString.GetChar( i ); - else - sReturn += "&"; - break; - - default: - sReturn += rString.GetChar( i ); - break; - } - } - } - rString = sReturn; -} - -void Export::RemoveUTF8ByteOrderMarker( ByteString &rString ){ - if( hasUTF8ByteOrderMarker( rString ) ) - rString.Erase( 0 , 3 ); -} - -bool Export::hasUTF8ByteOrderMarker( const ByteString &rString ){ - // Byte order marker signature - - const unsigned char c1 = 0xEF; - const unsigned char c2 = 0xBB; - const unsigned char c3 = 0xBF; - - const char bom[ 3 ] = { c1 , c2 , c3 }; - - return rString.Len() >= 3 && - rString.GetChar( 0 ) == bom[ 0 ] && - rString.GetChar( 1 ) == bom[ 1 ] && - rString.GetChar( 2 ) == bom[ 2 ] ; -} -bool Export::fileHasUTF8ByteOrderMarker( const ByteString &rString ){ - SvFileStream aFileIn( String( rString , RTL_TEXTENCODING_ASCII_US ) , STREAM_READ ); - ByteString sLine; - if( !aFileIn.IsEof() ) { - aFileIn.ReadLine( sLine ); - if( aFileIn.IsOpen() ) aFileIn.Close(); - return hasUTF8ByteOrderMarker( sLine ); - } - if( aFileIn.IsOpen() ) aFileIn.Close(); - return false; -} -void Export::RemoveUTF8ByteOrderMarkerFromFile( const ByteString &rFilename ){ - SvFileStream aFileIn( String( rFilename , RTL_TEXTENCODING_ASCII_US ) , STREAM_READ ); - ByteString sLine; - if( !aFileIn.IsEof() ) { - aFileIn.ReadLine( sLine ); - // Test header - if( hasUTF8ByteOrderMarker( sLine ) ){ - //cout << "UTF8 Header found!\n"; - DirEntry aTempFile = Export::GetTempFile(); - ByteString sTempFile = ByteString( aTempFile.GetFull() , RTL_TEXTENCODING_ASCII_US ); - SvFileStream aNewFile( String( sTempFile , RTL_TEXTENCODING_ASCII_US ) , STREAM_WRITE ); - // Remove header - RemoveUTF8ByteOrderMarker( sLine ); - //cout << "Copy stripped stuff to " << sTempFile.GetBuffer() << endl; - aNewFile.WriteLine( sLine ); - // Copy the rest - while( !aFileIn.IsEof() ){ - aFileIn.ReadLine( sLine ); - aNewFile.WriteLine( sLine ); - } - if( aFileIn.IsOpen() ) aFileIn.Close(); - if( aNewFile.IsOpen() ) aNewFile.Close(); - DirEntry aEntry( rFilename.GetBuffer() ); - //cout << "Removing file " << rFilename.GetBuffer() << "\n"; - aEntry.Kill(); - //cout << "Renaming file " << sTempFile.GetBuffer() << " to " << rFilename.GetBuffer() << "\n"; - DirEntry( sTempFile ).MoveTo( DirEntry( rFilename.GetBuffer() ) ); - } - } - if( aFileIn.IsOpen() ) aFileIn.Close(); -} - -// Merge it into source code! -//bool Export::isMergingGermanAllowed( const ByteString& rPrj ){ -// (void) rPrj; -// return true; -/* static ByteStringBoolHashMap aHash; - - if( aHash.find( rPrj ) != aHash.end() ){ - return aHash[ rPrj ]; - } - - ByteString sFile = Export::GetEnv( "SRC_ROOT" ) ; - sFile.Append("/"); - sFile.Append( rPrj ); - sFile.Append("/prj/l10n"); -#if defined(WNT) || defined(OS2) - sFile.SearchAndReplaceAll('/','\\'); -#endif - DirEntry aFlagfile( sFile ); - - aHash[ rPrj ] = !aFlagfile.Exists(); - return aHash[ rPrj ];*/ -//} -bool Export::CopyFile( const ByteString& source , const ByteString& dest ) -{ -// cout << "CopyFile( " << source.GetBuffer() << " , " << dest.GetBuffer() << " )\n"; - const int BUFFERSIZE = 8192; - char buf[ BUFFERSIZE ]; - - FILE* IN_FILE = fopen( source.GetBuffer() , "r" ); - FILE* OUT_FILE = fopen( dest.GetBuffer() , "w" ); - - if( IN_FILE == NULL ) - { - cerr << "Export::CopyFile WARNING: Could not open " << source.GetBuffer() << "\n"; - return false; - } - if( OUT_FILE == NULL ) - { - cerr << "Export::CopyFile WARNING: Could not open/create " << dest.GetBuffer() << " for writing\n"; - return false; - } - - while( fgets( buf , BUFFERSIZE , IN_FILE ) != NULL ) - { - if( fputs( buf , OUT_FILE ) == EOF ) - { - cerr << "Export::CopyFile WARNING: Write problems " << source.GetBuffer() << "\n"; - fclose( IN_FILE ); - fclose( OUT_FILE ); - return false; - } - } - if( ferror( IN_FILE ) ) - { - cerr << "Export::CopyFile WARNING: Read problems " << dest.GetBuffer() << "\n"; - fclose( IN_FILE ); - fclose( OUT_FILE ); - return false; - } - fclose ( IN_FILE ); - fclose ( OUT_FILE ); - - return true; -} - -/*****************************************************************************/ -void Export::UnquotHTML( ByteString &rString ) -/*****************************************************************************/ -{ - ByteString sReturn; - while ( rString.Len()) { - if ( rString.Copy( 0, 5 ) == "&" ) { - sReturn += "&"; - rString.Erase( 0, 5 ); - } - else if ( rString.Copy( 0, 4 ) == "<" ) { - sReturn += "<"; - rString.Erase( 0, 4 ); - } - else if ( rString.Copy( 0, 4 ) == ">" ) { - sReturn += ">"; - rString.Erase( 0, 4 ); - } - else if ( rString.Copy( 0, 6 ) == """ ) { - sReturn += "\""; - rString.Erase( 0, 6 ); - } - else if ( rString.Copy( 0, 6 ) == "'" ) { - sReturn += "\'"; - rString.Erase( 0, 6 ); - } - else { - sReturn += rString.GetChar( 0 ); - rString.Erase( 0, 1 ); - } - } - rString = sReturn; -} -bool Export::isSourceLanguage( const ByteString &sLanguage ) -{ - return !isAllowed( sLanguage ); -} -bool Export::isAllowed( const ByteString &sLanguage ){ - return ! ( sLanguage.EqualsIgnoreCaseAscii("en-US") ); -} -/*****************************************************************************/ -bool Export::LanguageAllowed( const ByteString &nLanguage ) -/*****************************************************************************/ -{ - return std::find( aLanguages.begin() , aLanguages.end() , nLanguage ) != aLanguages.end(); -} - -bool Export::isInitialized = false; - -/*****************************************************************************/ -void Export::InitLanguages( bool bMergeMode ){ -/*****************************************************************************/ - if( !isInitialized ){ - ByteString sTmp; - ByteStringBoolHashMap aEnvLangs; - for ( USHORT x = 0; x < sLanguages.GetTokenCount( ',' ); x++ ){ - sTmp = sLanguages.GetToken( x, ',' ).GetToken( 0, '=' ); - sTmp.EraseLeadingAndTrailingChars(); - if( bMergeMode && !isAllowed( sTmp ) ){} - else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) ){ - aLanguages.push_back( sTmp ); - } - } - InitForcedLanguages( bMergeMode ); - isInitialized = true; - } -} -/*****************************************************************************/ -void Export::InitForcedLanguages( bool bMergeMode ){ -/*****************************************************************************/ - ByteString sTmp; - ByteStringBoolHashMap aEnvLangs; - for ( USHORT x = 0; x < sForcedLanguages.GetTokenCount( ',' ); x++ ){ - sTmp = sForcedLanguages.GetToken( x, ',' ).GetToken( 0, '=' ); - sTmp.EraseLeadingAndTrailingChars(); - if( bMergeMode && isAllowed( sTmp ) ){} - else if( !( (sTmp.GetChar(0)=='x' || sTmp.GetChar(0)=='X') && sTmp.GetChar(1)=='-' ) ) - aForcedLanguages.push_back( sTmp ); - } -} - -/*****************************************************************************/ -ByteString Export::GetFallbackLanguage( const ByteString nLanguage ) -/*****************************************************************************/ -{ - ByteString sFallback=nLanguage; - GetIsoFallback( sFallback ); - return sFallback; -} - -void Export::replaceEncoding( ByteString& rString ) -{ -// ™ -> \u2122 - - for( xub_StrLen idx = 0; idx <= rString.Len()-8 ; idx++ ) - { - if( rString.GetChar( idx ) == '&' && - rString.GetChar( idx+1 ) == '#' && - rString.GetChar( idx+2 ) == 'x' && - rString.GetChar( idx+7 ) == ';' ) - { - ByteString sTmp = rString.Copy( 0 , idx ); - sTmp.Append( "\\u" ); - sTmp.Append( rString.GetChar( idx+3 ) ); - sTmp.Append( rString.GetChar( idx+4 ) ); - sTmp.Append( rString.GetChar( idx+5 ) ); - sTmp.Append( rString.GetChar( idx+6 ) ); - sTmp.Append( rString.Copy( idx+8 , rString.Len() ) ); - rString = sTmp; - } - } -} - -/*****************************************************************************/ -void Export::FillInFallbacks( ResData *pResData ) -/*****************************************************************************/ -{ - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - if( isAllowed( sCur ) ){ - ByteString nFallbackIndex = GetFallbackLanguage( sCur ); - if( nFallbackIndex.Len() ){ - if ( !pResData->sText[ sCur ].Len()) - pResData->sText[ sCur ] = - pResData->sText[ nFallbackIndex ]; - - if ( !pResData->sHelpText[ sCur ].Len()) - pResData->sHelpText[ sCur ] = - pResData->sHelpText[ nFallbackIndex ]; - - if ( !pResData->sQuickHelpText[ sCur ].Len()) - pResData->sQuickHelpText[ sCur ] = - pResData->sQuickHelpText[ nFallbackIndex ]; - - if ( !pResData->sTitle[ sCur ].Len()) - pResData->sTitle[ sCur ] = - pResData->sTitle[ nFallbackIndex ]; - - if ( pResData->pStringList ) - FillInListFallbacks( - pResData->pStringList, sCur, nFallbackIndex ); - - if ( pResData->pPairedList ) - FillInListFallbacks( - pResData->pPairedList, sCur, nFallbackIndex ); - - if ( pResData->pFilterList ) - FillInListFallbacks( - pResData->pFilterList, sCur, nFallbackIndex ); - - if ( pResData->pItemList ) - FillInListFallbacks( - pResData->pItemList, sCur, nFallbackIndex ); - - if ( pResData->pUIEntries ) - FillInListFallbacks( - pResData->pUIEntries, sCur, nFallbackIndex ); - } - } - } -} - -/*****************************************************************************/ -void Export::FillInListFallbacks( - ExportList *pList, const ByteString &nSource, const ByteString &nFallback ) -/*****************************************************************************/ -{ - - for ( ULONG i = 0; i < pList->Count(); i++ ) { - ExportListEntry *pEntry = pList->GetObject( i ); - if ( !( *pEntry )[ nSource ].Len()){ - ( *pEntry )[ nSource ] = ( *pEntry )[ nFallback ]; - ByteString x = ( *pEntry )[ nSource ]; - ByteString y = ( *pEntry )[ nFallback ]; - } - } -} - -/*****************************************************************************/ -ByteString Export::GetTimeStamp() -/*****************************************************************************/ -{ -// return "xx.xx.xx"; - char buf[20]; - Time aTime; - - snprintf(buf, sizeof(buf), "%8d %02d:%02d:%02d", int(Date().GetDate()), - int(aTime.GetHour()), int(aTime.GetMin()), int(aTime.GetSec())); - return ByteString(buf); -} - -/*****************************************************************************/ -BOOL Export::ConvertLineEnds( - ByteString sSource, ByteString sDestination ) -/*****************************************************************************/ -{ - String sSourceFile( sSource, RTL_TEXTENCODING_ASCII_US ); - String sDestinationFile( sDestination, RTL_TEXTENCODING_ASCII_US ); - - SvFileStream aSource( sSourceFile, STREAM_READ ); - if ( !aSource.IsOpen()) - return FALSE; - SvFileStream aDestination( sDestinationFile, STREAM_STD_WRITE | STREAM_TRUNC ); - if ( !aDestination.IsOpen()) { - aSource.Close(); - return FALSE; - } - - ByteString sLine; - - while ( !aSource.IsEof()) { - aSource.ReadLine( sLine ); - if ( !aSource.IsEof()) { - sLine.EraseAllChars( '\r' ); - aDestination.WriteLine( sLine ); - } - else - aDestination.WriteByteString( sLine ); - } - - aSource.Close(); - aDestination.Close(); - - return TRUE; -} - -/*****************************************************************************/ -ByteString Export::GetNativeFile( ByteString sSource ) -/*****************************************************************************/ -{ - DirEntry aTemp( GetTempFile()); - ByteString sReturn( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - for ( USHORT i = 0; i < 10; i++ ) - if ( ConvertLineEnds( sSource, sReturn )) - return sReturn; - - return ""; -} - -const char* Export::GetEnv( const char *pVar ) -{ - char *pRet = getenv( pVar ); - if ( !pRet ) - pRet = 0; - return pRet; -} - - -int Export::getCurrentDirectory( rtl::OUString& base_fqurl_out, rtl::OUString& base_out ) -{ - DirEntry aDir("."); - aDir.ToAbs(); - base_out = rtl::OUString( aDir.GetFull() ); - return osl::File::getFileURLFromSystemPath( base_out , base_fqurl_out ); -} - -void Export::getCurrentDir( string& dir ) -{ - char buffer[64000]; - if( getcwd( buffer , sizeof( buffer ) ) == 0 ){ - cerr << "Error: getcwd failed!\n"; - exit( -1 ); - } - dir = string( buffer ); -} - - -// Stolen from sal/osl/unx/tempfile.c - -#define RAND_NAME_LENGTH 6 - -void Export::getRandomName( const ByteString& sPrefix , ByteString& sRandStr , const ByteString& sPostfix ) -{ - static const char LETTERS[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - static const int COUNT_OF_LETTERS = sizeof(LETTERS)/sizeof(LETTERS[0]) - 1; - sRandStr.Append( sPrefix ); - - static sal_uInt64 value; - char buffer[RAND_NAME_LENGTH]; - - TimeValue tv; - sal_uInt64 v; - int i; - - osl_getSystemTime( &tv ); - oslProcessInfo proInfo; - osl_getProcessInfo( 0 , osl_Process_IDENTIFIER , &proInfo ); - - value += ((sal_uInt64) ( tv.Nanosec / 1000 ) << 16) ^ ( tv.Nanosec / 1000 ) ^ proInfo.Ident; - - v = value; - - for (i = 0; i < RAND_NAME_LENGTH; i++) - { - buffer[i] = LETTERS[v % COUNT_OF_LETTERS]; - v /= COUNT_OF_LETTERS; - } - - sRandStr.Append( buffer , RAND_NAME_LENGTH ); - sRandStr.Append( sPostfix ); -} - -void Export::getRandomName( ByteString& sRandStr ) -{ - const ByteString sEmpty; - getRandomName( sEmpty , sRandStr , sEmpty ); -} - -/*****************************************************************************/ -DirEntry Export::GetTempFile() -/*****************************************************************************/ -{ -#if defined(WNT) || defined(OS2) - String sTempDir( Export::GetEnv( "TEMP" ), RTL_TEXTENCODING_ASCII_US ); -#else - String sTempDir( String::CreateFromAscii( "/tmp" )); -#endif - rtl::OUString* sTempFilename = new rtl::OUString(); - - // Create a temp file - int nRC = osl::FileBase::createTempFile( 0 , 0 , sTempFilename ); - if( nRC ) printf(" osl::FileBase::createTempFile RC = %d",nRC); - - String strTmp( *sTempFilename ); - - INetURLObject::DecodeMechanism eMechanism = INetURLObject::DECODE_TO_IURI; - String sDecodedStr = INetURLObject::decode( strTmp , '%' , eMechanism ); - ByteString sTmp( sDecodedStr , RTL_TEXTENCODING_UTF8 ); - -#if defined(WNT) || defined(OS2) - sTmp.SearchAndReplace("file:///",""); - sTmp.SearchAndReplaceAll('/','\\'); -#else - // Set file permission to 644 - const sal_uInt64 nPerm = osl_File_Attribute_OwnRead | osl_File_Attribute_OwnWrite | - osl_File_Attribute_GrpRead | osl_File_Attribute_OthRead ; - - nRC = osl::File::setAttributes( *sTempFilename , nPerm ); - if( nRC ) printf(" osl::File::setAttributes RC = %d",nRC); - - sTmp.SearchAndReplace("file://",""); -#endif - DirEntry aDirEntry( sTmp ); - delete sTempFilename; - return aDirEntry; -} diff --git a/transex3/source/file.cxx b/transex3/source/file.cxx deleted file mode 100644 index 4ea9ca55d574..000000000000 --- a/transex3/source/file.cxx +++ /dev/null @@ -1,58 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: file.cxx,v $ - * $Revision: 1.6 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include - -namespace transex -{ - -File::File( const rtl::OUString sFile ) -{ - sFileName = sFile; -} - -File::File( const rtl::OUString sFullPath , const rtl::OUString sFile ) -{ - sFileName = sFile; - sFullName = sFullPath; -} - -bool File::lessFile ( const File& rKey1, const File& rKey2 ) -{ - rtl::OUString sName1( ( static_cast< File >( rKey1 ) ).getFileName() ); - rtl::OUString sName2( ( static_cast< File >( rKey2 ) ).getFileName() ); - - return sName1.compareTo( sName2 ) < 0 ; -} - -} diff --git a/transex3/source/filter/merge/FCFGMerge.cfg b/transex3/source/filter/merge/FCFGMerge.cfg deleted file mode 100644 index 46fcccafe7e4..000000000000 --- a/transex3/source/filter/merge/FCFGMerge.cfg +++ /dev/null @@ -1,125 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: FCFGMerge.cfg,v $ -# -# $Revision: 1.5 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -#************************************************ -# Specify the verbose mode of this tool. -# 1 = show errors only -# 2 = show errors/warnings (default) -# 3 = show errors/warnings and some generic infos -# 4 = show anything (including detailed infos) -# -# [OPTIONAL] -#************************************************ - -loglevel = 2 - -#************************************************ -# This extension is used for all XML files. It doesnt -# matter if its used for reading fragments or writing -# XML packages. -# Must be given without any additional signes like "." -# or "*."! -# -# [REQUIRED] -#************************************************ - -extension_xcu=xcu - -#************************************************ -# This extension is used for all Package files. It doesnt -# matter if its used for reading such files or writing -# it. -# Must be given without any additional signes like "." -# or "*."! -# -# [REQUIRED] -#************************************************ - -extension_pkg=pkg - -#************************************************ -# These values are used to generate a correct XML -# header. -# Note: The property "xmlpackage" must be specified -# via command line. There exists more then one -# possible value. -# -# [REQUIRED] -#************************************************ - -xmlversion = 1.0 -xmlencoding = UTF-8 -xmlpath = org.openoffice.TypeDetection -#xmlpackage = - -#************************************************ -# These values are used to name the configuration -# sets inside the generated XCM file for different -# item groups like e.g. types, filters etcpp. -# -# [REQUIRED] -#************************************************ - -setname_types = Types -setname_filters = Filters -setname_frameloaders = FrameLoaders -setname_contenthandlers = ContentHandlers - -subdir_types = types -subdir_filters = filters -subdir_frameloaders = frameloaders -subdir_contenthandlers = contenthandlers - -#************************************************ -# This delimiter is used to split every -# item list of the package configuration files -# (which are temp. created by the make proccess) -# into its tokens. -# -# [REQUIRED] -#************************************************ -delimiter=, - -#************************************************ -# Enable/disable removing of leading/trailing withespaces -# during splitting stringlists. -# -# [REQUIRED] -#************************************************ -trim=true - -#************************************************ -# Enable/disable removing of leading/trailing "-signs -# during splitting stringlists. -# -# [REQUIRED] -#************************************************ -decode=false diff --git a/transex3/source/filter/merge/FCFGMerge.java b/transex3/source/filter/merge/FCFGMerge.java deleted file mode 100644 index 7fbfa8a0c986..000000000000 --- a/transex3/source/filter/merge/FCFGMerge.java +++ /dev/null @@ -1,131 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: FCFGMerge.java,v $ - * $Revision: 1.5 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.filter.config.tools.merge; - -//_______________________________________________ - -import java.lang.*; -import java.util.*; -import java.io.*; -import com.sun.star.filter.config.tools.utils.*; - -//_______________________________________________ - -/** - * Its a simple command line tool, which can merge different XML fragments - * together. Such fragments must exist as files on disk, will be moved into - * one file together on disk. - * - * - */ -public class FCFGMerge -{ - //___________________________________________ - // const - - private static final java.lang.String CFGFILE = "com/sun/star/filter/config/tools/merge/FCFGMerge.cfg"; - private static final java.lang.String PROP_LOGLEVEL = "loglevel"; - - //___________________________________________ - // main - - public static void main(java.lang.String[] sCmdLine) - { - FCFGMerge.printCopyright(); - - // create log object in default mode "WARNINGS" - // If a command line parameter indicates another - // level - change it! - Logger aLog = new Logger(); - - try - { - // merge config file and overwrite properties - // via command line - ConfigHelper aCfg = null; - aCfg = new ConfigHelper(CFGFILE, sCmdLine); - - // update log level - int nLogLevel = aCfg.getInt(PROP_LOGLEVEL, Logger.LEVEL_WARNINGS); - aLog = new Logger(nLogLevel); - - // help requested? - if (aCfg.isHelp()) - { - FCFGMerge.printHelp(); - System.exit(-1); - } - - // create new merge object and start operation - Merger aMerger = new Merger(aCfg, aLog); - aMerger.merge(); - } - catch(java.lang.Throwable ex) - { - aLog.setException(ex); - System.exit(-1); - } - - System.exit(0); - } - - //___________________________________________ - - /** prints out a copyright message on stdout. - */ - private static void printCopyright() - { - java.lang.StringBuffer sOut = new java.lang.StringBuffer(256); - sOut.append("FCFGMerge\n"); - sOut.append("Copyright: 2003 by Sun Microsystems, Inc.\n"); - sOut.append("All Rights Reserved.\n"); - System.out.println(sOut.toString()); - } - - //___________________________________________ - - /** prints out a help message on stdout. - */ - private static void printHelp() - { - java.lang.StringBuffer sOut = new java.lang.StringBuffer(256); - sOut.append("____________________________________________________________\n"); - sOut.append("usage: FCFGMerge cfg=\n" ); - sOut.append("parameters:\n" ); - sOut.append("\tcfg=\n" ); - sOut.append("\t\tmust point to a system file, which contains\n" ); - sOut.append("\t\tall neccessary configuration data for the merge process.\n"); - sOut.append("\n\tFurther cou can specify every parameter allowed in the\n" ); - sOut.append("\n\tconfig file as command line parameter too, to overwrite\n" ); - sOut.append("\n\tthe value from the file.\n" ); - System.out.println(sOut.toString()); - } -} diff --git a/transex3/source/filter/merge/Manifest.mf b/transex3/source/filter/merge/Manifest.mf deleted file mode 100644 index 1337eaf4d39a..000000000000 --- a/transex3/source/filter/merge/Manifest.mf +++ /dev/null @@ -1 +0,0 @@ -Main-Class: com.sun.star.filter.config.tools.merge.FCFGMerge diff --git a/transex3/source/filter/merge/Merger.java b/transex3/source/filter/merge/Merger.java deleted file mode 100644 index 0bf11fc42fbf..000000000000 --- a/transex3/source/filter/merge/Merger.java +++ /dev/null @@ -1,364 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Merger.java,v $ - * $Revision: 1.8 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.filter.config.tools.merge; - -//_______________________________________________ - -import java.lang.*; -import java.util.*; -import java.io.*; -import com.sun.star.filter.config.tools.utils.*; - -//_______________________________________________ - -/** can merge different xml fragments together. - * - * - */ -public class Merger -{ - //___________________________________________ - // const - - private static final java.lang.String PROP_XMLVERSION = "xmlversion" ; // <= global cfg file - private static final java.lang.String PROP_XMLENCODING = "xmlencoding" ; // <= global cfg file - private static final java.lang.String PROP_XMLPATH = "xmlpath" ; // <= global cfg file - private static final java.lang.String PROP_XMLPACKAGE = "xmlpackage" ; // <= global cfg file - - private static final java.lang.String PROP_SETNAME_TYPES = "setname_types" ; // <= global cfg file - private static final java.lang.String PROP_SETNAME_FILTERS = "setname_filters" ; // <= global cfg file - private static final java.lang.String PROP_SETNAME_LOADERS = "setname_frameloaders" ; // <= global cfg file - private static final java.lang.String PROP_SETNAME_HANDLERS = "setname_contenthandlers" ; // <= global cfg file - - private static final java.lang.String PROP_SUBDIR_TYPES = "subdir_types" ; // <= global cfg file - private static final java.lang.String PROP_SUBDIR_FILTERS = "subdir_filters" ; // <= global cfg file - private static final java.lang.String PROP_SUBDIR_LOADERS = "subdir_frameloaders" ; // <= global cfg file - private static final java.lang.String PROP_SUBDIR_HANDLERS = "subdir_contenthandlers" ; // <= global cfg file - - private static final java.lang.String PROP_EXTENSION_XCU = "extension_xcu" ; // <= global cfg file - private static final java.lang.String PROP_EXTENSION_PKG = "extension_pkg" ; // <= global cfg file - - private static final java.lang.String PROP_DELIMITER = "delimiter" ; // <= global cfg file - private static final java.lang.String PROP_TRIM = "trim" ; // <= global cfg file - private static final java.lang.String PROP_DECODE = "decode" ; // <= global cfg file - - private static final java.lang.String PROP_FRAGMENTSDIR = "fragmentsdir" ; // <= cmdline - private static final java.lang.String PROP_TEMPDIR = "tempdir" ; // <= cmdline - private static final java.lang.String PROP_OUTDIR = "outdir" ; // <= cmdline - private static final java.lang.String PROP_PKG = "pkg" ; // <= cmdline - private static final java.lang.String PROP_DEBUG = "debug" ; // <= cmdline - - private static final java.lang.String PROP_TCFG = "tcfg" ; // <= cmdline - private static final java.lang.String PROP_FCFG = "fcfg" ; // <= cmdline - private static final java.lang.String PROP_LCFG = "lcfg" ; // <= cmdline - private static final java.lang.String PROP_CCFG = "ccfg" ; // <= cmdline - private static final java.lang.String PROP_LANGUAGEPACK = "languagepack" ; // <= cmdline - - private static final java.lang.String PROP_ITEMS = "items" ; // <= pkg cfg files! - - //___________________________________________ - // member - - //------------------------------------------- - /** TODO */ - private ConfigHelper m_aCfg; - - //------------------------------------------- - /** TODO */ - private Logger m_aLog; - - //------------------------------------------- - /** TODO */ - private java.io.File m_aFragmentsDir; - - //------------------------------------------- - /** TODO */ - private java.io.File m_aTempDir; - - //------------------------------------------- - /** TODO */ - private java.io.File m_aOutDir; - - //------------------------------------------- - /** TODO */ - private java.util.Vector m_lTypes; - private java.util.Vector m_lFilters; - private java.util.Vector m_lLoaders; - private java.util.Vector m_lHandlers; - - //___________________________________________ - // interface - - //------------------------------------------- - /** initialize a new instance of this class and - * try to get all needed resources from the config module. - * - * @param aCfg - * provides access to all values of the global - * config file and to the command line. - * - * @param aLog - * can be used to print out log informations. - */ - public Merger(ConfigHelper aCfg, - Logger aLog) - throws java.lang.Exception - { - m_aCfg = aCfg; - m_aLog = aLog; - - m_aFragmentsDir = new java.io.File(m_aCfg.getString(PROP_FRAGMENTSDIR)); - m_aTempDir = new java.io.File(m_aCfg.getString(PROP_TEMPDIR )); -// m_aOutDir = new java.io.File(m_aCfg.getString(PROP_OUTDIR )); - - java.lang.String sDelimiter = m_aCfg.getString(PROP_DELIMITER); - boolean bTrim = m_aCfg.getBoolean(PROP_TRIM); - boolean bDecode = m_aCfg.getBoolean(PROP_DECODE); - - try - { - ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_TCFG), null); - m_lTypes = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); - } - catch(java.util.NoSuchElementException ex1) - { - m_lTypes = new java.util.Vector(); - //m_aLog.setWarning("Fragment list of types is missing. Parameter \"items\" seems to be invalid."); - } - - try - { - ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_FCFG), null); - m_lFilters = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); - } - catch(java.util.NoSuchElementException ex1) - { - m_lFilters = new java.util.Vector(); - //m_aLog.setWarning("Fragment list of filters is missing. Parameter \"items\" seems to be invalid."); - } - - try - { - ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_LCFG), null); - m_lLoaders = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); - } - catch(java.util.NoSuchElementException ex1) - { - m_lLoaders = new java.util.Vector(); - //m_aLog.setWarning("Fragment list of frame loader objects is missing. Parameter \"items\" seems to be invalid."); - } - - try - { - ConfigHelper aFcfg = new ConfigHelper(m_aCfg.getString(PROP_CCFG), null); - m_lHandlers = aFcfg.getStringList(PROP_ITEMS, sDelimiter, bTrim, bDecode); - } - catch(java.util.NoSuchElementException ex1) - { - m_lHandlers = new java.util.Vector(); - //m_aLog.setWarning("Fragment list of content handler objects is missing. Parameter \"items\" seems to be invalid."); - } - } - - //------------------------------------------- - /** TODO */ - public synchronized void merge() - throws java.lang.Exception - { - java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(1000000); - java.lang.String sPackage = m_aCfg.getString(PROP_PKG); - - m_aLog.setGlobalInfo("create package \""+sPackage+"\" ..."); - m_aLog.setDetailedInfo("generate package header ... "); - - sBuffer.append( - XMLHelper.generateHeader( - m_aCfg.getString (PROP_XMLVERSION ), - m_aCfg.getString (PROP_XMLENCODING ), - m_aCfg.getString (PROP_XMLPATH ), - m_aCfg.getString (PROP_XMLPACKAGE ), - m_aCfg.getBoolean(PROP_LANGUAGEPACK, false))); - - // counts all transfered fragments - // Can be used later to decide, if a generated package file - // contains "nothing"! - int nItemCount = 0; - - for (int i=0; i<4; ++i) - { - java.lang.String sSetName = null; - java.lang.String sSubDir = null; - java.util.Vector lFragments = null; - - try - { - switch(i) - { - case 0: // types - { - m_aLog.setDetailedInfo("generate set for types ... "); - sSetName = m_aCfg.getString(PROP_SETNAME_TYPES); - sSubDir = m_aCfg.getString(PROP_SUBDIR_TYPES ); - lFragments = m_lTypes; - } - break; - - case 1: // filters - { - m_aLog.setDetailedInfo("generate set for filter ... "); - sSetName = m_aCfg.getString(PROP_SETNAME_FILTERS); - sSubDir = m_aCfg.getString(PROP_SUBDIR_FILTERS ); - lFragments = m_lFilters; - } - break; - - case 2: // loaders - { - m_aLog.setDetailedInfo("generate set for frame loader ... "); - sSetName = m_aCfg.getString(PROP_SETNAME_LOADERS); - sSubDir = m_aCfg.getString(PROP_SUBDIR_LOADERS ); - lFragments = m_lLoaders; - } - break; - - case 3: // handlers - { - m_aLog.setDetailedInfo("generate set for content handler ... "); - sSetName = m_aCfg.getString(PROP_SETNAME_HANDLERS); - sSubDir = m_aCfg.getString(PROP_SUBDIR_HANDLERS ); - lFragments = m_lHandlers; - } - break; - } - - nItemCount += lFragments.size(); - - getFragments( - new java.io.File(m_aFragmentsDir, sSubDir), - sSetName, - lFragments, - 1, - sBuffer); - } - catch(java.util.NoSuchElementException exIgnore) - { continue; } - } - - m_aLog.setDetailedInfo("generate package footer ... "); - sBuffer.append(XMLHelper.generateFooter()); - - // Attention! - // If the package seem to be empty, it make no sense to generate a corresponding - // xml file. We should suppress writing of this file on disk completly ... - if (nItemCount < 1) - { - m_aLog.setWarning("Package is empty and will not result into a xml file on disk!? Please check configuration file."); - return; - } - m_aLog.setGlobalInfo("package contains "+nItemCount+" items"); - - java.io.File aPackage = new File(sPackage); - m_aLog.setGlobalInfo("write temp package \""+aPackage.getPath()); // TODO encoding must be readed from the configuration - FileHelper.writeEncodedBufferToFile(aPackage, "UTF-8", false, sBuffer); // check for success is done inside this method! - } - - //------------------------------------------- - /** TODO */ - private void getFragments(java.io.File aDir , - java.lang.String sSetName , - java.util.Vector lFragments , - int nPrettyTabs, - java.lang.StringBuffer sBuffer ) - throws java.lang.Exception - { - if (lFragments.size()<1) - { - m_aLog.setWarning("List of fragments is empty!? Will be ignored ..."); - return; - } - - java.util.Enumeration pFragments = lFragments.elements(); - java.lang.String sExtXcu = m_aCfg.getString(PROP_EXTENSION_XCU); - - for (int tabs=0; tabs\n"); - ++nPrettyTabs; - - // special mode for generating language packs. - // In such case we must live with some missing fragment files. - // Reason behind; Not all filters are realy localized. - // But we dont use a different fragment list. We try to locate - // any fragment file in its language-pack version ... - boolean bHandleLanguagePacks = m_aCfg.getBoolean(PROP_LANGUAGEPACK, false); - boolean bDebug = m_aCfg.getBoolean(PROP_DEBUG , false); - java.lang.String sEncoding = "UTF-8"; - if (bDebug) - sEncoding = "UTF-8Special"; - - while(pFragments.hasMoreElements()) - { - java.lang.String sFragment = (java.lang.String)pFragments.nextElement(); - java.io.File aFragment = new java.io.File(aDir, sFragment+"."+sExtXcu); - - // handle simple files only and check for existence! - if (!aFragment.exists()) - { - if (bHandleLanguagePacks) - { - m_aLog.setWarning("language fragment \""+aFragment.getPath()+"\" does not exist. Will be ignored."); - continue; - } - else - throw new java.io.IOException("fragment \""+aFragment.getPath()+"\" does not exists."); - } - - if (!aFragment.isFile()) - { - m_aLog.setWarning("fragment \""+aFragment.getPath()+"\" seem to be not a valid file."); - continue; - } - - // copy file content of original fragment - // Note: A FileNotFoundException will be thrown automaticly by the - // used reader objects. Let it break this method too. Our calli is interested - // on such errors :-) - m_aLog.setDetailedInfo("merge fragment \""+aFragment.getPath()+"\" ..."); - FileHelper.readEncodedBufferFromFile(aFragment, sEncoding, sBuffer); - - sBuffer.append("\n"); - } - - --nPrettyTabs; - for (int tabs=0; tabs\n"); - } -} diff --git a/transex3/source/filter/merge/makefile.mk b/transex3/source/filter/merge/makefile.mk deleted file mode 100644 index bf768be851d8..000000000000 --- a/transex3/source/filter/merge/makefile.mk +++ /dev/null @@ -1,96 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.9.102.1 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ = ..$/..$/.. -TARGET = FCFGMerge -PRJNAME = filter -PACKAGE = com$/sun$/star$/filter$/config$/tools$/merge - -# --- Settings ----------------------------------------------------- - -.INCLUDE: settings.mk - -#----- compile .java files ----------------------------------------- -#.IF "$(L10N_framework)"=="" - -OWNCOPY = \ - $(MISC)$/$(TARGET)_copied.done - -#JARFILES = \ -# ridl.jar \ -# unoil.jar \ -# jurt.jar \ -# juh.jar \ -# java_uno.jar - -CFGFILES = \ - FCFGMerge.cfg - -JAVACLASSFILES = \ - $(CLASSDIR)$/$(PACKAGE)$/Merger.class \ - $(CLASSDIR)$/$(PACKAGE)$/FCFGMerge.class - -CUSTOMMANIFESTFILE = \ - Manifest.mf - -MAXLINELENGTH = 100000 - -#----- make a jar from compiled files ------------------------------ - -JARCLASSDIRS = \ - com$/sun$/star$/filter$/config$/tools$/utils \ - com$/sun$/star$/filter$/config$/tools$/merge - -JARTARGET = $(TARGET).jar - -JARCOMPRESS = TRUE - -# --- targets ----------------------------------------------------- - -.INCLUDE : target.mk - -.IF "$(SOLAR_JAVA)" != "" || "$(GUI)"=="OS2" -ALLTAR : $(OWNCOPY) - -.IF "$(JARTARGETN)" != "" -$(JARTARGETN) : $(OWNCOPY) -.ENDIF - -$(OWNCOPY) : $(CFGFILES) - -$(MKDIRHIER) $(CLASSDIR)$/$(PACKAGE) - $(COPY) $? $(CLASSDIR)$/$(PACKAGE) && $(TOUCH) $@ - -.ENDIF # "$(SOLAR_JAVA)" != "" - -#.ELSE -#pseudo: - -#.ENDIF diff --git a/transex3/source/filter/utils/AnalyzeStartupLog.java b/transex3/source/filter/utils/AnalyzeStartupLog.java deleted file mode 100644 index 498528850697..000000000000 --- a/transex3/source/filter/utils/AnalyzeStartupLog.java +++ /dev/null @@ -1,328 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: AnalyzeStartupLog.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.filter.config.tools.utils; - -//_______________________________________________ -// imports -import java.util.*; -import java.lang.*; - -//_______________________________________________ -// implementation -public class AnalyzeStartupLog -{ - private class OperationTime - { - /** name the measured operation. */ - public java.lang.String sOperation; - - /** contains the time value, when this operation was started. */ - public long nStartTime; - - /** contains the time value, when this operation was finished. */ - public long nEndTime; - - /** text inside log file, which identifies the start time value. */ - public java.lang.String sStartMsg; - - /** text inside log file, which identifies the end time value. */ - public java.lang.String sEndMsg; - } - - //_________________________________ - // main - - public static void main(java.lang.String[] lCmdLine) - { - int nExit = 0; - try - { - // analyze command line - ConfigHelper aCmdLine = new ConfigHelper("", lCmdLine); - java.lang.String sLogDir = aCmdLine.getString("logdir" ); - java.lang.String sDataFile = aCmdLine.getString("datafile"); - - if (sLogDir == null || sDataFile == null) - { - System.err.println("AnalyzeStartupLog lodir= datafile="); - System.err.println("E.g.: AnalyzeStartupLog lodir=c:\\temp\\logs datafile=c:\\temp\\data.csv"); - System.exit(--nExit); - } - - // get list of all log files - boolean bRecursive = true; - java.util.Vector lLogs = FileHelper.getSystemFilesFromDir(new java.io.File(sLogDir), bRecursive); - if (lLogs == null || lLogs.isEmpty()) - { - System.err.println("log dir is empty"); - System.exit(--nExit); - } - - // analyze it - java.lang.StringBuffer sOut = new java.lang.StringBuffer(1000); - sOut.append("log;t_cfg_start;t_cfg_end;t_fwk_start;t_fwk_end;t_sfx_start;t_sfx_end;t_types_start;t_types_end;t_filters_start;t_filters_end;"); - sOut.append("t_filters_swriter_start;t_filters_swriter_end;t_filters_sweb_start;t_filters_sweb_end;t_filters_sglobal_start;t_filters_sglobal_end;t_filters_scalc_start;t_filters_scalc_end;t_filters_sdraw_start;t_filters_sdraw_end;t_filters_simpress_start;t_filters_simpress_end;t_filters_schart_start;t_filters_schart_end;t_filters_smath_start;t_filters_smath_end;"); - sOut.append("t_others_start;t_others_end;d_cfg;d_fwk;d_sfx;d_types;d_filters;d_others;d_complete\n"); - - java.util.Enumeration aIt = lLogs.elements(); - while (aIt.hasMoreElements()) - { - java.io.File aLog = (java.io.File)aIt.nextElement(); - java.io.FileReader aReader = new java.io.FileReader(aLog); - java.io.BufferedReader aBuffer = new java.io.BufferedReader(aReader); - - long t_cfg_start = 0; - long t_cfg_end = 0; - - long t_fwk_start = 0; - long t_fwk_end = 0; - - long t_sfx_start = 0; - long t_sfx_end = 0; - - long t_types_start = 0; - long t_types_end = 0; - - long t_filters_start = 0; - long t_filters_end = 0; - - long t_filters_swriter_start = 0; - long t_filters_swriter_end = 0; - - long t_filters_sweb_start = 0; - long t_filters_sweb_end = 0; - - long t_filters_sglobal_start = 0; - long t_filters_sglobal_end = 0; - - long t_filters_scalc_start = 0; - long t_filters_scalc_end = 0; - - long t_filters_sdraw_start = 0; - long t_filters_sdraw_end = 0; - - long t_filters_simpress_start = 0; - long t_filters_simpress_end = 0; - - long t_filters_schart_start = 0; - long t_filters_schart_end = 0; - - long t_filters_smath_start = 0; - long t_filters_smath_end = 0; - - long t_others_start = 0; - long t_others_end = 0; - - while (true) - { - java.lang.String sLine = aBuffer.readLine(); - if (sLine == null) - break; - - if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : { creation ConfigItem [file=standard, version=6, mode=3]")) - t_cfg_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : } creation ConfigItem")) - t_cfg_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : { reading TypeDetection.xml")) - t_fwk_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("| framework (as96863) ::FilterCache::FilterCache : } reading TypeDetection.xml")) - t_fwk_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadTypes")) - t_types_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadTypes")) - t_types_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadFilters")) - t_filters_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadFilters")) - t_filters_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [swriter]")) - t_filters_swriter_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [swriter]")) - t_filters_swriter_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [sweb]")) - t_filters_sweb_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [sweb]")) - t_filters_sweb_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [sglobal]")) - t_filters_sglobal_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [sglobal]")) - t_filters_sglobal_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [scalc]")) - t_filters_scalc_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [scalc]")) - t_filters_scalc_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [sdraw]")) - t_filters_sdraw_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [sdraw]")) - t_filters_sdraw_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [simpress]")) - t_filters_simpress_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [simpress]")) - t_filters_simpress_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [schart]")) - t_filters_schart_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [schart]")) - t_filters_schart_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ reading FilterGroup [smath]")) - t_filters_smath_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} reading FilterGroup [smath]")) - t_filters_smath_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("{ framework (as96863) ::FilterCFGAccess::impl_loadDetectors")) - t_others_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} framework (as96863) ::FilterCFGAccess::impl_loadContentHandlers")) - t_others_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} framework (as96863) ::FilterCache::FilterCache")) - t_sfx_start = new java.lang.Long(sLine.substring(0, 6)).longValue(); - else - if (sLine.endsWith("} desktop (lo119109) OfficeWrapper::OfficeWrapper")) - t_sfx_end = new java.lang.Long(sLine.substring(0, 6)).longValue(); - } - - sOut.append(aLog.getName() ); - sOut.append(";" ); - sOut.append(t_cfg_start ); - sOut.append(";" ); - sOut.append(t_cfg_end ); - sOut.append(";" ); - sOut.append(t_fwk_start ); - sOut.append(";" ); - sOut.append(t_fwk_end ); - sOut.append(";" ); - sOut.append(t_sfx_start ); - sOut.append(";" ); - sOut.append(t_sfx_end ); - sOut.append(";" ); - sOut.append(t_types_start ); - sOut.append(";" ); - sOut.append(t_types_end ); - sOut.append(";" ); - sOut.append(t_filters_start ); - sOut.append(";" ); - sOut.append(t_filters_end ); - sOut.append(";" ); - - sOut.append(t_filters_swriter_start ); - sOut.append(";" ); - sOut.append(t_filters_swriter_end ); - sOut.append(";" ); - sOut.append(t_filters_sweb_start ); - sOut.append(";" ); - sOut.append(t_filters_sweb_end ); - sOut.append(";" ); - sOut.append(t_filters_sglobal_start ); - sOut.append(";" ); - sOut.append(t_filters_sglobal_end ); - sOut.append(";" ); - sOut.append(t_filters_scalc_start ); - sOut.append(";" ); - sOut.append(t_filters_scalc_end ); - sOut.append(";" ); - sOut.append(t_filters_sdraw_start ); - sOut.append(";" ); - sOut.append(t_filters_sdraw_end ); - sOut.append(";" ); - sOut.append(t_filters_simpress_start ); - sOut.append(";" ); - sOut.append(t_filters_simpress_end ); - sOut.append(";" ); - sOut.append(t_filters_schart_start ); - sOut.append(";" ); - sOut.append(t_filters_schart_end ); - sOut.append(";" ); - sOut.append(t_filters_smath_start ); - sOut.append(";" ); - sOut.append(t_filters_smath_end ); - sOut.append(";" ); - - sOut.append(t_others_start ); - sOut.append(";" ); - sOut.append(t_others_end ); - sOut.append(";" ); - sOut.append(t_cfg_end -t_cfg_start ); - sOut.append(";" ); - sOut.append(t_fwk_end -t_fwk_start ); - sOut.append(";" ); - sOut.append(t_sfx_end -t_sfx_start ); - sOut.append(";" ); - sOut.append(t_types_end -t_types_start ); - sOut.append(";" ); - sOut.append(t_filters_end-t_filters_start); - sOut.append(";" ); - sOut.append(t_others_end -t_others_start ); - sOut.append(";" ); - sOut.append(t_others_end -t_cfg_start ); - sOut.append("\n" ); - - aBuffer.close(); - } - - java.io.FileWriter aCSV = new java.io.FileWriter(sDataFile); - java.lang.String sData = sOut.toString(); - aCSV.write(sData, 0, sData.length()); - aCSV.flush(); - aCSV.close(); - } - catch(java.lang.Throwable exAny) - { - System.err.println(exAny.getMessage()); - exAny.printStackTrace(); - System.exit(--nExit); - } - - System.exit(0); - } -} diff --git a/transex3/source/filter/utils/Cache.java b/transex3/source/filter/utils/Cache.java deleted file mode 100644 index 94c26008ed13..000000000000 --- a/transex3/source/filter/utils/Cache.java +++ /dev/null @@ -1,2449 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Cache.java,v $ - * $Revision: 1.7 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.filter.config.tools.utils; - -//_______________________________________________ - -import java.lang.*; -import java.util.*; -import java.io.*; - -//_______________________________________________ - -/** - * It implements a container for all possible entries which are part of the type - * and filter mechanism of an office - means all items of the configuration file - * "TypeDetection". How these entries will be readed or written can be switch - * in different modes. That would make it possible to edit an xml directly or - * to contact a running office instance. - * - * - */ -public class Cache -{ - //___________________________________________ - // public const - - /** identifies a file type item of this cache. */ - public static final int E_TYPE = 0; - - /** identifies a filter item of this cache. */ - public static final int E_FILTER = 1; - - /** identifies a detect service item of this cache. */ - public static final int E_DETECTSERVICE = 2; - - /** identifies a frame loader item of this cache. */ - public static final int E_FRAMELOADER = 3; - - /** identifies a content handler item of this cache. */ - public static final int E_CONTENTHANDLER = 4; - - /** indicates an unsupported xml format => error! */ - public static final int FORMAT_UNSUPPORTED = -1; - - /** identify the configuration format of an office 6.0. - * The own formated data string is used. */ - public static final int FORMAT_60 = 0; - - /** identify the configuration format of an office 6.y. - * Properties are realy xml tags again. */ - public static final int FORMAT_6Y = 1; - - /** identify the configuration format which is used inside - * this tooling project. */ - public static final int FORMAT_INTERNAL = 2; - - /** right value for a command line parameter to define a 6.0 version. */ - public static final java.lang.String CMDVAL_FORMAT_60 = "6.0"; - - /** right value for a command line parameter to define a 6.Y version. */ - public static final java.lang.String CMDVAL_FORMAT_6Y = "6.Y"; - - /** right value for a command line parameter to define an internal xml version! */ - public static final java.lang.String CMDVAL_FORMAT_INTERNAL = "internal"; - - // general - public static final java.lang.String PROPNAME_DATA = "Data"; - public static final java.lang.String PROPNAME_NAME = "Name"; - public static final java.lang.String PROPNAME_UINAME = "UIName"; - public static final java.lang.String PROPNAME_UINAMES = "UINames"; - - // type 6.0 ... - public static final java.lang.String PROPNAME_MEDIATYPE = "MediaType"; - public static final java.lang.String PROPNAME_PREFERRED = "Preferred"; - public static final java.lang.String PROPNAME_CLIPBOARDFORMAT = "ClipboardFormat"; - public static final java.lang.String PROPNAME_DOCUMENTICONID = "DocumentIconID"; - public static final java.lang.String PROPNAME_URLPATTERN = "URLPattern"; - public static final java.lang.String PROPNAME_EXTENSIONS = "Extensions"; - // ... +6.y - public static final java.lang.String PROPNAME_UIORDER = "UIOrder"; - public static final java.lang.String PROPNAME_PREFERREDFILTER = "PreferredFilter"; - public static final java.lang.String PROPNAME_DETECTSERVICE = "DetectService"; - public static final java.lang.String PROPNAME_FRAMELOADER = "FrameLoader"; - public static final java.lang.String PROPNAME_CONTENTHANDLER = "ContentHandler"; - - // filter - public static final java.lang.String PROPNAME_DOCUMENTSERVICE = "DocumentService"; - public static final java.lang.String PROPNAME_FILEFORMATVERSION = "FileFormatVersion"; - public static final java.lang.String PROPNAME_FILTERSERVICE = "FilterService"; - public static final java.lang.String PROPNAME_FLAGS = "Flags"; - public static final java.lang.String PROPNAME_ORDER = "Order"; // -6.y - public static final java.lang.String PROPNAME_TEMPLATENAME = "TemplateName"; - public static final java.lang.String PROPNAME_TYPE = "Type"; - public static final java.lang.String PROPNAME_UICOMPONENT = "UIComponent"; - public static final java.lang.String PROPNAME_USERDATA = "UserData"; - - // frame loader / detect services / content handler - public static final java.lang.String PROPNAME_TYPES = "Types"; - - //___________________________________________ - // private const - - private static final java.lang.String FILTERSERVICE_NATIVEWARPPER = "com.sun.star.filter.NativeFilterWrapper"; - private static final java.lang.String GENERIC_DETECTSERVICE = "com.sun.star.comp.office.FrameLoader"; - - /** its the name of the cfg set, which contains all types. */ - private static final java.lang.String CFGNODE_TYPES = "Types"; - - /** its the name of the cfg set, which contains all filters. */ - private static final java.lang.String CFGNODE_FILTERS = "Filters"; - - /** its the name of the cfg set, which contains all detect services. */ - private static final java.lang.String CFGNODE_DETECTSERVICES = "DetectServices"; - - /** its the name of the cfg set, which contains all frame loaders. */ - private static final java.lang.String CFGNODE_FRAMELOADERS = "FrameLoaders"; - - /** its the name of the cfg set, which contains all content handlers. */ - private static final java.lang.String CFGNODE_CONTENTHANDLERS = "ContentHandlers"; - - // names for filter flags - private static final java.lang.String FLAGNAME_3RDPARTYFILTER = "3RDPARTYFILTER"; - private static final java.lang.String FLAGNAME_ALIEN = "ALIEN"; - private static final java.lang.String FLAGNAME_ASYNCHRON = "ASYNCHRON"; - private static final java.lang.String FLAGNAME_BROWSERPREFERRED = "BROWSERPREFERRED"; - private static final java.lang.String FLAGNAME_CONSULTSERVICE = "CONSULTSERVICE"; - private static final java.lang.String FLAGNAME_DEFAULT = "DEFAULT"; - private static final java.lang.String FLAGNAME_EXPORT = "EXPORT"; - private static final java.lang.String FLAGNAME_IMPORT = "IMPORT"; - private static final java.lang.String FLAGNAME_INTERNAL = "INTERNAL"; - private static final java.lang.String FLAGNAME_NOTINCHOOSER = "NOTINCHOOSER"; - private static final java.lang.String FLAGNAME_NOTINFILEDIALOG = "NOTINFILEDIALOG"; - private static final java.lang.String FLAGNAME_NOTINSTALLED = "NOTINSTALLED"; - private static final java.lang.String FLAGNAME_OWN = "OWN"; - private static final java.lang.String FLAGNAME_PACKED = "PACKED"; - private static final java.lang.String FLAGNAME_PREFERRED = "PREFERRED"; - private static final java.lang.String FLAGNAME_READONLY = "READONLY"; - private static final java.lang.String FLAGNAME_SILENTEXPORT = "SILENTEXPORT"; - private static final java.lang.String FLAGNAME_TEMPLATE = "TEMPLATE"; - private static final java.lang.String FLAGNAME_TEMPLATEPATH = "TEMPLATEPATH"; - private static final java.lang.String FLAGNAME_USESOPTIONS = "USESOPTIONS"; - - private static final java.lang.String FLAGNAME_COMBINED = "COMBINED"; - private static final java.lang.String FLAGNAME_SUPPORTSSELECTION= "SUPPORTSSELECTION"; - - // values for filter flags - private static final int FLAGVAL_3RDPARTYFILTER = 0x00080000; // 524288 - private static final int FLAGVAL_ALIEN = 0x00000040; // 64 - private static final int FLAGVAL_ALL = 0xffffffff; // 4294967295 - private static final int FLAGVAL_ASYNCHRON = 0x00004000; // 16384 - private static final int FLAGVAL_BROWSERPREFERRED = 0x00400000; // 4194304 - private static final int FLAGVAL_CONSULTSERVICE = 0x00040000; // 262144 - private static final int FLAGVAL_DEFAULT = 0x00000100; // 256 - private static final int FLAGVAL_EXPORT = 0x00000002; // 2 - private static final int FLAGVAL_IMPORT = 0x00000001; // 1 - private static final int FLAGVAL_INTERNAL = 0x00000008; // 8 - private static final int FLAGVAL_NOTINCHOOSER = 0x00002000; // 8192 - private static final int FLAGVAL_NOTINFILEDIALOG = 0x00001000; // 4096 - private static final int FLAGVAL_NOTINSTALLED = 0x00020000; // 131072 - private static final int FLAGVAL_OWN = 0x00000020; // 32 - private static final int FLAGVAL_PACKED = 0x00100000; // 1048576 - private static final int FLAGVAL_PREFERRED = 0x10000000; // 268435456 - private static final int FLAGVAL_READONLY = 0x00010000; // 65536 - private static final int FLAGVAL_SILENTEXPORT = 0x00200000; // 2097152 - private static final int FLAGVAL_TEMPLATE = 0x00000004; // 4 - private static final int FLAGVAL_TEMPLATEPATH = 0x00000010; // 16 - private static final int FLAGVAL_USESOPTIONS = 0x00000080; // 128 - - private static final int FLAGVAL_COMBINED = 0x00800000; // ... - private static final int FLAGVAL_SUPPORTSSELECTION = 0x00000400; // 1024 - - //___________________________________________ - // member - - /** list of all located types. - * Format: [string,HashMap] - */ - private java.util.HashMap m_lTypes; - - /** list of all located filters. - * Format: [string,HashMap] - */ - private java.util.HashMap m_lFilters; - - /** list of all located detect services. - * Format: [string,HashMap] - */ - private java.util.HashMap m_lDetectServices; - - /** list of all located frame loader. - * Format: [string,HashMap] - */ - private java.util.HashMap m_lFrameLoaders; - - /** list of all located content handler. - * Format: [string,HashMap] - */ - private java.util.HashMap m_lContentHandlers; - - /** contains all analyzed relations between - * filters and types. The key is an internal - * type name (can be used as reference into the - * list m_lTypes) and the value is a Vector of all - * internal filter names, which are registered for - * this type. - * Format: [string, Vector] - */ - private java.util.HashMap m_lFilterToTypeRegistrations; - - private int m_nDoubleRegisteredFilters; - private int m_nTypesForFilters; - private int m_nTypesForDetectServices; - private int m_nTypesForFrameLoaders; - private int m_nTypesForContentHandlers; - - /** can be used to log different informations. */ - private Logger m_aDebug; - - //___________________________________________ - // interface - - /** standard ctor. - * - * Initialize an empty cache instance. You have to use - * on of the fromXXX() methods to fill it from different - * sources with content. - */ - public Cache(Logger aDebug) - { - reset(); - m_aDebug = aDebug; - } - - //___________________________________________ - - /** free memory and set default values on all members. - */ - public synchronized void reset() - { - m_lTypes = new java.util.HashMap(); - m_lFilters = new java.util.HashMap(); - m_lFrameLoaders = new java.util.HashMap(); - m_lDetectServices = new java.util.HashMap(); - m_lContentHandlers = new java.util.HashMap(); - m_lFilterToTypeRegistrations = new java.util.HashMap(); - m_aDebug = new Logger(); - m_nDoubleRegisteredFilters = 0; - m_nTypesForFilters = 0; - m_nTypesForDetectServices = 0; - m_nTypesForFrameLoaders = 0; - m_nTypesForContentHandlers = 0; - } - - //___________________________________________ - - /** converts a string representation of an xml format - * to its int value, which must be used at some interface - * methods of this cache. - * - * If the given string does not match to any well known format, - * the return value will be FORMAT_UNSUPPORTED. The calli have to - * check that. Otherwhise a called interface method at this cache - * instance will be rejected by an exception! - * - * @param sFormat - * the string representation - * Must be one of our public const values from type CMDVAL_FORMAT_xxx. - * - * @return [int] - * the int representation. - * Will be one of our public const values from type FORMAT_xxx. - */ - public static int mapFormatString2Format(java.lang.String sFormat) - { - int nFormat = FORMAT_UNSUPPORTED; - if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_60)) - nFormat = FORMAT_60; - else - if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_6Y)) - nFormat = FORMAT_6Y; - else - if (sFormat.equalsIgnoreCase(CMDVAL_FORMAT_INTERNAL)) - nFormat = FORMAT_INTERNAL; - return nFormat; - } - - //___________________________________________ - - /** return some statistic values. - * - * Such values can be: - count of container items, - * - ... - * - * @return [java.lang.String] - * a formated string, which contains al statistic data. - */ - public synchronized java.lang.String getStatistics() - { - java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(256); - - sBuffer.append("types = "+m_lTypes.size() +"\n"); - sBuffer.append("filters = "+m_lFilters.size() +"\n"); - sBuffer.append("detect services = "+m_lDetectServices.size() +"\n"); - sBuffer.append("frame loaders = "+m_lFrameLoaders.size() +"\n"); - sBuffer.append("content handler = "+m_lContentHandlers.size() +"\n"); - sBuffer.append("double registered filters = "+m_nDoubleRegisteredFilters+"\n"); - sBuffer.append("types used by filters = "+m_nTypesForFilters +"\n"); - sBuffer.append("types used by detect services = "+m_nTypesForDetectServices +"\n"); - sBuffer.append("types used by frame loaders = "+m_nTypesForFrameLoaders +"\n"); - sBuffer.append("types used by content handlers = "+m_nTypesForContentHandlers+"\n"); - - return sBuffer.toString(); - } - - //___________________________________________ - - /** reset this cache and fill it with new values using the given XML file. - * - * @param aXML - * must be a system file of a suitable XML file, which - * include all neccessary type/filter items. - * - * @param nFormat - * identifies the format of the specified xml file, - * which must be interpreted. - */ - public synchronized void fromXML(java.io.File aXML , - int nFormat) - throws java.lang.Exception - { - // clear this cache - reset(); - - // parse it - javax.xml.parsers.DocumentBuilderFactory aFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); - /* Attention: - * This call is important. It force right handling of entities during parsing and(!) - * writing. It let all possible signs for entities or it's quoted representations - * untouched. So this class don't change the original signs of the original file. - * Means: - *
    - *
  • (') => (')
  • - *
  • (") => (")
  • - *
  • (>) => (>)
  • - *
  • (<) => (<)
  • - *
  • (>) => (>)
  • - *
  • (&) => (&)
  • - *
  • ...
  • - *
- */ - - System.out.println("TODO: must be adapted to java 1.3 :-("); - System.exit(-1); -//TODO_JAVA aFactory.setExpandEntityReferences(false); - - javax.xml.parsers.DocumentBuilder aBuilder = aFactory.newDocumentBuilder(); - org.w3c.dom.Document aDOM = aBuilder.parse(aXML); - org.w3c.dom.Element aRoot = aDOM.getDocumentElement(); - - // step over all sets - java.util.Vector lSetNodes = XMLHelper.extractChildNodesByTagName(aRoot, XMLHelper.XMLTAG_NODE); - java.util.Enumeration it1 = lSetNodes.elements(); - while (it1.hasMoreElements()) - { - // try to find out, which set should be read - org.w3c.dom.Node aSetNode = (org.w3c.dom.Node)it1.nextElement(); - java.lang.String sSetName = XMLHelper.extractNodeAttribByName(aSetNode, XMLHelper.XMLATTRIB_OOR_NAME); - if (sSetName == null) - throw new java.io.IOException("unsupported format: could not extract set name on node ...\n"+aSetNode); - - // map some generic interfaces to the right members! - int eType = -1 ; - java.util.HashMap rMap = null; - - if (sSetName.equals(CFGNODE_TYPES)) - { - eType = E_TYPE; - rMap = m_lTypes; - } - else - if (sSetName.equals(CFGNODE_FILTERS)) - { - eType = E_FILTER; - rMap = m_lFilters; - } - else - if (sSetName.equals(CFGNODE_FRAMELOADERS)) - { - eType = E_FRAMELOADER; - rMap = m_lFrameLoaders; - } - else - if (sSetName.equals(CFGNODE_DETECTSERVICES)) - { - eType = E_DETECTSERVICE; - rMap = m_lDetectServices; - } - else - if (sSetName.equals(CFGNODE_CONTENTHANDLERS)) - { - eType = E_CONTENTHANDLER; - rMap = m_lContentHandlers; - } - else - throw new java.io.IOException("unsupported format: unknown set name [\""+sSetName+"\"] detected on node ...\n"+aSetNode); - - // load all set entries - java.util.Vector lChildNodes = XMLHelper.extractChildNodesByTagName(aSetNode, XMLHelper.XMLTAG_NODE); - java.util.Enumeration it2 = lChildNodes.elements(); - while (it2.hasMoreElements()) - { - org.w3c.dom.Node aChildNode = (org.w3c.dom.Node)it2.nextElement(); - java.lang.String sChildName = XMLHelper.extractNodeAttribByName(aChildNode, XMLHelper.XMLATTRIB_OOR_NAME); - if (sChildName == null) - throw new java.io.IOException("unsupported format: could not extract child node name on node ...\n"+aChildNode); - java.util.HashMap aPropSet = null; - - // Note: Our internal format is different from the source format! - java.util.HashMap aTempSet = XMLHelper.convertNodeToPropSet(aChildNode); - switch(eType) - { - case E_TYPE : - { - aPropSet = Cache.convertTypePropsToInternal(aTempSet, nFormat); - m_aDebug.setDetailedInfo("type [\""+sChildName+"\"] converted to internal format"); - } - break; - - case E_FILTER : - { - aPropSet = Cache.convertFilterPropsToInternal(aTempSet, nFormat); - m_aDebug.setDetailedInfo("filter [\""+sChildName+"\"] converted to internal format"); - } - break; - - case E_DETECTSERVICE : - { - aPropSet = Cache.convertDetectServicePropsToInternal(aTempSet, nFormat); - m_aDebug.setDetailedInfo("detect service [\""+sChildName+"\"] converted to internal format"); - } - break; - - case E_FRAMELOADER : - { - aPropSet = Cache.convertFrameLoaderPropsToInternal(aTempSet, nFormat); - m_aDebug.setDetailedInfo("frame loader [\""+sChildName+"\"] converted to internal format"); - } - break; - - case E_CONTENTHANDLER : - { - aPropSet = Cache.convertContentHandlerPropsToInternal(aTempSet, nFormat); - m_aDebug.setDetailedInfo("content handler [\""+sChildName+"\"] converted to internal format"); - } - break; - } - m_aDebug.setDetailedInfo("props = "+aTempSet); - rMap.put(sChildName, aPropSet); - } - } - } - - //___________________________________________ - - /** create some hml views of the current content of this cache. - * - * The given directory is used to create different html files - * there. Every of them show another aspect of this cache. - * E.g.: - all type/filter properties - * - relation ships between types/filters/loaders etc. - * - * @param aDirectory - * points to a system directory, which - * can be used completely(!) to generate - * the results there. - * - * @param nFormat - * specify in which context the cache items should be - * interpreted. - */ - public synchronized void toHTML(java.io.File aDirectory, - int nFormat , - java.lang.String sEncoding ) - throws java.lang.Exception - { - if (nFormat != FORMAT_6Y) - throw new java.lang.Exception("HTML views are supported for the new 6.y format only yet."); - - java.lang.StringBuffer sRelationView = new java.lang.StringBuffer(1000); - sRelationView.append("
Relation View
"); - sRelationView.append(""); - sRelationView.append(""); - - java.util.Iterator aIt = m_lTypes.keySet().iterator(); - while (aIt.hasNext()) - { - java.lang.String sType = (java.lang.String)aIt.next(); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sType); - - sRelationView.append(""); - sRelationView.append(""); - - java.lang.String sVal = (java.lang.String)aType.get(PROPNAME_DETECTSERVICE); - if (sVal == null || sVal.length()<1) - sRelationView.append(""); - else - sRelationView.append(""); - - sVal = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); - if (sVal == null || sVal.length()<1) - sRelationView.append(""); - else - sRelationView.append(""); - - sVal = (java.lang.String)aType.get(PROPNAME_FRAMELOADER); - if (sVal == null || sVal.length()<1) - sRelationView.append(""); - else - sRelationView.append(""); - - sVal = (java.lang.String)aType.get(PROPNAME_CONTENTHANDLER); - if (sVal == null || sVal.length()<1) - sRelationView.append(""); - else - sRelationView.append(""); - - sRelationView.append(""); - } - - sRelationView.append("
typedetect servicepreferred filterframe loadercontent handler
"+sType+" - "+sVal+" - "+sVal+" - "+sVal+" - "+sVal+"
"); - sRelationView.append(""); - - FileHelper.writeEncodedBufferToFile(new java.io.File(aDirectory, "relation_view.html"), sEncoding, false, sRelationView); - - java.util.HashMap lFilters2TypeRegistration = new java.util.HashMap(); - aIt = m_lFilters.keySet().iterator(); - while (aIt.hasNext()) - { - java.lang.String sFilter = (java.lang.String)aIt.next(); - java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); - java.lang.String sType = (java.lang.String)aFilter.get(PROPNAME_TYPE); - - java.util.Vector lFilters = (java.util.Vector)lFilters2TypeRegistration.get(sType); - if (lFilters == null) - lFilters = new java.util.Vector(); - lFilters.add(sFilter); - lFilters2TypeRegistration.put(sType, lFilters); - } - - java.lang.StringBuffer sType2FiltersView = new java.lang.StringBuffer(1000); - sType2FiltersView.append("
Type2Filters View
"); - sType2FiltersView.append(""); - sType2FiltersView.append(""); - - aIt = lFilters2TypeRegistration.keySet().iterator(); - while (aIt.hasNext()) - { - java.lang.String sType = (java.lang.String)aIt.next(); - java.util.Vector lFilters = (java.util.Vector)lFilters2TypeRegistration.get(sType); - - sType2FiltersView.append(""); - } - - sType2FiltersView.append("
typefilters
"+sType+""); - java.util.Enumeration aEn = lFilters.elements(); - while(aEn.hasMoreElements()) - sType2FiltersView.append(aEn.nextElement()+"
"); - sType2FiltersView.append("
"); - sType2FiltersView.append(""); - - FileHelper.writeEncodedBufferToFile(new java.io.File(aDirectory, "type2filters_view.html"), sEncoding, false, sType2FiltersView); - } - - //___________________________________________ - - /** converts all items of this cache to its xml representation - * and write it to the given file. - * - * @param aXML - * the target file for output. - * - * @param nFormat - * the requested xml format. - * see const values FORMAT_xxx too. - * - * @param sEncoding - * specify the file encoding for the generated xml file. - * - * @throws [java.lang.Exception] - * if something fail during convertion. - */ - public synchronized void toXML(java.io.File aXML , - int nFormat , - java.lang.String sEncoding) - throws java.lang.Exception - { - java.lang.StringBuffer sXML = new java.lang.StringBuffer(500000); - - for (int i=0; i<5; ++i) - { - // define right sub container - java.lang.String sSetName = null; - java.util.HashMap rMap = null; - int eType = -1; - - switch(i) - { - case 0 : - { - sSetName = CFGNODE_TYPES; - rMap = m_lTypes; - eType = E_TYPE; - } - break; - - case 1 : - { - sSetName = CFGNODE_FILTERS; - rMap = m_lFilters; - eType = E_FILTER; - } - break; - - case 2 : - { - sSetName = CFGNODE_DETECTSERVICES; - rMap = m_lDetectServices; - eType = E_DETECTSERVICE; - } - break; - - case 3 : - { - sSetName = CFGNODE_FRAMELOADERS; - rMap = m_lFrameLoaders; - eType = E_FRAMELOADER; - } - break; - - case 4 : - { - sSetName = CFGNODE_CONTENTHANDLERS; - rMap = m_lContentHandlers; - eType = E_CONTENTHANDLER; - } - break; - } - - // generate set - sXML.append("\n"); - java.util.Iterator it = rMap.keySet().iterator(); - while(it.hasNext()) - { - java.lang.String sItem = (java.lang.String)it.next(); - sXML.append("\n"); - sXML.append(getItemAsXML(eType, sItem, nFormat)); - sXML.append("\n"); - } - sXML.append("\n"); - } - - java.io.FileOutputStream aStream = new java.io.FileOutputStream(aXML.getAbsolutePath(), false); - java.io.OutputStreamWriter aWriter = new java.io.OutputStreamWriter(aStream, sEncoding); - java.lang.String sOut = sXML.toString(); - aWriter.write(sOut, 0, sOut.length()); - aWriter.flush(); - aWriter.close(); - } - - //___________________________________________ - - /** converts a type property set from internal format - * to an external one. - * - * @param aMap - * points to the item, which should be converted. - * - * @param nFormat - * specify the requested output format. - * - * @return [java.util.HashMap] - * contains the properties in the requested format. - * - * @throws [java.lang.Exception - * if something fail during convertion. - */ - private static java.util.HashMap convertTypePropsToExternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - java.util.HashMap aResultMap = new java.util.HashMap(); - // copy Name property ... if it exists! - if (aMap.containsKey(PROPNAME_NAME)) - aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); - switch(nFormat) - { - //----------------------------------- - case FORMAT_60 : - { - // copy UIName property unchanged - aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); - - // ignore properties "UIOrder", "PreferredFilter", "DetectService" - // They are not supported for 6.0 types. - - // pack all other properties to one "Data" string value - java.lang.StringBuffer sData = new java.lang.StringBuffer(256); - - sData.append(aMap.get(PROPNAME_PREFERRED)); - sData.append(","); - sData.append(aMap.get(PROPNAME_MEDIATYPE)); - sData.append(","); - sData.append(aMap.get(PROPNAME_CLIPBOARDFORMAT)); - sData.append(","); - - java.util.Vector lList = (java.util.Vector)aMap.get(PROPNAME_URLPATTERN); - int c = lList.size(); - int i = 0; - for (i=0; i aExpandedMap["UIName"] - * aMap["Data" ] => aExpandedMap["Preferred" ], aExpandedMap["MediaType"] etc. ... - * - * @param aMap - * points to the item, which should be converted. - - * @param nFormat - * specify the external format. - * - * @return [java.util.HashMap] - * The new map in internal format. - */ - private static java.util.HashMap convertTypePropsToInternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - java.util.HashMap aResultMap = new java.util.HashMap(); - // copy Name property ... if it exists! - if (aMap.containsKey(PROPNAME_NAME)) - aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); - switch(nFormat) - { - //----------------------------------- - case FORMAT_60 : - { - // copy UIName property unchanged! - aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); - - // generate new property "UIOrder" - // Its the moved property "Order" of filters for versions >= 6.y! - aResultMap.put(PROPNAME_UIORDER, new java.lang.Integer(0)); - - // generate new property "PreferredFilter" - // Its a the moved filter flag "Preferred" for versions >= 6.y! - aResultMap.put(PROPNAME_PREFERREDFILTER, new java.lang.String()); - - // generate new property "DetectService" - // Every type know its detector diretcly from now. No search - // will be neccessary any longer. - aResultMap.put(PROPNAME_DETECTSERVICE, new java.lang.String()); - - // analyze the Data property of the original map - // and copy its results (means all expanded properties) - // to the result map. - java.lang.String sDataVal = (java.lang.String)aMap.get(PROPNAME_DATA); - java.util.Vector lTokens = Cache.splitTokenString(sDataVal, ","); - - int t = 0; - java.util.Enumeration it = lTokens.elements(); - while (it.hasMoreElements()) - { - java.lang.String sToken = (java.lang.String)it.nextElement(); - switch(t) - { - case 0 : - aResultMap.put(PROPNAME_PREFERRED, new java.lang.Boolean(sToken)); - break; - case 1 : - aResultMap.put(PROPNAME_MEDIATYPE, sToken); - break; - case 2 : - { - /*HACK ersetze %20 mit " " ...*/ - int ni = sToken.indexOf("%20"); - if (ni!=-1) - { - java.lang.String sPatch = sToken.substring(0,ni) + " " + sToken.substring(ni+3); - sToken = sPatch; - } - aResultMap.put(PROPNAME_CLIPBOARDFORMAT, sToken); - } - break; - case 3 : - aResultMap.put(PROPNAME_URLPATTERN, Cache.splitTokenString(sToken, ";")); - break; - case 4 : - aResultMap.put(PROPNAME_EXTENSIONS, Cache.splitTokenString(sToken, ";")); - break; - case 5 : - aResultMap.put(PROPNAME_DOCUMENTICONID, new java.lang.Integer(sToken)); - break; - default : - throw new java.lang.Exception("unsupported format for data value of a type \""+aMap.get(PROPNAME_NAME)+"\" detected."); - } - ++t; - } - } - break; - - //----------------------------------- - case FORMAT_6Y : - { - // copy all supported properties directly - aResultMap.put(PROPNAME_PREFERRED , aMap.get(PROPNAME_PREFERRED )); - aResultMap.put(PROPNAME_MEDIATYPE , aMap.get(PROPNAME_MEDIATYPE )); - aResultMap.put(PROPNAME_CLIPBOARDFORMAT, aMap.get(PROPNAME_CLIPBOARDFORMAT)); - aResultMap.put(PROPNAME_URLPATTERN , aMap.get(PROPNAME_URLPATTERN )); - aResultMap.put(PROPNAME_EXTENSIONS , aMap.get(PROPNAME_EXTENSIONS )); - aResultMap.put(PROPNAME_DOCUMENTICONID , aMap.get(PROPNAME_DOCUMENTICONID )); - aResultMap.put(PROPNAME_UINAME , aMap.get(PROPNAME_UINAME )); - aResultMap.put(PROPNAME_UIORDER , aMap.get(PROPNAME_UIORDER )); - aResultMap.put(PROPNAME_PREFERREDFILTER, aMap.get(PROPNAME_PREFERREDFILTER)); - aResultMap.put(PROPNAME_DETECTSERVICE , aMap.get(PROPNAME_DETECTSERVICE )); - } - break; - - //----------------------------------- - default : - throw new java.lang.Exception("unknown format"); - } - - return aResultMap; - } - - //___________________________________________ - - /** converts a filter property set (using an external format) to - * our internal cache format. - * - * Especialy the data format string will be expanded - * to its real properties. - * - * Schema: - * aMap["UIName"] => aExpandedMap["UIName"] - * aMap["Data" ] => aExpandedMap["Order" ], aExpandedMap["Flags"] etc. ... - * - * @param aMap - * points to the item, which should be converted. - * - * @param nFormat - * specify the external format. - * - * @return [java.util.HashMap] - * The new map in internal format. - */ - private static java.util.HashMap convertFilterPropsToInternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - java.util.HashMap aResultMap = new java.util.HashMap(); - // copy Name property ... if it exists! - if (aMap.containsKey(PROPNAME_NAME)) - aResultMap.put(PROPNAME_NAME, aMap.get(PROPNAME_NAME)); - switch(nFormat) - { - //----------------------------------- - case FORMAT_60 : - { - // copy UIName property - aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); - - // analyze the Data property of the original map - // and copy its results (means all expanded properties) - // to the result map. - java.lang.String sDataVal = (java.lang.String)aMap.get(PROPNAME_DATA); - java.util.Vector lTokens = Cache.splitTokenString(sDataVal, ","); - - int t = 0; - java.util.Enumeration it = lTokens.elements(); - while (it.hasMoreElements()) - { - java.lang.String sToken = (java.lang.String)it.nextElement(); - switch(t) - { - case 0 : - aResultMap.put(PROPNAME_ORDER, new java.lang.Integer(sToken)); - break; - case 1 : - aResultMap.put(PROPNAME_TYPE, sToken); - break; - case 2 : - aResultMap.put(PROPNAME_DOCUMENTSERVICE, sToken); - break; - case 3 : - aResultMap.put(PROPNAME_FILTERSERVICE, sToken); - break; - case 4 : - aResultMap.put(PROPNAME_FLAGS, new java.lang.Integer(sToken)); - break; - case 5 : - aResultMap.put(PROPNAME_USERDATA, Cache.splitTokenString(sToken, ";")); - break; - case 6 : - aResultMap.put(PROPNAME_FILEFORMATVERSION, new java.lang.Integer(sToken)); - break; - case 7 : - aResultMap.put(PROPNAME_TEMPLATENAME, sToken); - break; - case 8 : - aResultMap.put(PROPNAME_UICOMPONENT, sToken); - break; - default : - throw new java.lang.Exception("unsupported format for data value of a filter detected."); - } - ++t; - } - - // its an optional property :-) - if (!aResultMap.containsKey(PROPNAME_TEMPLATENAME)) - aResultMap.put(PROPNAME_TEMPLATENAME, new java.lang.String("")); - - // its an optional property :-) - if (!aResultMap.containsKey(PROPNAME_UICOMPONENT)) - aResultMap.put(PROPNAME_UICOMPONENT, new java.lang.String("")); - } - break; - - //----------------------------------- - case FORMAT_6Y : - { - // "Order" does not exist for 6.y versions! Use default. - aResultMap.put(PROPNAME_ORDER, new java.lang.Integer(0)); - - // "UIName" property does not exist for 6.y versions! use default. - /* TODO make it configurable :-) */ - aResultMap.put(PROPNAME_UINAME, aMap.get(PROPNAME_UINAME)); - //aResultMap.put(PROPNAME_UINAME, new java.util.HashMap()); - - // "Flags" must be converted from names to its values - java.util.Vector lFlags = (java.util.Vector)aMap.get(PROPNAME_FLAGS); - java.lang.Integer nFlags = Cache.convertFilterFlagNames2Values(lFlags); - aResultMap.put(PROPNAME_FLAGS, nFlags); - - // copy all direct supported properties - aResultMap.put(PROPNAME_TYPE , aMap.get(PROPNAME_TYPE )); - aResultMap.put(PROPNAME_DOCUMENTSERVICE , aMap.get(PROPNAME_DOCUMENTSERVICE )); - aResultMap.put(PROPNAME_FILTERSERVICE , aMap.get(PROPNAME_ORDER )); - aResultMap.put(PROPNAME_USERDATA , aMap.get(PROPNAME_USERDATA )); - aResultMap.put(PROPNAME_FILEFORMATVERSION, aMap.get(PROPNAME_FILEFORMATVERSION)); - aResultMap.put(PROPNAME_TEMPLATENAME , aMap.get(PROPNAME_TEMPLATENAME )); - aResultMap.put(PROPNAME_UICOMPONENT , aMap.get(PROPNAME_UICOMPONENT )); - } - break; - - //----------------------------------- - default : - throw new java.lang.Exception("unknown format"); - } - - return aResultMap; - } - - private static java.util.HashMap convertDetectServicePropsToInternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - /*FIXME*/ - java.util.HashMap aResultMap = aMap; - return aResultMap; - } - - private static java.util.HashMap convertFrameLoaderPropsToInternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - /*FIXME*/ - java.util.HashMap aResultMap = aMap; - return aResultMap; - } - - private static java.util.HashMap convertContentHandlerPropsToInternal(java.util.HashMap aMap , - int nFormat) - throws java.lang.Exception - { - /*FIXME*/ - java.util.HashMap aResultMap = aMap; - return aResultMap; - } - - //___________________________________________ - - /** converts filter flag names to its int representation. - * - * @param lFlags - * a list of flag names. - * - * @return [java.lang.Integer] - * an integer field of all set flags. - * - * @throws [java.lang.Exception] - * for unsupported flags or empty flag fields! - */ - private static java.lang.Integer convertFilterFlagNames2Values(java.util.Vector lFlags) - throws java.lang.Exception - { - int nFlags = 0; - java.util.Enumeration it = lFlags.elements(); - while(it.hasMoreElements()) - { - java.lang.String sFlagName = (java.lang.String)it.nextElement(); - - if (sFlagName.equals(FLAGNAME_3RDPARTYFILTER)) - nFlags |= FLAGVAL_3RDPARTYFILTER; - else - if (sFlagName.equals(FLAGNAME_ALIEN)) - nFlags |= FLAGVAL_ALIEN; - else - if (sFlagName.equals(FLAGNAME_ASYNCHRON)) - nFlags |= FLAGVAL_ASYNCHRON; - else - if (sFlagName.equals(FLAGNAME_BROWSERPREFERRED)) - nFlags |= FLAGVAL_BROWSERPREFERRED; - else - if (sFlagName.equals(FLAGNAME_CONSULTSERVICE)) - nFlags |= FLAGVAL_CONSULTSERVICE; - else - if (sFlagName.equals(FLAGNAME_DEFAULT)) - nFlags |= FLAGVAL_DEFAULT; - else - if (sFlagName.equals(FLAGNAME_EXPORT)) - nFlags |= FLAGVAL_EXPORT; - else - if (sFlagName.equals(FLAGNAME_IMPORT)) - nFlags |= FLAGVAL_IMPORT; - else - if (sFlagName.equals(FLAGNAME_INTERNAL)) - nFlags |= FLAGVAL_INTERNAL; - else - if (sFlagName.equals(FLAGNAME_NOTINCHOOSER)) - nFlags |= FLAGVAL_NOTINCHOOSER; - else - if (sFlagName.equals(FLAGNAME_NOTINFILEDIALOG)) - nFlags |= FLAGVAL_NOTINFILEDIALOG; - else - if (sFlagName.equals(FLAGNAME_NOTINSTALLED)) - nFlags |= FLAGVAL_NOTINSTALLED; - else - if (sFlagName.equals(FLAGNAME_OWN)) - nFlags |= FLAGVAL_OWN; - else - if (sFlagName.equals(FLAGNAME_PACKED)) - nFlags |= FLAGVAL_PACKED; - else - if (sFlagName.equals(FLAGNAME_PREFERRED)) - nFlags |= FLAGVAL_PREFERRED; - else - if (sFlagName.equals(FLAGNAME_READONLY)) - nFlags |= FLAGVAL_READONLY; - else - if (sFlagName.equals(FLAGNAME_SILENTEXPORT)) - nFlags |= FLAGVAL_SILENTEXPORT; - else - if (sFlagName.equals(FLAGNAME_TEMPLATE)) - nFlags |= FLAGVAL_TEMPLATE; - else - if (sFlagName.equals(FLAGNAME_TEMPLATEPATH)) - nFlags |= FLAGVAL_TEMPLATEPATH; - else - if (sFlagName.equals(FLAGNAME_USESOPTIONS)) - nFlags |= FLAGVAL_USESOPTIONS; - else - if (sFlagName.equals(FLAGNAME_COMBINED)) - nFlags |= FLAGVAL_COMBINED; - else - throw new java.lang.Exception("unsupported filter flag detected: \""+sFlagName+"\""); - } - - if (nFlags == 0) - throw new java.lang.Exception("no filter flags?"); - - return new java.lang.Integer(nFlags); - } - - //___________________________________________ - - /** converts filter flag values to its string representation. - * - * @param nFlags - * the flag field as int value. - * - * @return [java.util.Vector] - * a list of flag names. - * - * @throws [java.lang.Exception] - * for unsupported flags or empty flag fields! - */ - private static java.util.Vector convertFilterFlagValues2Names(java.lang.Integer nFlags) - throws java.lang.Exception - { - java.util.Vector lFlags = new java.util.Vector(); - int field = nFlags.intValue(); - - if (field == 0) - throw new java.lang.Exception("no filter flags?"); - - if((field & FLAGVAL_IMPORT) == FLAGVAL_IMPORT) - lFlags.add(FLAGNAME_IMPORT); - - if((field & FLAGVAL_EXPORT) == FLAGVAL_EXPORT) - lFlags.add(FLAGNAME_EXPORT); - - if((field & FLAGVAL_TEMPLATE) == FLAGVAL_TEMPLATE) - lFlags.add(FLAGNAME_TEMPLATE); - - if((field & FLAGVAL_INTERNAL) == FLAGVAL_INTERNAL) - lFlags.add(FLAGNAME_INTERNAL); - - if((field & FLAGVAL_TEMPLATEPATH) == FLAGVAL_TEMPLATEPATH) - lFlags.add(FLAGNAME_TEMPLATEPATH); - - if((field & FLAGVAL_OWN) == FLAGVAL_OWN) - lFlags.add(FLAGNAME_OWN); - - if((field & FLAGVAL_ALIEN) == FLAGVAL_ALIEN) - lFlags.add(FLAGNAME_ALIEN); - - if((field & FLAGVAL_USESOPTIONS) == FLAGVAL_USESOPTIONS) - lFlags.add(FLAGNAME_USESOPTIONS); - - if((field & FLAGVAL_DEFAULT) == FLAGVAL_DEFAULT) - lFlags.add(FLAGNAME_DEFAULT); - - if((field & FLAGVAL_NOTINFILEDIALOG) == FLAGVAL_NOTINFILEDIALOG) - lFlags.add(FLAGNAME_NOTINFILEDIALOG); - - if((field & FLAGVAL_NOTINCHOOSER) == FLAGVAL_NOTINCHOOSER) - lFlags.add(FLAGNAME_NOTINCHOOSER); - - if((field & FLAGVAL_ASYNCHRON) == FLAGVAL_ASYNCHRON) - lFlags.add(FLAGNAME_ASYNCHRON); - - if((field & FLAGVAL_READONLY) == FLAGVAL_READONLY) - lFlags.add(FLAGNAME_READONLY); - - if((field & FLAGVAL_NOTINSTALLED) == FLAGVAL_NOTINSTALLED) - lFlags.add(FLAGNAME_NOTINSTALLED); - - if((field & FLAGVAL_CONSULTSERVICE) == FLAGVAL_CONSULTSERVICE) - lFlags.add(FLAGNAME_CONSULTSERVICE); - - if((field & FLAGVAL_3RDPARTYFILTER) == FLAGVAL_3RDPARTYFILTER) - lFlags.add(FLAGNAME_3RDPARTYFILTER); - - if((field & FLAGVAL_PACKED) == FLAGVAL_PACKED) - lFlags.add(FLAGNAME_PACKED); - - if((field & FLAGVAL_SILENTEXPORT) == FLAGVAL_SILENTEXPORT) - lFlags.add(FLAGNAME_SILENTEXPORT); - - if((field & FLAGVAL_BROWSERPREFERRED) == FLAGVAL_BROWSERPREFERRED) - lFlags.add(FLAGNAME_BROWSERPREFERRED); - - if((field & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED) - lFlags.add(FLAGNAME_PREFERRED); - - if((field & FLAGVAL_COMBINED) == FLAGVAL_COMBINED) - lFlags.add(FLAGNAME_COMBINED); - - if((field & FLAGVAL_COMBINED) == FLAGVAL_SUPPORTSSELECTION) - lFlags.add(FLAGNAME_SUPPORTSSELECTION); - - return lFlags; - } - - //___________________________________________ - - /** return a reference to one of our member - * lists for types/filters etc ... - * - * @param eItemType - * specify, which item map is required. - * - * @return [java.util.HashMap] - * a reference(!) to the right member. - * - * @throws [java.lang.Exception] - * if the specified map does not exist. - */ - private java.util.HashMap getItemMap(int eItemType) - throws java.lang.Exception - { - java.util.HashMap rMap = null; - switch(eItemType) - { - case E_TYPE : - rMap = m_lTypes; - break; - - case E_FILTER : - rMap = m_lFilters; - break; - - case E_DETECTSERVICE : - rMap = m_lDetectServices; - break; - - case E_FRAMELOADER : - rMap = m_lFrameLoaders; - break; - - case E_CONTENTHANDLER : - rMap = m_lContentHandlers; - break; - - default: - throw new java.lang.Exception("Invalid item map specified."); - } - return rMap; - } - - //___________________________________________ - - /** return the count of items inside a sub container - * of this cache. - * - * @param eItemType - * specify, which item map is required. - * - * @throws [java.lang.Exception] - * if the specified map does not exist. - */ - public synchronized int getItemCount(int eItemType) - throws java.lang.Exception - { - java.util.HashMap rMap = getItemMap(eItemType); - return rMap.size(); - } - - //___________________________________________ - - /** get a list of all item names of the specified - * sub container. - * - * @param eItemType - * specify, which item map is required. - * - * @throws [java.lang.Exception] - * if the specified map does not exist. - */ - public synchronized java.util.Vector getItemNames(int eItemType) - throws java.lang.Exception - { - java.util.Vector lNames = new java.util.Vector(); - java.util.HashMap rMap = getItemMap(eItemType); - java.util.Iterator it = rMap.keySet().iterator(); - while(it.hasNext()) - lNames.add(it.next()); - return lNames; - } - - //___________________________________________ - - /** get a list of all item names of the specified - * sub coontainer, where items match to given property set. - * - * Note: The given property set must exist at all - * returned items as minimum and every checked property - * value must be equals! Using of reg expressions or - * similar mechanism will not be supported here. - * - * @param eItemType - * specify, which item map is required. - * - * @param aPropSet - * the set of properties, which must - * exist at the returned item as minimum. - * - * @throws [java.lang.Exception] - * if the specified map does not exist. - */ - public synchronized java.util.Vector getMatchedItemNames(int eItemType, - java.util.HashMap aPropSet ) - throws java.lang.Exception - { - java.util.Vector lNames = new java.util.Vector(); - java.util.HashMap rMap = getItemMap(eItemType); - java.util.Iterator it = rMap.keySet().iterator(); - while(it.hasNext()) - { - java.lang.String sItemName = (java.lang.String)it.next(); - java.util.HashMap rItemProps = (java.util.HashMap)rMap.get(sItemName); - - boolean bMatch = Cache.matchPropSet(rItemProps, aPropSet); - if (bMatch) - lNames.add(sItemName); - else - { - java.lang.StringBuffer sBuffer = new java.lang.StringBuffer(1000); - sBuffer.append("entry ["+eItemType+"] \""+sItemName+"\" does not match.\n"); - sBuffer.append("\torg items = {"+rItemProps+"}\n"); - sBuffer.append("\treq items = {"+aPropSet+"}\n"); - - m_aDebug.setDetailedInfo(sBuffer.toString()); - } - } - return lNames; - } - - //___________________________________________ - - /** check if two property sets are equals in its - * shared properties. - * - * Note: Only set properties of the match set will be searched - * inside the original set. And its values must be equals. - * Using of reg expressions or similar mechanism will not - * be supported here. - * - * @param rOrgProps - * the original property set, which should be checked. - * - * @param rMatchProps - * contains the properties, which must be searched - * inside rOrgProps. - * - * @return TRUE if all properties of rMatchProps could be located - * inside rOrgProps. - */ - private static boolean matchPropSet(java.util.HashMap rOrgProps , - java.util.HashMap rMatchProps) - { - java.util.Iterator it = rMatchProps.keySet().iterator(); - while(it.hasNext()) - { - java.lang.String sMatchName = (java.lang.String)it.next(); - java.lang.Object aMatchValue = rMatchProps.get(sMatchName); - - if ( - (!rOrgProps.containsKey(sMatchName) ) || - (!rOrgProps.get(sMatchName).equals(aMatchValue)) - ) - { - return false; - } - } - return true; - } - - //___________________________________________ - - /** return a property set for the queried container item. - * - * @param eItemType - * specify, which item map is required. - * - * @param sItemName - * must be a valid item name of the specified item map. - * - * @return [java.util.HashMap] - * the property set of the queried item. - * Always different from null! - * - * @throws [java.lang.Exception] - * if the specified item does not exists or - * seems to be invalid in general (means null!). - */ - public synchronized java.util.HashMap getItem(int eItemType, - java.lang.String sItemName) - throws java.lang.Exception - { - java.util.HashMap rMap = getItemMap(eItemType); - java.util.HashMap rItem = (java.util.HashMap)rMap.get(sItemName); - if (rItem == null) - throw new java.lang.Exception("Queried item \""+sItemName+"\" does not exist inside this cache."); - return rItem; - } - - //___________________________________________ - - /** return a requested item in XML format. - * - * @param eItemType - * identify the right sub set of this cache - * inside which the requested item should exist. - * e.g. E_TYPE, E_FILTER, ... - * - * @param sItemName - * the name of the request item - * - * @param nXMLFormat - * means the format of the generated xml source. - * - * @return [java.lang.String] - * a xml formated string, which contains all properties - * for this container item. - */ - public synchronized java.lang.String getItemAsXML(int eItemType , - java.lang.String sItemName , - int nXMLFormat) - throws java.lang.Exception - { - // Note: Our internal format must be converted to the target format! - java.util.HashMap rItem = getItem(eItemType, sItemName); - java.util.HashMap rFormatedItem = null; - switch(eItemType) - { - case E_TYPE : - { - rFormatedItem = Cache.convertTypePropsToExternal(rItem, nXMLFormat); - m_aDebug.setGlobalInfo("type to external \""+sItemName+"\""); - } - break; - - case E_FILTER : - { - rFormatedItem = Cache.convertFilterPropsToExternal(rItem, nXMLFormat); - m_aDebug.setGlobalInfo("filter to external \""+sItemName+"\""); - } - break; - - case E_DETECTSERVICE : - { - rFormatedItem = Cache.convertDetectServicePropsToExternal(rItem, nXMLFormat); - m_aDebug.setGlobalInfo("detect service to external \""+sItemName+"\""); - } - break; - - case E_FRAMELOADER : - { - rFormatedItem = Cache.convertFrameLoaderPropsToExternal(rItem, nXMLFormat); - m_aDebug.setGlobalInfo("frame loader to external \""+sItemName+"\""); - } - break; - - case E_CONTENTHANDLER : - { - rFormatedItem = Cache.convertContentHandlerPropsToExternal(rItem, nXMLFormat); - m_aDebug.setGlobalInfo("content handler to external \""+sItemName+"\""); - } - break; - } - - java.lang.StringBuffer sXML = new java.lang.StringBuffer(1000); - int nPrettyTabs = 1; - for (int t=0; t\n"); - sXML.append(XMLHelper.convertPropSetToXML(rFormatedItem, nPrettyTabs+1)); - for (int t=0; t\n"); - - return sXML.toString(); - } - - //___________________________________________ - - /** split the given string (using the specified delimiter) - * and return alist of found string tokens. - * - * Note: Against the normal behaviour of the StringTokenizer class - * this method returns empty tokens too. - * E.g: "0,,1" will return "0" - "" - "1" - * - * @param sTokenString - * the string value, which should be analyzed. - * - * @param sDelim - * the delimiter, which will be used to differe between tokens. - * - * @return [java.util.Vector] - * a list of string tokens. Can be empty - but not null! - */ - private static java.util.Vector splitTokenString(java.lang.String sTokenString, - java.lang.String sDelim ) - { - java.util.Vector lTokens = new java.util.Vector(); - java.util.StringTokenizer aTokenizer = new java.util.StringTokenizer(sTokenString, sDelim, true); - boolean bLastWasDelim = false; - - while (aTokenizer.hasMoreTokens()) - { - java.lang.String sToken = aTokenizer.nextToken(); - if (sToken.equals(sDelim)) - { - if (bLastWasDelim) - { - // last token was a delimiter - new one too - // => an empty token must be placed between these - // two delimiters! Add this empty value to the return list. - lTokens.add(""); - } - else - { - // last token was not a delimiter - new one is such delim - // => ignore this delimiter - but save the information, that - // it occured - bLastWasDelim = true; - } - } - else - { - // new token is no delim - // => Add it to the return list. - lTokens.add(sToken); - // Dont forget to reset this information - so next loop - // will do the right things! - bLastWasDelim = false; - } - } - - return lTokens; - } - - //___________________________________________ - - /** - */ - public synchronized void analyze() - { - m_nDoubleRegisteredFilters = 0; - m_nTypesForFilters = 0; - m_nTypesForDetectServices = 0; - m_nTypesForFrameLoaders = 0; - m_nTypesForContentHandlers = 0; - - // create table of types and all registered filters for such types - // By the way: count all double registrations, where a filter - // uses the same type then another filter. - m_lFilterToTypeRegistrations = new java.util.HashMap(); - java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); - while (aIt1.hasNext()) - { - java.lang.String sFilter = (java.lang.String)aIt1.next(); - java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); - java.lang.String sType = (java.lang.String)aFilter.get(PROPNAME_TYPE); - - java.util.Vector lFilters = (java.util.Vector)m_lFilterToTypeRegistrations.get(sType); - if (lFilters == null) - lFilters = new java.util.Vector(); - else - ++m_nDoubleRegisteredFilters; - lFilters.add(sFilter); - m_lFilterToTypeRegistrations.put(sType, lFilters); - } - - // count, how many types are used by filters, frame loaders or content handlers - aIt1 = m_lTypes.keySet().iterator(); - while (aIt1.hasNext()) - { - java.lang.String sType = (java.lang.String)aIt1.next(); - - java.util.Iterator aIt2 = m_lFilters.keySet().iterator(); - while (aIt2.hasNext()) - { - java.lang.String sItem = (java.lang.String)aIt2.next(); - java.util.HashMap aItem = (java.util.HashMap)m_lFilters.get(sItem); - java.lang.String sTypeReg = (java.lang.String)aItem.get(PROPNAME_TYPE); - - if (sTypeReg.equals(sType)) - { - ++m_nTypesForFilters; - break; - } - } - - aIt2 = m_lDetectServices.keySet().iterator(); - while (aIt2.hasNext()) - { - java.lang.String sItem = (java.lang.String)aIt2.next(); - java.util.HashMap aItem = (java.util.HashMap)m_lDetectServices.get(sItem); - java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); - - if (lTypeReg.contains(sType)) - { - ++m_nTypesForDetectServices; - break; - } - } - - aIt2 = m_lFrameLoaders.keySet().iterator(); - while (aIt2.hasNext()) - { - java.lang.String sItem = (java.lang.String)aIt2.next(); - java.util.HashMap aItem = (java.util.HashMap)m_lFrameLoaders.get(sItem); - java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); - - if (lTypeReg.contains(sType)) - { - ++m_nTypesForFrameLoaders; - break; - } - } - - aIt2 = m_lContentHandlers.keySet().iterator(); - while (aIt2.hasNext()) - { - java.lang.String sItem = (java.lang.String)aIt2.next(); - java.util.HashMap aItem = (java.util.HashMap)m_lContentHandlers.get(sItem); - java.util.Vector lTypeReg = (java.util.Vector)aItem.get(PROPNAME_TYPES); - - if (lTypeReg.contains(sType)) - { - ++m_nTypesForContentHandlers; - break; - } - } - } - } - - //___________________________________________ - - /** validate all cache entries. - * - * It checks if all made registrations are valid; - * try to repair some simple problems; - * create missing informations on demand ... - * - * @param nFormat - * specify, which configuration format - * must be checked. - * - * @throws [java.lang.Exception] - * if an unrecoverable problem occure. - */ - public synchronized void validate(int nFormat) - throws java.lang.Exception - { - validateTypes(nFormat); - validateFilters(nFormat); - } - - //___________________________________________ - - /** validate all type entries of this cache. - * - * @param nFormat - * specify, which configuration format - * must be checked. - * - * @throws [java.lang.Exception] - * if an unrecoverable problem occure. - */ - private void validateTypes(int nFormat) - throws java.lang.Exception - { - java.util.Iterator aIt1 = m_lTypes.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sType = (java.lang.String)aIt1.next(); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sType); - if (aType == null) - throw new java.lang.Exception("type ["+sType+"] dos not exist realy?!"); - - if ( - (!aType.containsKey(PROPNAME_MEDIATYPE )) || - (!aType.containsKey(PROPNAME_PREFERRED )) || - (!aType.containsKey(PROPNAME_CLIPBOARDFORMAT)) || - (!aType.containsKey(PROPNAME_DOCUMENTICONID )) || - (!aType.containsKey(PROPNAME_URLPATTERN )) || - (!aType.containsKey(PROPNAME_EXTENSIONS )) || - (!aType.containsKey(PROPNAME_UINAME )) - ) - { - throw new java.lang.Exception("Type \""+sType+"\" does not contain all neccessary properties for a 6.0/6.Y format."); - } - - if ( - (((java.util.Vector)aType.get(PROPNAME_EXTENSIONS)).isEmpty()) && - (((java.util.Vector)aType.get(PROPNAME_URLPATTERN)).isEmpty()) - ) - { - throw new java.lang.Exception("Type \""+sType+"\" does not contain any extension nor an url pattern."); - } - - if (((java.util.HashMap)aType.get(PROPNAME_UINAME)).isEmpty()) - throw new java.lang.Exception("Type \""+sType+"\" is not localized."); - - if (nFormat == FORMAT_6Y) - { - if ( - (!aType.containsKey(PROPNAME_UIORDER )) || - (!aType.containsKey(PROPNAME_PREFERREDFILTER)) || - (!aType.containsKey(PROPNAME_DETECTSERVICE )) - ) - { - throw new java.lang.Exception("Type \""+sType+"\" does not contain all neccessary properties for a 6.Y format."); - } - - if (((java.lang.Integer)aType.get(PROPNAME_UIORDER)).intValue() < 0) - throw new java.lang.Exception("Type \""+sType+"\" has invalid value for prop UIOrder."); - - if (((java.lang.String)aType.get(PROPNAME_DETECTSERVICE)).length() < 1) - m_aDebug.setWarning("Type \""+sType+"\" has no detect service registered."); - - java.lang.String sPreferredReg = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); - if ( - (sPreferredReg == null) || - (sPreferredReg.length() < 1 ) - ) - { - m_aDebug.setWarning("Type \""+sType+"\" has no preferred filter ..."); - /*FIXME - * OK - not every type has a filter registered .. but the - * a frame loader MUST(!) exist! Check it. - */ - } - else - { - if (!m_lFilters.containsKey(sPreferredReg)) - throw new java.lang.Exception("Type \""+sType+"\" has no valid preferred filter registration [\""+sPreferredReg+"\"]."); - } - } - } - } - - //___________________________________________ - - /** validate all filter entries of this cache. - * - * @param nFormat - * specify, which configuration format - * must be checked. - * - * @throws [java.lang.Exception] - * if an unrecoverable problem occure. - */ - public synchronized void validateFilters(int nFormat) - throws java.lang.Exception - { - java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sFilter = (java.lang.String)aIt1.next(); - java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); - if (aFilter == null) - throw new java.lang.Exception("filter ["+sFilter+"] dos not exist realy?!"); - - if ( - (!aFilter.containsKey(PROPNAME_DOCUMENTSERVICE )) || - (!aFilter.containsKey(PROPNAME_FILEFORMATVERSION)) || - (!aFilter.containsKey(PROPNAME_FILTERSERVICE )) || - (!aFilter.containsKey(PROPNAME_FLAGS )) || - (!aFilter.containsKey(PROPNAME_TEMPLATENAME )) || - (!aFilter.containsKey(PROPNAME_TYPE )) || - (!aFilter.containsKey(PROPNAME_UICOMPONENT )) || - (!aFilter.containsKey(PROPNAME_USERDATA )) - ) - { - throw new java.lang.Exception("Filter \""+sFilter+"\" does not contain all neccessary properties for a 6.0/6.Y format."); - } - - if (((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue() < 1) - throw new java.lang.Exception("Filter \""+sFilter+"\" does not have a valid flag field."); - - if (!m_lTypes.containsKey(aFilter.get(PROPNAME_TYPE))) - throw new java.lang.Exception("Filter \""+sFilter+"\" is not registered for a well known type."); - - if (nFormat == FORMAT_60) - { - if ( - (!aFilter.containsKey(PROPNAME_ORDER )) || - (!aFilter.containsKey(PROPNAME_UINAME)) - ) - { - throw new java.lang.Exception("Filter \""+sFilter+"\" does not contain all neccessary properties for a 6.0 format."); - } - - if (((java.lang.Integer)aFilter.get(PROPNAME_ORDER)).intValue() < 0) - throw new java.lang.Exception("Filter \""+sFilter+"\" does not have a valid Order value."); - - if (((java.util.HashMap)aFilter.get(PROPNAME_UINAME)).isEmpty()) - throw new java.lang.Exception("Filter \""+sFilter+"\" is not localized."); - } -/*TODO - depends from the configuration item "remove_filter_flag_preferred" ... - - if (nFormat == FORMAT_6Y) - { - int flags = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); - if ((flags & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED) - throw new java.lang.Exception("Filter \""+sFilter+"\" has superflous Preferred flag set. Please remove this flag. ["+flags+"]"); - } -*/ - } - } - - /*TODO - * - remove graphic filters! - * - move detect services to types - */ - - public synchronized void transform60to6Y(boolean bCreateCombineFilterFlag , - boolean bRemoveFilterFlagBrowserPreferred, - boolean bRemoveFilterFlagPreferred , - boolean bRemoveFilterFlag3rdparty , - boolean bRemoveFilterUINames , - boolean bRemoveGraphicFilters , - boolean bSetDefaultDetector ) - throws java.lang.Exception - { - // remove some superflous cache entries ... - // everything related to "load macros" - // Macros should be dispatched instead of loaded! - if (m_lTypes.containsKey("macro")) - { - m_lTypes.remove("macro"); - m_aDebug.setDetailedInfo("superflous type \"macro\" was removed"); - } - if (m_lFrameLoaders.containsKey("com.sun.star.comp.sfx2.SfxMacroLoader")) - { - m_lFrameLoaders.remove("com.sun.star.comp.sfx2.SfxMacroLoader"); - m_aDebug.setDetailedInfo("superflous frame loader \"com.sun.star.comp.sfx2.SfxMacroLoader\" was removed"); - } - - // step over all filters and check her properties and references - java.util.Vector lPreferredFilters = new java.util.Vector(); - java.util.Vector lNoRealFilters = new java.util.Vector(); - java.util.Iterator aIt1 = m_lFilters.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sFilter = (java.lang.String)aIt1.next(); - java.util.HashMap aFilter = (java.util.HashMap)m_lFilters.get(sFilter); - - // remove the "graphic helper filters" used by draw and impress - // They dont have any valid document service name set and cant be handled - // by our generic FrameLoader! - // They must be moved to her own configuration ... - - if ( - (bRemoveGraphicFilters ) && - (((java.lang.String)aFilter.get(PROPNAME_DOCUMENTSERVICE)).length() < 1) - ) - { - lNoRealFilters.add(sFilter); - continue; - } - - java.lang.String sTypeReg = (java.lang.String)aFilter.get(PROPNAME_TYPE); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); - - // move UINames of filters to types - java.util.HashMap lFilterUINames = (java.util.HashMap)aFilter.get(PROPNAME_UINAME); - java.util.HashMap lTypeUINames = (java.util.HashMap)aType.get(PROPNAME_UINAME); - java.util.HashMap lPatchUINames = new java.util.HashMap(); - - java.util.Iterator pUINames = lTypeUINames.keySet().iterator(); - while(pUINames.hasNext()) - { - java.lang.String sLocale = (java.lang.String)pUINames.next(); - java.lang.String sValue = (java.lang.String)lTypeUINames.get(sLocale); - lPatchUINames.put(sLocale, sValue); - } - - pUINames = lFilterUINames.keySet().iterator(); - while(pUINames.hasNext()) - { - java.lang.String sLocale = (java.lang.String)pUINames.next(); - java.lang.String sValue = (java.lang.String)lFilterUINames.get(sLocale); - lPatchUINames.put(sFilter+":"+sLocale, sValue); - } - aType.put(PROPNAME_UINAME, lPatchUINames); - - // set generic filter service wrapper for our own native filters! - // By the way: The format types of such filters can be detected by our - // generic detector too. - if ( - (bSetDefaultDetector ) && - (((java.lang.String)aFilter.get(PROPNAME_FILTERSERVICE)).length() < 1) - ) - { - /*ME_THINKING aFilter.put(PROPNAME_FILTERSERVICE, FILTERSERVICE_NATIVEWARPPER);*/ - aType.put(PROPNAME_DETECTSERVICE, GENERIC_DETECTSERVICE); - } - - // move the preferred filter information to any type - // Set the filter name to the type for which the filter is registered. - // If this type already have a set PreferredFilter value, check if the current filter - // has the preferred flag set. If not ignore it - otherwhise overwrite the - // current information at the type. But look for multiple preferred filter relations ... - // means: look if more the one filter has set the preferred flag for the same type! - - /* Attention! - * - * Dont remove the preferred flag from any filter! ... not here. - * Otherwhise next loop can't detect ambigous preferred registrations! - * Add filter to a temp. list, which can be used later to remove the preferred - * flag ... - */ - - int flags1 = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); - java.lang.String sDocSrv = (java.lang.String)aFilter.get(PROPNAME_DOCUMENTSERVICE); - if (sDocSrv.length()>0)// without a doc service its not a real filter - its a graphic filter! - { - boolean preferred1 = ((flags1 & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED); - if (preferred1) - lPreferredFilters.add(aFilter); - - java.lang.String sAlreadyRegisteredFilter = (java.lang.String)aType.get(PROPNAME_PREFERREDFILTER); - // no registration => set this filter as "any possible one"! - if (sAlreadyRegisteredFilter.length() < 1) - aType.put(PROPNAME_PREFERREDFILTER, sFilter); - else - { - java.util.HashMap aAlreadyRegisteredFilter = (java.util.HashMap)m_lFilters.get(sAlreadyRegisteredFilter); - int flags2 = ((java.lang.Integer)aAlreadyRegisteredFilter.get(PROPNAME_FLAGS)).intValue(); - boolean preferred2 = ((flags2 & FLAGVAL_PREFERRED) == FLAGVAL_PREFERRED); - - // two preferred filters for the same type! => error - if (preferred1 && preferred2) - { - java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); - sMsg.append("More the one preferred filter detected for the same type.\n"); - sMsg.append("\ttype = \""+sTypeReg+"\"\n"); - sMsg.append("\tfilter[1] = \""+sAlreadyRegisteredFilter+"\"\n"); - sMsg.append("\tfilter[2] = \""+sFilter+"\"\n"); - throw new java.lang.Exception(sMsg.toString()); - } - else - // overwrite the "any possible" filter with a real preferred one - if (preferred1 && !preferred2) - aType.put(PROPNAME_PREFERREDFILTER, sFilter); - } - } - - // create the new combined filter flag if required - if (bCreateCombineFilterFlag) - { - if ( - ((flags1 & FLAGVAL_IMPORT) == FLAGVAL_IMPORT) && - ((flags1 & FLAGVAL_EXPORT) == FLAGVAL_EXPORT) - ) - { - flags1 |= FLAGVAL_COMBINED; - flags1 &= ~FLAGVAL_IMPORT ; - flags1 &= ~FLAGVAL_EXPORT ; - aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); - } - } - - // remove some obsolete filter flags - if (bRemoveFilterFlagBrowserPreferred) - { - flags1 &= ~FLAGVAL_BROWSERPREFERRED; - aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); - } - - if (bRemoveFilterFlag3rdparty) - { - flags1 &= ~FLAGVAL_3RDPARTYFILTER; - aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags1)); - } - - // if its a filter with an UI order ... - // move this information to the registered type. - // Note: Because more then one filter can be registered for the same type. - // Handle it as an error ... till we find a better transformation! - java.lang.Integer nOrder = (java.lang.Integer)aFilter.get(PROPNAME_ORDER); - java.lang.Integer nUIOrder = (java.lang.Integer)aType.get(PROPNAME_UIORDER); - int order = nOrder.intValue(); - int uiorder = nUIOrder.intValue(); - - if (order > 0) - { - if ( - (uiorder < 1 ) || - (uiorder > order) - ) - { - aType.put(PROPNAME_UIORDER, nOrder); - m_aDebug.setDetailedInfo("moved order value "+nOrder+" from filter \""+sFilter+"\" to type \""+sTypeReg+"\""); - } - else - m_aDebug.setDetailedInfo("ignore order value [order="+nOrder+",uiorder="+nUIOrder+"] for filter \""+sFilter+"\" and type \""+sTypeReg+"\""); - } - } - - // NOW ... remove the preferred flags from every filter, which it has set. - java.util.Enumeration aIt2 = null; - if (bRemoveFilterFlagPreferred) - { - aIt2 = lPreferredFilters.elements(); - while (aIt2.hasMoreElements()) - { - java.util.HashMap aFilter = (java.util.HashMap)aIt2.nextElement(); - int flags = ((java.lang.Integer)aFilter.get(PROPNAME_FLAGS)).intValue(); - flags &= ~FLAGVAL_PREFERRED; - aFilter.put(PROPNAME_FLAGS, new java.lang.Integer(flags)); - } - } - - // NOW ... remove all "no real filters" like the graphich helper filters of - // draw and impress! - aIt2 = lNoRealFilters.elements(); - while (aIt2.hasMoreElements()) - m_lFilters.remove(aIt2.nextElement()); - - // step over all detect services and move this information directly to - // the corresponding types - // Overwrite possibel default registrations with a real existing one! - aIt1 = m_lDetectServices.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sDetector = (java.lang.String)aIt1.next(); - java.util.HashMap aDetector = (java.util.HashMap)m_lDetectServices.get(sDetector); - java.util.Vector lTypeReg = (java.util.Vector)aDetector.get(PROPNAME_TYPES); - aIt2 = lTypeReg.elements(); - while(aIt2.hasMoreElements()) - { - java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); - - if (aType == null) - { - m_aDebug.setWarning("Detector \""+sDetector+"\" seem to be registered for unknown type \""+sTypeReg+"\""); - continue; - } - - java.lang.Object aAlreadyRegisteredDetector = aType.get(PROPNAME_DETECTSERVICE); - if (aAlreadyRegisteredDetector != null && ((java.lang.String)aAlreadyRegisteredDetector).length() > 0) - { - java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); - sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a detect service\n"); - sMsg.append("\tdetect service[1] = \""+(java.lang.String)aAlreadyRegisteredDetector+"\"\n"); - sMsg.append("\tdetect service[2] = \""+sDetector+"\"\n"); - m_aDebug.setWarning(sMsg.toString()); - } - aType.put(PROPNAME_DETECTSERVICE, sDetector); - m_aDebug.setGlobalInfo("move detector \""+sDetector+"\" to type \""+sTypeReg+"\""); - } - } - - // because all detect service was registered as type properties directly ... - // remove all detect service objects of this cache! - m_lDetectServices.clear(); - - // step over all frame loader and move this information directly to - // the corresponding types - // Overwrite possibel default registrations with a real existing one! - aIt1 = m_lFrameLoaders.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sLoader = (java.lang.String)aIt1.next(); - java.util.HashMap aLoader = (java.util.HashMap)m_lFrameLoaders.get(sLoader); - java.util.Vector lTypeReg = (java.util.Vector)aLoader.get(PROPNAME_TYPES); - aIt2 = lTypeReg.elements(); - while(aIt2.hasMoreElements()) - { - java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); - java.lang.String sAlreadyRegisteredLoader = (java.lang.String)aType.get(PROPNAME_FRAMELOADER); - if (sAlreadyRegisteredLoader != null && sAlreadyRegisteredLoader.length() > 0) - { - java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); - sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a frame loader\n"); - sMsg.append("\tframe loader[1] = \""+sAlreadyRegisteredLoader+"\"\n"); - sMsg.append("\tframe loader[2] = \""+sLoader+"\"\n"); - m_aDebug.setWarning(sMsg.toString()); - } - aType.put(PROPNAME_FRAMELOADER, sLoader); - System.out.println("move loader \""+sLoader+"\" to type \""+sTypeReg+"\""); - } - } - - m_lFrameLoaders.clear(); - - // step over all content handler and move this information directly to - // the corresponding types - // Overwrite possibel default registrations with a real existing one! - aIt1 = m_lContentHandlers.keySet().iterator(); - while(aIt1.hasNext()) - { - java.lang.String sHandler = (java.lang.String)aIt1.next(); - java.util.HashMap aHandler = (java.util.HashMap)m_lContentHandlers.get(sHandler); - java.util.Vector lTypeReg = (java.util.Vector)aHandler.get(PROPNAME_TYPES); - aIt2 = lTypeReg.elements(); - while(aIt2.hasMoreElements()) - { - java.lang.String sTypeReg = (java.lang.String)aIt2.nextElement(); - java.util.HashMap aType = (java.util.HashMap)m_lTypes.get(sTypeReg); - java.lang.String sAlreadyRegisteredHandler = (java.lang.String)aType.get(PROPNAME_CONTENTHANDLER); - if (sAlreadyRegisteredHandler != null && sAlreadyRegisteredHandler.length() > 0) - { - java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); - sMsg.append("type \""+sTypeReg+"\" has ambigous registrations of a content handler\n"); - sMsg.append("\tcontent handler[1] = \""+sAlreadyRegisteredHandler+"\"\n"); - sMsg.append("\tcontent handler[2] = \""+sHandler+"\"\n"); - m_aDebug.setWarning(sMsg.toString()); - } - aType.put(PROPNAME_CONTENTHANDLER, sHandler); - System.out.println("move handler \""+sHandler+"\" to type \""+sTypeReg+"\""); - } - } - - m_lContentHandlers.clear(); - -/* - int c = m_lTypes.size(); - java.lang.String[] lT1 = new java.lang.String[c]; - java.lang.String[] lT2 = new java.lang.String[c]; - long nUPS = 0; - - int i = 0; - aIt1 = m_lTypes.keySet().iterator(); - while(aIt1.hasNext()) - { - lT1[i] = (java.lang.String)aIt1.next(); - lT2[i] = lT1[i]; - ++i; - } - - for (int i1=0; i1 search from left to right - int len = lCommandLineArgs[arg].length(); - int pos = lCommandLineArgs[arg].indexOf('='); - if (pos != -1) - { - java.lang.String sArg = lCommandLineArgs[arg].substring(0,pos); - java.lang.String sValue = lCommandLineArgs[arg].substring(pos+1); - setProperty(sArg, sValue); - continue; - } - - // is it a boolean argument? - // Note: Because "--" and "-" will be interpreted as the same - // we search from right to left! - pos = lCommandLineArgs[arg].lastIndexOf('-'); - if (pos == -1) - pos = lCommandLineArgs[arg].lastIndexOf('/'); - if (pos != -1) - { - java.lang.String sArg = lCommandLineArgs[arg].substring(pos+1); - setProperty(sArg, java.lang.String.valueOf(true)); - continue; - } - - // There is an unknown format used by this argument ... - throw new MalformedCommandLineException("Invalid command line detected. The argument \""+lCommandLineArgs[arg]+"\" use an unsupported format."); - } - } - - //------------------------------------------- - /** indicates if the given command line includes - * a help request. - * - * @return True if there was an explicit help request. - */ - public synchronized boolean isHelp() - { - return ( - (containsKey("help")) || - (containsKey("?") ) || - (containsKey("h") ) - ); - } - - //------------------------------------------- - /** indicates if the gioven command line was empty. - * - * @return True if there was an empty command line. - */ - public synchronized boolean isEmpty() - { - return m_bEmpty; - } - - //------------------------------------------- - /** returns the value of sProp as boolean value. - * - * @param sProp - * the name of the parameter. - * - * @return The boolean value of the requested property. - * - * @throw [NoSuchElementException] - * if the requested property does not exists. - */ - public synchronized boolean getBoolean(java.lang.String sProp) - throws java.util.NoSuchElementException - { - java.lang.String sValue = getProperty(sProp); - if (sValue == null) - throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); - return new java.lang.Boolean(sValue).booleanValue(); - } - - public synchronized boolean getBoolean(java.lang.String sProp , - boolean bDefault) - { - java.lang.String sDefault = java.lang.String.valueOf(bDefault); - java.lang.String sValue = getProperty(sProp, sDefault); - return new java.lang.Boolean(sValue).booleanValue(); - } - - //------------------------------------------- - /** returns the value of sProp as int value. - * - * @param sProp - * the name of the parameter. - * - * @return The int value of the requested property. - * - * @throw [NoSuchElementException] - * if the requested property does not exists. - */ - public synchronized int getInt(java.lang.String sProp) - throws java.util.NoSuchElementException - { - java.lang.String sValue = getProperty(sProp); - if (sValue == null) - throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); - return new java.lang.Integer(sValue).intValue(); - } - - public synchronized int getInt(java.lang.String sProp , - int nDefault) - { - java.lang.String sDefault = java.lang.String.valueOf(nDefault); - java.lang.String sValue = getProperty(sProp, sDefault); - return new java.lang.Integer(sValue).intValue(); - } - - //------------------------------------------- - /** returns the value of sProp as string value. - * - * @param sProp - * the name of the parameter. - * - * @return The string value of the requested property. - * - * @throw [NoSuchElementException] - * if the requested property does not exists. - */ - public synchronized java.lang.String getString(java.lang.String sProp) - throws java.util.NoSuchElementException - { - java.lang.String sValue = getProperty(sProp); - if (sValue == null) - throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); - return sValue; - } - - //------------------------------------------- - /** returns the value of sProp as string list value! - * - * @descr The delimiter must be well known and - * it must be clear if trailing/leading - * whitespaces must be ignored or not. - * - * @param sProp - * the name of the parameter. - * - * @param sDelim - * the delimiter, which must be used to split - * the config string value into an array. - * - * @param bTrim - * if its set to true, trailing and leading whitespace - * characters will be ommited. - * - * @param bDecode - * if its set to TRUE all liste items will be - * interpreted as "" and converted to ! - * - * @return The string list value of the requested property. - * - * @throw [NoSuchElementException] - * if the requested property does not exists. - */ - public synchronized java.util.Vector getStringList(java.lang.String sProp , - java.lang.String sDelimiter, - boolean bTrim , - boolean bDecode ) - throws java.util.NoSuchElementException - { - java.lang.String sValue = getProperty(sProp); - if (sValue == null) - throw new java.util.NoSuchElementException("The requested config value \""+sProp+"\" does not exists!"); - - java.util.Vector lValue = new java.util.Vector(); - try - { - java.util.StringTokenizer lTokens = new java.util.StringTokenizer(sValue, sDelimiter); - while(lTokens.hasMoreTokens()) - { - java.lang.String sToken = lTokens.nextToken(); - // remove trailing/leading whitespaces - if (bTrim) - sToken = sToken.trim(); - // remove "" - if ( - (bDecode ) && - (sToken.indexOf("\"") == 0 ) && - (sToken.lastIndexOf("\"") == sToken.length()-1) - ) - { - sToken = sToken.substring(1, sToken.length()-1); - } - lValue.add(sToken); - } - } - catch(java.lang.Throwable ex) - { lValue.clear(); } - - return lValue; - } -} diff --git a/transex3/source/filter/utils/FileHelper.java b/transex3/source/filter/utils/FileHelper.java deleted file mode 100644 index 71f51cf36bf6..000000000000 --- a/transex3/source/filter/utils/FileHelper.java +++ /dev/null @@ -1,766 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: FileHelper.java,v $ - * $Revision: 1.13 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.filter.config.tools.utils; - -// __________ Imports __________ - -import java.io.*; -import java.lang.*; -import java.net.*; -import java.util.*; - -// __________ Implementation __________ - -/** - * It collects some static helper functons to handle file system specific problems. - * Sometimes it's neccessary to convert URL from/to system pathes; - * or from string notation to structural versions (e.g. com.sun.star.util.URL). - * And sometimes java had another notation then the office it has. - * Further it provides functionality to work easiear with the java.io.File class of java. - * - * - */ -public class FileHelper -{ - // ____________________ - - /** - * Because the office need URLs for loading/saving documents - * we must convert used system pathes. - * And java use another notation for file URLs ... correct it. - * - * @param aSystemPath - * represent the file in system notation - * - * @return [String] - * a file url which represent the given system path - */ - public static java.lang.String getFileURLFromSystemPath(java.io.File aSystemPath) - { - System.out.println("TODO: must be adapted to java 1.3 :-("); - System.exit(-1); -/*TODO_JAVA - try - { - sFileURL = aSystemPath.toURI().toURL().toString(); - } - catch( MalformedURLException exWrong ) - { - sFileURL = null; - } -*/ - java.lang.String sFileURL = null; - - // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones! - // => correct this problem first, otherwise office can't use these URL's - if( - (sFileURL != null ) && - (sFileURL.startsWith("file:/") == true ) && - (sFileURL.startsWith("file://") == false) - ) - { - java.lang.StringBuffer sWorkBuffer = new java.lang.StringBuffer(sFileURL); - sWorkBuffer.insert(6,"//"); - sFileURL = sWorkBuffer.toString(); - } - - return sFileURL; - } - - // ____________________ - - /** - * The same as getFileURLFromSystemPath() before but uses string parameter instead - * of a java.io.File type. It exist to supress converting of neccessary parameters in the - * outside code. But of course getFileURLFromSystemPath(File) will be a little bit faster - * then this method ... - * - * @param sSystemPath - * represent the file in system notation - * - * @return [String] - * a file url which represent the given system path - */ - public static java.lang.String getFileURLFromSystemPath(java.lang.String sSystemPath) - { - return getFileURLFromSystemPath(new java.io.File(sSystemPath)); - } - - // ____________________ - - /** - * Does the same as getFileURLFromSystemPath() before ... but uses - * the given protocol string (e.g."http://") insted of "file:///". - * - * @param aSystemPath - * represent the file in system notation - * - * @param aBasePath - * define the base path of the aSystemPath value, - * which must be replaced with the value of "sServerPath". - * - * @param sServerURL - * Will be used to replace sBasePath. - * - * @example - * System Path = "d:\test\file.txt" - * Base Path = "d:\test" - * Server Path = "http://alaska:8000" - * => "http://alaska:8000/file.txt" - * - * @return [String] - * an url which represent the given system path - * and uses the given protocol - */ - public static java.lang.String getURLWithProtocolFromSystemPath(java.io.File aSystemPath, - java.io.File aBasePath , - java.lang.String sServerURL ) - { - System.out.println("TODO: must be adapted to java 1.3 :-("); - System.exit(-1); - - java.lang.String sFileURL = FileHelper.getFileURLFromSystemPath(aSystemPath); - java.lang.String sBaseURL = FileHelper.getFileURLFromSystemPath(aBasePath ); - - // cut last '/'! - if (sBaseURL.lastIndexOf('/')==(sBaseURL.length()-1)) - sBaseURL = sBaseURL.substring(0,sBaseURL.length()-1); - - // cut last '/'! - if (sServerURL.lastIndexOf('/')==(sServerURL.length()-1)) - sServerURL = sServerURL.substring(0,sServerURL.length()-1); - -//TODO_JAVA java.lang.String sURL = sFileURL.replaceFirst(sBaseURL,sServerURL); - java.lang.String sURL = null; - return sURL; - } - - // ____________________ - - /** - * The same as getURLWithProtocolFromSystemPath() before but uses string parameter instead - * of a java.io.File types. It exist to supress converting of neccessary parameters in the - * outside code. But of course getURLWithProtocolFromSystemPath(File,File,String) will be - * a little bit faster then this method ... - * - * @param sSystemPath - * represent the file in system notation - * - * @param sBasePath - * define the base path of the aSystemPath value, - * which must be replaced with the value of "sServerPath". - * - * @param sServerPath - * Will be used to replace sBasePath. - * - * @example - * System Path = "d:\test\file.txt" - * Base Path = "d:\test" - * Server Path = "http://alaska:8000" - * => "http://alaska:8000/file.txt" - * - * @return [String] - * an url which represent the given system path - * and uses the given protocol - */ - public static java.lang.String getURLWithProtocolFromSystemPath(java.lang.String sSystemPath, - java.lang.String sBasePath , - java.lang.String sServerPath) - { - return getURLWithProtocolFromSystemPath(new java.io.File(sSystemPath), new java.io.File(sBasePath), sServerPath); - } - - //_________________________________ - - /** - * Return a list of all available files of a directory. - * We filter sub directories. All other files - * are returned. So they can be used for further purposes. - * One parameter define the start directory, - * another one enable/disable recursive search into sub directories. - * - * @param aRoot - * the start directory, which should be analyzed. - * - * @param bRecursive - * enable/disable search in sub directories. - * - * @return [Vector] - * a filtered list of java java.io.File objects of all available files - * of the start dir (and may of its sub directories). - */ - public static java.util.Vector getSystemFilesFromDir(java.io.File aRoot , - boolean bRecursive) - { - java.io.File[] lAllFiles = aRoot.listFiles(); - if (lAllFiles == null) - return null; - - int c = lAllFiles.length; - java.util.Vector lFilteredFiles = new java.util.Vector(c); - for (int i=0; i=48 && c<=57 // 0-9 - && - c>=97 && c<=122 // a-z - && - c>=65 && c<=90 // A-Z - ) - { - sNewName.append(c); - } - else - { - sNewName.append("_"); - } - } - - return sNewName.toString(); - } - - //___________________________________________ - - /** it removes all child nodes of a file system directory. - * - * @param aDirectory - * points to the directory, which should be made empty. - * - * @param bFilesOnly - * force deletion of files only. If its set to TRUE, - * no subdirectory will be removed. - * - * @throw [java.io.IOException] - * if some of the child nodes couldn't be removed. - */ - public static void makeDirectoryEmpty(java.io.File aDirectory, - boolean bFilesOnly) - throws java.io.IOException - { - if (!aDirectory.isDirectory()) - throw new java.io.FileNotFoundException("\""+aDirectory.toString()+"\" is not a directory."); - - java.io.File[] lChilds = aDirectory.listFiles(); - for (int f=0; f0) - sBuffer.append(aEncodedBuffer, 0, nReadCount); - - aEncodedReader.close(); - } - - //___________________________________________ - private static void logEncodingData(java.lang.StringBuffer sLog , - int nUTF8 , - int nByteOrg1 , - int nByteOrg2 , - int nByteOrg3 , - int nByteOrg4 , - int nByte1 , - int nByte2 , - int nByte3 , - int nByte4 , - int nEncodingType) - { - sLog.append("["+nEncodingType+"]\t"); - sLog.append((int)nUTF8+"\t="); - sLog.append("\t"+nByteOrg1+"/"+nByte1); - sLog.append("\t"+nByteOrg2+"/"+nByte2); - sLog.append("\t"+nByteOrg3+"/"+nByte3); - sLog.append("\t"+nByteOrg4+"/"+nByte4); - sLog.append("\n"); - } - - //___________________________________________ - private static char impl_convertBytesToChar(int nByte1, int nByte2, int nByte3, int nByte4) - { - return (char)((nByte1*0x40000)+(nByte2*0x1000)+(nByte3*0x40)+nByte4); - } - - //___________________________________________ - private static int impl_readAndCheckNextByte(byte[] aBuffer , - int nBufPos , - int nBufLength , - int nMinRange , - int nMaxRange ) - throws java.lang.Exception - { - if (nBufPos>=nBufLength) - throw new java.lang.Exception("impl_readAndCheckNextByte()\nEnd of buffer reached."); - - int nByte = aBuffer[nBufPos] & 0xFF; - if ( - (nByte < nMinRange) || - (nByte > nMaxRange) - ) - { - throw new java.lang.Exception("impl_readAndCheckNextByte()\nByte does not fit the specified range."); - } - - return nByte; - } - - //___________________________________________ - public static void readAndCheckUTF8File(java.io.File aFile , - java.lang.StringBuffer sBuffer) - throws java.io.IOException - { - java.io.FileInputStream aByteStream = new java.io.FileInputStream(aFile.getAbsolutePath()); - byte[] aBuffer = new byte[4096]; - int nReadCount = 0; - int nByteOrg_1 = 0; - int nByteOrg_2 = 0; - int nByteOrg_3 = 0; - int nByteOrg_4 = 0; - int nByte_1 = 0; - int nByte_2 = 0; - int nByte_3 = 0; - int nByte_4 = 0; - char nUTF8 = 0; - int i = 0; - int nEncodingType = 0; - java.lang.StringBuffer sLog = new java.lang.StringBuffer(); - - try - { - - while((nReadCount=aByteStream.read(aBuffer))>0) - { - i=0; - while (i= 0x00) && - (nByteOrg_1 <= 0x7F) - ) - { - nEncodingType = 1; - nUTF8 = (char)nByte_1; - } - // ------------------------------------------------------------ - // 02 - // 1 byte: 110xxxxx - // 2 byte: 101xxxxx - // ------------------------------------------------------------ - else - if ( - (nByteOrg_1 >= 0xC2) && - (nByteOrg_1 <= 0xDF) - ) - { - nEncodingType = 2; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_1 = nByteOrg_1-0xC2; - nByte_2 = nByteOrg_2-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0,0,nByte_1, nByte_2); - } - // ------------------------------------------------------------ - // 03 - // 1 byte: 11100000 - // 2 byte: 101xxxxx - // 3 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if (nByteOrg_1 == 0xE0) - { - nEncodingType = 3; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0xA0, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_2 = nByteOrg_2-0xA0; - nByte_3 = nByteOrg_3-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0,0,nByte_2, nByte_3); - } - // ------------------------------------------------------------ - // 04 - // 1 byte: 111xxxxx - // 2 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if ( - (nByteOrg_1 >= 0xE1) && - (nByteOrg_1 <= 0xEC) - ) - { - nEncodingType = 4; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_1 = nByteOrg_1-0xE1; - nByte_2 = nByteOrg_2-0x80; - nByte_3 = nByteOrg_3-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0,nByte_1, nByte_2, nByte_3); - } - // ------------------------------------------------------------ - // 05 - // 1 byte: 11101101 - // 2 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if (nByteOrg_1 == 0xED) - { - nEncodingType = 5; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0x9F); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_2 = nByteOrg_2-0x80; - nByte_3 = nByteOrg_3-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0,0, nByte_2, nByte_3); - } - // ------------------------------------------------------------ - // 06 - // 1 byte: 1110111x - // 2 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if ( - (nByteOrg_1 >= 0xEE) && - (nByteOrg_1 <= 0xEF) - ) - { - nEncodingType = 6; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_1 = nByteOrg_1-0xEE; - nByte_2 = nByteOrg_2-0x80; - nByte_3 = nByteOrg_3-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0,nByte_1, nByte_2, nByte_3); - } - // ------------------------------------------------------------ - // 07 - // 1 byte: 11110000 - // 2 byte: 1001xxxx - // 3 byte: 10xxxxxx - // 4 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if (nByteOrg_1 == 0xF0) - { - nEncodingType = 7; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x90, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_2 = nByteOrg_2-0x90; - nByte_3 = nByteOrg_3-0x80; - nByte_4 = nByteOrg_4-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0, nByte_2, nByte_3, nByte_4); - } - // ------------------------------------------------------------ - // 08 - // 1 byte: 111100xx - // 2 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if ( - (nByteOrg_1 >= 0xF1) && - (nByteOrg_1 <= 0xF3) - ) - { - nEncodingType = 8; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_1 = nByteOrg_1-0xF1; - nByte_2 = nByteOrg_2-0x80; - nByte_3 = nByteOrg_3-0x80; - nByte_4 = nByteOrg_4-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(nByte_1, nByte_2, nByte_3, nByte_4); - } - // ------------------------------------------------------------ - // 09 - // 1 byte: 11110100 - // 2 byte: 10xxxxxx - // 3 byte: 10xxxxxx - // 4 byte: 10xxxxxx - // ------------------------------------------------------------ - else - if (nByteOrg_1 == 0xF0) - { - nEncodingType = 9; - nByteOrg_2 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_3 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByteOrg_4 = FileHelper.impl_readAndCheckNextByte(aBuffer, i++, nReadCount, 0x80, 0xBF); - nByte_2 = nByteOrg_2-0x80; - nByte_3 = nByteOrg_3-0x80; - nByte_4 = nByteOrg_4-0x80; - nUTF8 = FileHelper.impl_convertBytesToChar(0, nByte_2, nByte_3, nByte_4); - } - // wrong encoding ? - else - { - throw new java.lang.Exception("Non well formed UTF-8 encoding."); - } - - sBuffer.append(nUTF8); - // -> DEBUG ! - FileHelper.logEncodingData(sLog, nUTF8, nByteOrg_1, nByteOrg_2, nByteOrg_3, nByteOrg_4, nByte_1, nByte_2, nByte_3, nByte_4, nEncodingType); - // <- DEBUG ! - } - } - - } - catch(java.lang.Throwable ex) - { - // -> DEBUG ! - FileHelper.logEncodingData(sLog, nUTF8, nByteOrg_1, nByteOrg_2, nByteOrg_3, nByteOrg_4, nByte_1, nByte_2, nByte_3, nByte_4, nEncodingType); - - java.io.File aDir = new java.io.File(aFile.getParent()); - java.lang.String sDump = aFile.getName(); - java.io.File aDump = FileHelper.createUniqueFile(aDir, sDump, "dump"); - FileHelper.writeEncodedBufferToFile(aDump, "UTF-8", false, sLog); - // <- DEBUG ! - - java.lang.String sMsg = "File '"+aFile.getPath()+"' is not encoded right as UTF-8."; - throw new java.io.IOException(sMsg); - } - - aByteStream.close(); - } - - //___________________________________________ - - /** writes the given string buffer into the specified file - * using the specified encoding. - * - * Further it can be set, if the file should be expanded - * or replaced by this new string buffer. - * - * @param aFile - * must point to a system file. It can already exist! - * e.g.: "c:\temp\test.txt" - * "/tmp/test.txt" - * - * @param sEncoding - * will be used to encode the string content inside the file. - * e.g.: "UTF8" - * - * @param bAppend - * specify if an already existing file will be - * expanded or replaced. - * - * @param sBuffer - * the new string content for this file. - */ - public static void writeEncodedBufferToFile(java.io.File aFile , - java.lang.String sEncoding, - boolean bAppend , - java.lang.StringBuffer sBuffer ) - throws java.io.IOException - { - java.io.FileOutputStream aByteStream = new java.io.FileOutputStream(aFile.getAbsolutePath(), bAppend); - java.io.OutputStreamWriter aEncodedWriter = new java.io.OutputStreamWriter(aByteStream, sEncoding); - - java.lang.String sTemp = sBuffer.toString(); - aEncodedWriter.write(sTemp, 0, sTemp.length()); - - aEncodedWriter.flush(); - aEncodedWriter.close(); - - if (!aFile.exists()) - throw new java.io.IOException("File \""+aFile.getAbsolutePath()+"\" not written correctly."); - } -} diff --git a/transex3/source/filter/utils/Logger.java b/transex3/source/filter/utils/Logger.java deleted file mode 100644 index 7657eba5f426..000000000000 --- a/transex3/source/filter/utils/Logger.java +++ /dev/null @@ -1,177 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: Logger.java,v $ - * $Revision: 1.8 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.filter.config.tools.utils; - -//_______________________________________________ -// imports - -import java.lang.*; -import java.util.*; - -//_______________________________________________ -// definition - -/** can be used to print out some debug messages - * and group it into warnings/errors or info statements. - * - * - */ -public class Logger -{ - //___________________________________________ - // const - - /** only error message will be shown. */ - public static final int LEVEL_ERRORS = 1; - - /** only errors and warnings will be shown. */ - public static final int LEVEL_WARNINGS = 2; - - /** enable errors/warnings and some global info - * message. */ - public static final int LEVEL_GLOBALINFOS = 3; - - /** enable anything! */ - public static final int LEVEL_DETAILEDINFOS = 4; - - //___________________________________________ - // member - - /** enable/disable different output level. - * e.g. warnings/errors/infos */ - private int m_nLevel; - - //___________________________________________ - // ctor - - /** initialize new debug object with the specified - * debug level. - * - * @param nLevel - * the new debug level. - * See const values LEVEL_xxx too. - */ - public Logger(int nLevel) - { - m_nLevel = nLevel; - } - - //___________________________________________ - // interface - - /** initialize new debug object with a default - * debug level. - */ - public Logger() - { - m_nLevel = LEVEL_DETAILEDINFOS; - } - - //___________________________________________ - // interface - - /** prints out an exception ... if the right level is set. - * - * @param ex - * the exception object - */ - public synchronized void setException(java.lang.Throwable ex) - { - if (m_nLevel >= LEVEL_ERRORS) - { - System.err.println("Exception:\n"); - ex.printStackTrace(); - } - } - - //___________________________________________ - // interface - - /** prints out an error ... if the right level is set. - * - * @param sError - * the error message. - */ - public synchronized void setError(java.lang.String sError) - { - if (m_nLevel >= LEVEL_ERRORS) - System.err.println("Error :\t\""+sError+"\""); - } - - //___________________________________________ - // interface - - /** prints out a warning ... if the right level is set. - * - * @param sWarning - * the warning message. - */ - public synchronized void setWarning(java.lang.String sWarning) - { - if (m_nLevel >= LEVEL_WARNINGS) - System.err.println("Warning :\t\""+sWarning+"\""); - } - - //___________________________________________ - // interface - - /** prints out a global info message ... if the right level is set. - * - * Global infos should be used to describe a complex operation. - * E.g.: loading of a document. - * But not for every sub operation like e.g. analyzing lines - * during loading the document! - * - * @param sInfo - * the info message. - */ - public synchronized void setGlobalInfo(java.lang.String sInfo) - { - if (m_nLevel >= LEVEL_GLOBALINFOS) - System.out.println("Info :\t\""+sInfo+"\""); - } - - //___________________________________________ - // interface - - /** prints out a mode detailed info message ... if the right level is set. - * - * Such detailed message are e.g. "analyze line [n] of file ...". - * - * @param sInfo - * the info message. - */ - public synchronized void setDetailedInfo(java.lang.String sInfo) - { - if (m_nLevel >= LEVEL_DETAILEDINFOS) - System.out.println("Detail :\t\""+sInfo+"\""); - } -} diff --git a/transex3/source/filter/utils/MalformedCommandLineException.java b/transex3/source/filter/utils/MalformedCommandLineException.java deleted file mode 100644 index e073dcb9adcc..000000000000 --- a/transex3/source/filter/utils/MalformedCommandLineException.java +++ /dev/null @@ -1,50 +0,0 @@ -/*_*********************************************************************** - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: MalformedCommandLineException.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - **********************************************************************_*/ - -package com.sun.star.filter.config.tools.utils; - -//_______________________________________________ -// imports - -import java.lang.*; - -//___________________________________________ -// types - -/** indicates a malformed command line. - * - * E.g. it must be thrown if the command line contains one item more then once, - * or use unsupported format. - */ -public class MalformedCommandLineException extends java.lang.Exception -{ - public MalformedCommandLineException() {} - public MalformedCommandLineException(java.lang.String sMsg) { super(sMsg); } -} diff --git a/transex3/source/filter/utils/XMLHelper.java b/transex3/source/filter/utils/XMLHelper.java deleted file mode 100644 index 0f912cac8e25..000000000000 --- a/transex3/source/filter/utils/XMLHelper.java +++ /dev/null @@ -1,825 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: XMLHelper.java,v $ - * $Revision: 1.7 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.filter.config.tools.utils; - -//_______________________________________________ - -import java.lang.*; -import java.util.*; -import java.io.*; - -//_______________________________________________ - -/** - * It provides some constant values and some static helper routines - * which are neccessary to work with a xml file - especialy - * the filter configuration. - * - * - */ -public class XMLHelper -{ - //___________________________________________ - // public const - - /** its a possible value of the xml attribute "oor:type" and identify an integer type. */ - public static final java.lang.String XMLTYPE_INTEGER = "xs:int"; - - /** its a possible value of the xml attribute "oor:type" and identify an boolean type. */ - public static final java.lang.String XMLTYPE_BOOLEAN = "xs:boolean"; - - /** its a possible value of the xml attribute "oor:type" and identify an string type. */ - public static final java.lang.String XMLTYPE_STRING = "xs:string"; - - /** its a possible value of the xml attribute "oor:type" and identify an string list type. */ - public static final java.lang.String XMLTYPE_STRINGLIST = "oor:string-list"; - - /** its a xml attribute, which specify a property name. */ - public static final java.lang.String XMLATTRIB_OOR_NAME = "oor:name"; - - /** its a xml attribute, which specify a property type. */ - public static final java.lang.String XMLATTRIB_OOR_TYPE = "oor:type"; - - /** its a xml attribute, which specify a list separator. */ - public static final java.lang.String XMLATTRIB_OOR_SEPARATOR = "oor:separator"; - - /** its a xml attribute, which specify a localized value. */ - public static final java.lang.String XMLATTRIB_OOR_LOCALIZED = "oor:localized"; - - /** its a xml attribute, which specify a merge operation for cfg layering. */ - public static final java.lang.String XMLATTRIB_OOR_OP = "oor:op"; - - /** can be used as value for XMLATTRIB_OOR_OP. */ - public static final java.lang.String XMLATTRIB_OP_REPLACE = "replace"; - - /** its a xml attribute, which specify a locale value. */ - public static final java.lang.String XMLATTRIB_XML_LANG = "xml:lang"; - - /** its the tag name of a entry. */ - public static final java.lang.String XMLTAG_VALUE = "value"; - - /** its the tag name of a entry. */ - public static final java.lang.String XMLTAG_PROP = "prop"; - - /** its the tag name of a entry. */ - public static final java.lang.String XMLTAG_NODE = "node"; - - //___________________________________________ - // private const - - /** a static list of all possible separators, which can be used for configuration type string-list. */ - private static final java.lang.String[] DELIMS = {" ", ",", ";", ".", ":", "-", "_", "#", "'", "+", "*", "~", "=", "?"}; - - /** index of the default separator inside list DELIMS. - * Its neccessary to know such default separator; because it can - * be supressed as xml attribute of the corresponding value tag. */ - private static final int DEFAULT_SEPARATOR = 0; - - //___________________________________________ - - /** analyze the structures of the given XML node and - * return a property set of all found sub nodes. - * - * Such properties are organized as [name, value] pairs. - * The type of a xml node will be detected automaticly. - * Following types are supported: - * xs:int => java.lang.Integer - * xs:bool => java.lang.Boolean - * xs:string => java.lang.String - * oor:string-list => java.util.LinkedList[java.lang.String] - * oor:set => java.util.Vector[java.lang.Object] - * oor:localized => java.util.HashMap[java.lang.Object] - * - * @param aNode - * points directly to the xml node, where we should analyze - * the children nodes. - * - * @return [java.util.HashMap] - * contains every node name as key and its string(!) as value. - */ - public static java.util.HashMap convertNodeToPropSet(org.w3c.dom.Node aNode) - throws java.lang.Exception - { - java.util.HashMap aPropSet = new java.util.HashMap(); - - // get all child nodes, which seems to be properties - java.util.Vector lChildNodes = XMLHelper.extractChildNodesByTagName(aNode, XMLTAG_PROP); - java.util.Enumeration en1 = lChildNodes.elements(); - while(en1.hasMoreElements()) - { - org.w3c.dom.Node aChildNode = (org.w3c.dom.Node)en1.nextElement(); - - // read its name - java.lang.String sChildName = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_NAME); - if (sChildName == null) - throw new java.io.IOException("unsupported format: could not extract child node name"); - - // read its type info - java.lang.String sChildType = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_TYPE); - if (sChildType == null) - { - /** Special patch: - * If an xml tag has no type information set ... we can restore it - * by analyzing the already readed tag name :-) - * Not very nice - but it can help to read stripped xml files too. */ - sChildType = XMLHelper.getTypeForTag(sChildName); - if (sChildType == null) - throw new java.io.IOException("unsupported format: could not extract child node type"); - } - - // read its value(s?) - java.util.Vector lChildValues = XMLHelper.extractChildNodesByTagName(aChildNode, XMLTAG_VALUE); - java.util.Enumeration en2 = lChildValues.elements(); - int nValue = 0; - java.lang.Object aValue = null; - while(en2.hasMoreElements()) - { - org.w3c.dom.Node aValueNode = (org.w3c.dom.Node)en2.nextElement(); - java.lang.String sChildLocale = XMLHelper.extractNodeAttribByName(aValueNode, XMLATTRIB_XML_LANG); - boolean bLocalized = (sChildLocale != null); - - ++nValue; - - if (sChildType.equals(XMLTYPE_INTEGER)) - { - if (!bLocalized && nValue > 1) - throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); - java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); - aValue = new java.lang.Integer(sData); - } - else - if (sChildType.equals(XMLTYPE_BOOLEAN)) - { - if (!bLocalized && nValue > 1) - throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); - java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); - aValue = new java.lang.Boolean(sData); - } - else - if (sChildType.equals(XMLTYPE_STRING)) - { - if (!bLocalized && nValue > 1) - throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); - - java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); - - java.util.HashMap lLocalized = null; - if (bLocalized) - { - if (aValue == null) - aValue = new java.util.HashMap(); - lLocalized = (java.util.HashMap)aValue; - lLocalized.put(sChildLocale, sData); - } - else - aValue = sData; - } - else - if (sChildType.equals(XMLTYPE_STRINGLIST)) - { - if (!bLocalized && nValue > 1) - throw new java.io.IOException("unsupported format: more then one value for non localized but atomic type detected"); - - java.lang.String sSeparator = XMLHelper.extractNodeAttribByName(aChildNode, XMLATTRIB_OOR_SEPARATOR); - if (sSeparator == null) - sSeparator = " "; - - java.lang.String sData = ((org.w3c.dom.CharacterData)aValueNode.getFirstChild()).getData(); - sData = sData.replace('\t', ' '); - sData = sData.replace('\n', ' '); - java.util.StringTokenizer aTokenizer = new java.util.StringTokenizer(sData, sSeparator); - java.util.Vector lList = new java.util.Vector(); - while(aTokenizer.hasMoreTokens()) - { - java.lang.String sToken = (java.lang.String)aTokenizer.nextToken(); - sToken.trim(); - if (sToken.length() < 1) - continue; - lList.add(sToken); - } - aValue = lList; - } - - aPropSet.put(sChildName, aValue); - } - } - - return aPropSet; - } - - //___________________________________________ - - private static java.lang.String getTypeForTag(java.lang.String sTag) - { - java.lang.String sType = null; - - if ( - (sTag.equals(Cache.PROPNAME_DATA )) || - (sTag.equals(Cache.PROPNAME_NAME )) || - (sTag.equals(Cache.PROPNAME_UINAME )) || - (sTag.equals(Cache.PROPNAME_MEDIATYPE )) || - (sTag.equals(Cache.PROPNAME_CLIPBOARDFORMAT )) || - (sTag.equals(Cache.PROPNAME_PREFERREDFILTER )) || - (sTag.equals(Cache.PROPNAME_DETECTSERVICE )) || - (sTag.equals(Cache.PROPNAME_FRAMELOADER )) || - (sTag.equals(Cache.PROPNAME_CONTENTHANDLER )) || - (sTag.equals(Cache.PROPNAME_DOCUMENTSERVICE )) || - (sTag.equals(Cache.PROPNAME_FILTERSERVICE )) || - (sTag.equals(Cache.PROPNAME_TEMPLATENAME )) || - (sTag.equals(Cache.PROPNAME_TYPE )) || - (sTag.equals(Cache.PROPNAME_UICOMPONENT )) - ) - sType = XMLTYPE_STRING; - else - if ( - (sTag.equals(Cache.PROPNAME_PREFERRED )) || - (sTag.equals("Installed" )) - ) - sType = XMLTYPE_BOOLEAN; - else - if ( - (sTag.equals(Cache.PROPNAME_UIORDER )) || - (sTag.equals(Cache.PROPNAME_DOCUMENTICONID )) || - (sTag.equals(Cache.PROPNAME_FILEFORMATVERSION)) - ) - sType = XMLTYPE_INTEGER; - else - if ( - (sTag.equals(Cache.PROPNAME_URLPATTERN )) || - (sTag.equals(Cache.PROPNAME_EXTENSIONS )) || - (sTag.equals(Cache.PROPNAME_USERDATA )) || - (sTag.equals(Cache.PROPNAME_FLAGS )) || - (sTag.equals(Cache.PROPNAME_TYPES )) - ) - sType = XMLTYPE_STRINGLIST; - - if (sType == null) - System.err.println("getTypeForTag("+sTag+") = "+sType); - - return sType; - } - - //___________________________________________ - - /** return a xml representation of the given property set. - * - * @param aPropSet - * a set of pairs, which should be translated to xml - * - * @return [java.lang.String] - * the xml string representation. - * - * @throws [java.lang.Exception] - * if anything during convertion fill fail. - */ - public static java.lang.String convertPropSetToXML(java.util.HashMap aPropSet , - int nPrettyTabs) - throws java.lang.Exception - { - java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); - - java.util.Iterator it1 = aPropSet.keySet().iterator(); - while(it1.hasNext()) - { - java.lang.String sProp = (java.lang.String)it1.next(); - java.lang.Object aVal = aPropSet.get(sProp); - - sProp = encodeHTMLSigns(sProp); - - // is it a simple type? - if ( - (aVal instanceof java.lang.Integer) || - (aVal instanceof java.lang.Boolean) || - (aVal instanceof java.lang.String ) - ) - { - sXML.append(XMLHelper.convertSimpleObjectToXML(sProp, aVal, nPrettyTabs)); - continue; - } - - // no! - // is it a list value? - if (aVal instanceof java.util.Vector) - { - java.util.Vector lVal = (java.util.Vector)aVal; - sXML.append(XMLHelper.convertListToXML(sProp, lVal, nPrettyTabs)); - continue; - } - - // its a localized value? - if (aVal instanceof java.util.HashMap) - { - java.util.HashMap lVal = (java.util.HashMap)aVal; - sXML.append(XMLHelper.convertLocalizedValueToXML(sProp, lVal, nPrettyTabs)); - continue; - } - - // unknown type! - java.lang.StringBuffer sMsg = new java.lang.StringBuffer(256); - sMsg.append("unsupported object type detected."); - sMsg.append("\ttype ? : \""+sProp+"\" = "+aVal); - sMsg.append("\tprop set: \""+aPropSet ); - throw new java.lang.Exception(sMsg.toString()); - } - - return sXML.toString(); - } - - public static java.lang.String encodeHTMLSigns(java.lang.String sValue) - { - java.lang.StringBuffer sSource = new java.lang.StringBuffer(sValue); - java.lang.StringBuffer sDestination = new java.lang.StringBuffer(1000 ); - - for (int i=0; i \""+sReturn+"\""); - - return sReturn; - } - - //___________________________________________ - - /** return a xml representation of an atomic property. - * - * Atomic property types are e.g. Integer, Boolean, String. - * - * @param sName - * the name of the property. - - * @param aValue - * the value of the property. - * - * @param nPrettyTabs - * count of tab signs for pretty format the xml code :-) - * - * @return [java.lang.String] - * the xml string representation. - * - * @throws [java.lang.Exception] - * if anything during convertion fill fail. - */ - private static java.lang.String convertSimpleObjectToXML(java.lang.String sName , - java.lang.Object aValue , - int nPrettyTabs) - throws java.lang.Exception - { - java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); - for (int t=0; t"); - sXML.append(""+aValue.toString()+""); - sXML.append("\n"); - } - else - if (aValue instanceof java.lang.Boolean) - { - sXML.append(""); - sXML.append(""+aValue.toString()+""); - sXML.append("\n"); - } - else - if (aValue instanceof java.lang.String) - { - sXML.append("\n"); - else - { - sXML.append(">"+sValue+""); - sXML.append("\n"); - } - } - else - { - System.err.println("name = "+sName); - System.err.println("value = "+aValue); - // ! can be used outside to detect - that it was not a simple type :-) - throw new java.lang.Exception("not an atomic type."); - } - - return sXML.toString(); - } - - //___________________________________________ - - /** return a xml representation of a string-list property. - * - * @param sName - * the name of the property. - - * @param aValue - * the value of the property. - * - * @param nPrettyTabs - * count of tab signs for pretty format the xml code :-) - * - * @return [java.lang.String] - * the xml string representation. - * - * @throws [java.lang.Exception] - * if anything during convertion fill fail. - */ - private static java.lang.String convertListToXML(java.lang.String sName , - java.util.Vector aValue , - int nPrettyTabs) - throws java.lang.Exception - { - java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); - - for (int t=0; t\n"); - return sXML.toString(); - } - - // step over all list items and add it to a string buffer - // Every item will be separated by a default separator "\n" first. - // Because "\n" is not a valid separator at all and can`t occure inside - // our list items. During we step over all items, we check if our current separator - // (we use a list of possible ones!) clash with an item. - // If it clash - we step to the next possible separator. - // If our list of possible separator values runs out of range we throw - // an exception :-) Its better then generating of wrong values - // If we found a valid seperator - we use it to replace our "\n" place holder - // at the end of the following loop ... - - int d = 0; - java.lang.StringBuffer sValBuff = new java.lang.StringBuffer(256); - for (int i=0; i= DELIMS.length) - throw new java.lang.Exception("No valid separator found for a string list item."); - if (sValue.length() < 1 && DELIMS[d].equals(" ")) - { - ++d; - continue; - } - if (sValue.indexOf(DELIMS[d]) != -1) - { - ++d; - continue; - } - break; - } - } - - // replace default separator with right one - System.out.println("TODO: must be adapted to java 1.3 :-("); - System.exit(-1); -//TODO_JAVA java.lang.String sListVal = sValBuff.toString().replaceAll("\n", DELIMS[d]); - java.lang.String sListVal = null; - - sXML.append(""); - if (d == DEFAULT_SEPARATOR) - sXML.append(""); - else - sXML.append(""); - sXML.append(sListVal); - sXML.append(""); - sXML.append("\n"); - - return sXML.toString(); - } - - //___________________________________________ - - /** return a xml representation of a localized property. - * - * @param sName - * the name of the property. - - * @param aValue - * the value of the property. - * - * @param nPrettyTabs - * count of tab signs for pretty format the xml code :-) - * - * @return [java.lang.String] - * the xml string representation. - * - * @throws [java.lang.Exception] - * if anything during convertion fill fail. - */ - private static java.lang.String convertLocalizedValueToXML(java.lang.String sName , - java.util.HashMap aValue , - int nPrettyTabs) - throws java.lang.Exception - { - java.lang.StringBuffer sXML = new java.lang.StringBuffer(256); - - int c = aValue.size(); - if (c < 1) - throw new java.lang.Exception("Cant detect type of localized values. Because the given list is empty."); - - for (int t=0; t\n"); - java.util.Iterator it = aValue.keySet().iterator(); -// boolean bTypeKnown = false; - while(it.hasNext()) - { - java.lang.String sLocale = (java.lang.String)it.next(); - java.lang.Object aLocalizedValue = aValue.get(sLocale); -/* - if (!bTypeKnown) - { - bTypeKnown = true; - if (aLocalizedValue instanceof java.lang.Integer) - sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_INTEGER+"\">\n"); - else - if (aLocalizedValue instanceof java.lang.Boolean) - sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_BOOLEAN+"\">\n"); - else - if (aLocalizedValue instanceof java.lang.String) - sXML.append(" "+XMLATTRIB_OOR_TYPE+"=\""+XMLTYPE_STRING+"\">\n"); - else - throw new java.lang.Exception("Unsupported type for localized value detected."); - } -*/ - java.lang.String sLocValue = aLocalizedValue.toString(); - java.lang.String sValue = encodeHTMLSigns(sLocValue); - - for (int t=0; t"+sValue+"\n"); - } - --nPrettyTabs; - for (int t=0; t\n"); - - return sXML.toString(); - } - - //___________________________________________ - - /** returns the value of an attribute of the given node. - * - * If the given node represent an lement node, may it supports some attributes. - * Then this method search for an attribute with the specified name and return it's value. - * If nothing could be found ... or the given node isn't a suitable node ... it returns null. - * - * @param aNode - * the node, which should be analyzed. - * - * @param sAttrib - * name of the attribute, which should be searched. - * - * @return The value of the specified attribute if it could be found at the given node. - * Can be null if node doesn't support attributes or the searched one does not exist there. - */ - public static java.lang.String extractNodeAttribByName(org.w3c.dom.Node aNode , - java.lang.String sAttrib) - throws java.lang.Exception - { - // We can get valid attributes for element nodes only! - if (aNode.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) - { -// System.err.println("not an element node"); - return null; - } - - // may it supports attributes in general ... but doesn't have anyone realy. - org.w3c.dom.NamedNodeMap lAttribs = aNode.getAttributes(); - if (lAttribs==null) - { -// System.err.println("no attributes at all"); - return null; - } - - // step over the attribute list and search for the requested one - for (int i=0; i\n"); - sHeader.append("\n"); - } - else - { - sHeader.append("\n\n"); - sHeader.append("\n"); - } - - return sHeader.toString(); - } - - public static java.lang.String generateFooter() - { - return "\n"; - } -} diff --git a/transex3/source/filter/utils/makefile.mk b/transex3/source/filter/utils/makefile.mk deleted file mode 100644 index d41d8ba9a825..000000000000 --- a/transex3/source/filter/utils/makefile.mk +++ /dev/null @@ -1,57 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.9.98.2 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ = ..$/..$/.. -TARGET = FCFGUtils -PRJNAME = filter -PACKAGE = com$/sun$/star$/filter$/config$/tools$/utils - -# --- Settings ----------------------------------------------------- - -.INCLUDE: settings.mk - -#----- compile .java files ----------------------------------------- - - -JAVACLASSFILES = \ - $(CLASSDIR)$/$(PACKAGE)$/AnalyzeStartupLog.class \ - $(CLASSDIR)$/$(PACKAGE)$/ConfigHelper.class \ - $(CLASSDIR)$/$(PACKAGE)$/Logger.class \ - $(CLASSDIR)$/$(PACKAGE)$/FileHelper.class \ - $(CLASSDIR)$/$(PACKAGE)$/MalformedCommandLineException.class \ - $(CLASSDIR)$/$(PACKAGE)$/Cache.class \ - $(CLASSDIR)$/$(PACKAGE)$/XMLHelper.class - -MAXLINELENGTH = 100000 - -# --- targets ----------------------------------------------------- - -.INCLUDE : target.mk diff --git a/transex3/source/gsicheck.cxx b/transex3/source/gsicheck.cxx deleted file mode 100644 index 99183602f951..000000000000 --- a/transex3/source/gsicheck.cxx +++ /dev/null @@ -1,1177 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: gsicheck.cxx,v $ - * $Revision: 1.29 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -#include -#include - -// local includes -#include "tagtest.hxx" -#include "gsicheck.hxx" - -#define MAX_GID_LID_LEN 250 - -/*****************************************************************************/ -void PrintMessage( ByteString aType, ByteString aMsg, ByteString aPrefix, - ByteString aContext, BOOL bPrintContext, ULONG nLine, ByteString aUniqueId = ByteString() ) -/*****************************************************************************/ -{ - fprintf( stdout, "%s %s, Line %lu", aType.GetBuffer(), aPrefix.GetBuffer(), nLine ); - if ( aUniqueId.Len() ) - fprintf( stdout, ", UniqueID %s", aUniqueId.GetBuffer() ); - fprintf( stdout, ": %s", aMsg.GetBuffer() ); - - if ( bPrintContext ) - fprintf( stdout, " \"%s\"", aContext.GetBuffer() ); - fprintf( stdout, "\n" ); -} - -/*****************************************************************************/ -void PrintError( ByteString aMsg, ByteString aPrefix, - ByteString aContext, BOOL bPrintContext, ULONG nLine, ByteString aUniqueId = ByteString() ) -/*****************************************************************************/ -{ - PrintMessage( "Error:", aMsg, aPrefix, aContext, bPrintContext, nLine, aUniqueId ); -} - -BOOL LanguageOK( ByteString aLang ) -{ - if ( !aLang.Len() ) - return FALSE; - - if ( aLang.IsNumericAscii() ) - return TRUE; - - if ( aLang.GetTokenCount( '-' ) == 1 ) - return aLang.IsAlphaAscii() && aLang.IsLowerAscii(); - else if ( aLang.GetTokenCount( '-' ) == 2 ) - { - ByteString aTok0( aLang.GetToken( 0, '-' ) ); - ByteString aTok1( aLang.GetToken( 1, '-' ) ); - return aTok0.Len() && aTok0.IsAlphaAscii() && aTok0.IsLowerAscii() - && aTok1.Len() && aTok1.IsAlphaAscii() && aTok1.IsUpperAscii() - && !aTok1.EqualsIgnoreCaseAscii( aTok0 ); - } - - return FALSE; -} - - -// -// class LazySvFileStream -// - - -class LazySvFileStream : public SvFileStream -{ - -private: - String aFileName; - BOOL bOpened; - StreamMode eOpenMode; - -public: - LazySvFileStream() - : aFileName() - , bOpened( FALSE ) - , eOpenMode( 0 ) - {}; - - void SetOpenParams( const String& rFileName, StreamMode eOpenModeP ) - { - aFileName = rFileName; - eOpenMode = eOpenModeP; - }; - - void LazyOpen(); -}; - -void LazySvFileStream::LazyOpen() -{ - if ( !bOpened ) - { - Open( aFileName, eOpenMode ); - if ( !IsOpen()) - { - fprintf( stderr, "\nERROR: Could not open Output-File %s!\n\n", ByteString( aFileName, RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); - exit ( 4 ); - } - bOpened = TRUE; - } -} - - -// -// class GSILine -// - -/*****************************************************************************/ -GSILine::GSILine( const ByteString &rLine, ULONG nLine ) -/*****************************************************************************/ - : ByteString( rLine ) - , nLineNumber( nLine ) - , bOK( TRUE ) - , bFixed ( FALSE ) -{ - if ( rLine.GetTokenCount( '\t' ) == 15 ) - { - aFormat = FORMAT_SDF; - aUniqId = rLine.GetToken( 0, '\t' ); - aUniqId.Append("/").Append( rLine.GetToken( 1, '\t' ) ).Append("/").Append( rLine.GetToken( 3, '\t' ) ).Append("/").Append( rLine.GetToken( 4, '\t' ) ).Append("/").Append( rLine.GetToken( 5, '\t' ) ).Append("/").Append( rLine.GetToken( 6, '\t' ) ).Append("/").Append( rLine.GetToken( 7, '\t' ) ); - aLineType = ""; - aLangId = rLine.GetToken( 9, '\t' ); - aText = rLine.GetToken( 10, '\t' ); - aQuickHelpText = rLine.GetToken( 12, '\t' ); - aTitle = rLine.GetToken( 13, '\t' ); - - // do some more format checks here - if ( !rLine.GetToken( 8, '\t' ).IsNumericAscii() ) - { - PrintError( "The length field does not contain a number!", "Line format", rLine.GetToken( 8, '\t' ), TRUE, GetLineNumber(), GetUniqId() ); - NotOK(); - } - if ( !LanguageOK( aLangId ) ) - { - PrintError( "The Language is invalid!", "Line format", aLangId, TRUE, GetLineNumber(), GetUniqId() ); - NotOK(); - } - // limit GID and LID to MAX_GID_LID_LEN chars each for database conformity, see #137575# - if ( rLine.GetToken( 4, '\t' ).Len() > MAX_GID_LID_LEN || rLine.GetToken( 5, '\t' ).Len() > MAX_GID_LID_LEN ) - { - PrintError( ByteString("GID and LID may only be ").Append( ByteString::CreateFromInt32(MAX_GID_LID_LEN) ).Append( " chars long each!" ), "Line format", aLangId, TRUE, GetLineNumber(), GetUniqId() ); - NotOK(); - } - } - else // allow tabs in gsi files - { - aFormat = FORMAT_GSI; - ByteString sTmp( rLine ); - USHORT nPos = sTmp.Search( "($$)" ); - USHORT nStart = 0; - if ( nPos != STRING_NOTFOUND ) - { - aUniqId = sTmp.Copy( nStart, nPos - nStart ); - nStart = nPos + 4; // + length of the delemiter - nPos = sTmp.Search( "($$)", nStart ); - } - if ( nPos != STRING_NOTFOUND ) - { - aLineType = sTmp.Copy( nStart, nPos - nStart ); - nStart = nPos + 4; // + length of the delemiter - nPos = sTmp.Search( "($$)", nStart ); - aUniqId.Append( "/" ); - aUniqId.Append( aLineType ); - } - if ( nPos != STRING_NOTFOUND ) - { - aLangId = sTmp.Copy( nStart, nPos - nStart ); - nStart = nPos + 4; // + length of the delemiter - nPos = sTmp.Search( "($$)", nStart ); - } - if ( nPos != STRING_NOTFOUND ) - { -// ByteString aStatus = sTmp.Copy( nStart, nPos - nStart ); // ext int ... - nStart = nPos + 4; // + length of the delemiter - } - if ( nPos != STRING_NOTFOUND ) - aText = sTmp.Copy( nStart ); - else - aFormat = FORMAT_UNKNOWN; - } - - if ( FORMAT_UNKNOWN == GetLineFormat() ) - NotOK(); -} - -/*****************************************************************************/ -void GSILine::NotOK() -/*****************************************************************************/ -{ - bOK = FALSE; -} - -/*****************************************************************************/ -void GSILine::ReassembleLine() -/*****************************************************************************/ -{ - ByteString aReassemble; - if ( GetLineFormat() == FORMAT_SDF ) - { - USHORT i; - for ( i = 0 ; i < 10 ; i++ ) - { - aReassemble.Append( GetToken( i, '\t' ) ); - aReassemble.Append( "\t" ); - } - aReassemble.Append( aText ); - aReassemble.Append( "\t" ); - aReassemble.Append( GetToken( 11, '\t' ) ); // should be empty but there are some places in sc. Not reflected to sources!! - aReassemble.Append( "\t" ); - aReassemble.Append( aQuickHelpText ); - aReassemble.Append( "\t" ); - aReassemble.Append( aTitle ); - for ( i = 14 ; i < 15 ; i++ ) - { - aReassemble.Append( "\t" ); - aReassemble.Append( GetToken( i, '\t' ) ); - } - *(ByteString*)this = aReassemble; - } - else if ( GetLineFormat() == FORMAT_GSI ) - { - USHORT nPos = Search( "($$)" ); - USHORT nStart = 0; - if ( nPos != STRING_NOTFOUND ) - { - nStart = nPos + 4; // + length of the delemiter - nPos = Search( "($$)", nStart ); - } - if ( nPos != STRING_NOTFOUND ) - { - nStart = nPos + 4; // + length of the delemiter - nPos = Search( "($$)", nStart ); - } - if ( nPos != STRING_NOTFOUND ) - { - nStart = nPos + 4; // + length of the delemiter - nPos = Search( "($$)", nStart ); - } - if ( nPos != STRING_NOTFOUND ) - { - nStart = nPos + 4; // + length of the delemiter - } - if ( nPos != STRING_NOTFOUND ) - { - aReassemble = Copy( 0, nStart ); - aReassemble += aText; - *(ByteString*)this = aReassemble; - } - else - PrintError( "Cannot reassemble GSI line (internal Error).", "Line format", "", FALSE, GetLineNumber(), GetUniqId() ); - } - else - PrintError( "Cannot reassemble line of unknown type (internal Error).", "Line format", "", FALSE, GetLineNumber(), GetUniqId() ); -} - -// -// class GSIBlock -// -/*****************************************************************************/ -GSIBlock::GSIBlock( BOOL PbPrintContext, BOOL bSource, BOOL bTrans, BOOL bRef, BOOL bAllowKID, BOOL bAllowSusp ) -/*****************************************************************************/ - : pSourceLine( NULL ) - , pReferenceLine( NULL ) - , bPrintContext( PbPrintContext ) - , bCheckSourceLang( bSource ) - , bCheckTranslationLang( bTrans ) - , bReference( bRef ) - , bAllowKeyIDs( bAllowKID ) - , bAllowSuspicious( bAllowSusp ) - , bHasBlockError( FALSE ) -{ -} - -/*****************************************************************************/ -GSIBlock::~GSIBlock() -/*****************************************************************************/ -{ - delete pSourceLine; - delete pReferenceLine; - - for ( ULONG i = 0; i < Count(); i++ ) - delete ( GetObject( i )); -} - -/*****************************************************************************/ -void GSIBlock::InsertLine( GSILine* pLine, ByteString aSourceLang) -/*****************************************************************************/ -{ - if ( pLine->GetLanguageId().Equals( aSourceLang ) ) - { - if ( pSourceLine ) - { - PrintError( "Source Language entry double. Treating as Translation.", "File format", "", pLine->GetLineNumber(), pLine->GetUniqId() ); - bHasBlockError = TRUE; - pSourceLine->NotOK(); - pLine->NotOK(); - } - else - { - pSourceLine = pLine; - return; - } - } - ULONG nPos = 0; - - if ( aSourceLang.Len() ) // only check blockstructure if source lang is given - { - while ( nPos < Count() ) - { - if ( GetObject( nPos )->GetLanguageId().Equals( pLine->GetLanguageId() ) ) - { - PrintError( "Translation Language entry double. Checking both.", "File format", "", pLine->GetLineNumber(), pLine->GetUniqId() ); - bHasBlockError = TRUE; - GetObject( nPos )->NotOK(); - pLine->NotOK(); - } - nPos++; - } - } - Insert( pLine, LIST_APPEND ); -} - -/*****************************************************************************/ -void GSIBlock::SetReferenceLine( GSILine* pLine ) -/*****************************************************************************/ -{ - pReferenceLine = pLine; -} - -/*****************************************************************************/ -void GSIBlock::PrintMessage( ByteString aType, ByteString aMsg, ByteString aPrefix, - ByteString aContext, ULONG nLine, ByteString aUniqueId ) -/*****************************************************************************/ -{ - ::PrintMessage( aType, aMsg, aPrefix, aContext, bPrintContext, nLine, aUniqueId ); -} - -/*****************************************************************************/ -void GSIBlock::PrintError( ByteString aMsg, ByteString aPrefix, - ByteString aContext, ULONG nLine, ByteString aUniqueId ) -/*****************************************************************************/ -{ - PrintMessage( "Error:", aMsg, aPrefix, aContext, nLine, aUniqueId ); -} - -/*****************************************************************************/ -void GSIBlock::PrintList( ParserMessageList *pList, ByteString aPrefix, - GSILine *pLine ) -/*****************************************************************************/ -{ - ULONG i; - for ( i = 0 ; i < pList->Count() ; i++ ) - { - ParserMessage *pMsg = pList->GetObject( i ); - ByteString aContext; - if ( bPrintContext ) - { - if ( pMsg->GetTagBegin() == STRING_NOTFOUND ) - aContext = pLine->GetText().Copy( 0, 300 ); - else - aContext = pLine->Copy( pMsg->GetTagBegin()-150, 300 ); - aContext.EraseTrailingChars(' '); - aContext.EraseLeadingChars(' '); - } - - PrintMessage( pMsg->Prefix(), pMsg->GetErrorText(), aPrefix, aContext, pLine->GetLineNumber(), pLine->GetUniqId() ); - } -} - -/*****************************************************************************/ -BOOL GSIBlock::IsUTF8( const ByteString &aTestee, BOOL bFixTags, USHORT &nErrorPos, ByteString &aErrorMsg, BOOL &bHasBeenFixed, ByteString &aFixed ) const -/*****************************************************************************/ -{ - String aUTF8Tester( aTestee, RTL_TEXTENCODING_UTF8 ); - if ( STRING_MATCH != (nErrorPos = ByteString( aUTF8Tester, RTL_TEXTENCODING_UTF8 ).Match( aTestee )) ) - { - aUTF8Tester = String( aTestee.GetBuffer(), nErrorPos, RTL_TEXTENCODING_UTF8 ); - nErrorPos = aUTF8Tester.Len(); - aErrorMsg = ByteString( "UTF8 Encoding seems to be broken" ); - return FALSE; - } - - nErrorPos = aUTF8Tester.SearchChar( String::CreateFromAscii( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f" ).GetBuffer() ); - if ( nErrorPos != STRING_NOTFOUND ) - { - aErrorMsg = ByteString( "String contains illegal character" ); - return FALSE; - } - - if ( bFixTags ) - { - bHasBeenFixed = FALSE; - aFixed.Erase(); - } - - if ( !bAllowKeyIDs ) - { - BOOL bIsKeyID = FALSE; - BOOL bNewId = FALSE; - ByteString aID( aTestee ); - USHORT nAfterID = 0; - - if ( aTestee.Equals( "{&", 0, 2 ) ) - { // check for strings from instset_native like "{&Tahoma8}335795.Installation Wiza ..." - USHORT nTagEnd = aTestee.Search( '}' ); - if ( nTagEnd != STRING_NOTFOUND ) - { - if ( bFixTags ) - aFixed = aTestee.Copy( 0, nTagEnd+1 ); - nErrorPos = nTagEnd+1; - aID = aTestee.Copy( nTagEnd+1 ); - nAfterID = nTagEnd+1; - } - } - - ByteString aDelimiter( (String)String( sal_Unicode(0x2016) ), RTL_TEXTENCODING_UTF8 ); - - if ( aID.Equals( aDelimiter, 6, aDelimiter.Len() ) ) - { // New KeyId 6 Letters, digits and spechial chars followed by delimiter - bNewId = TRUE; - nErrorPos = 1; - aID = aID.Copy( 0, 6 ); - nAfterID += 6; - nAfterID = nAfterID + aDelimiter.Len(); - } - else if ( ( aID.GetChar(6) == '*' ) && aID.Equals( aDelimiter, 7, aDelimiter.Len() ) ) - { // New KeyId 6 Letters, digits and spechial chars followed by '*delimiter' to indicate translation in progress - bNewId = TRUE; - nErrorPos = 1; - aID = aID.Copy( 0, 6 ); - nAfterID += 7; - nAfterID = nAfterID + aDelimiter.Len(); - } - else if ( aID.GetTokenCount( '.' ) > 1 ) - { // test for old KeyIDs 5 to 6 digits followed by a dot '44373.' - bNewId = FALSE; - nErrorPos = 1; - aID = aID.GetToken( 0, '.' ); - nAfterID = nAfterID + aID.Len(); - } - else - { - aID.Erase(); - } - - if ( bNewId ) - { - if ( aID.Len() == 6 ) - { - bIsKeyID = TRUE; - ByteString aDigits("0123456789abcdefghijklmnopqrstuvwxyz+-<=>"); - for ( USHORT i=0 ; i < aID.Len() ;i++ ) - { - if ( aDigits.Search( aID.GetChar(i) ) == STRING_NOTFOUND ) - bIsKeyID = FALSE; - } - } - } - else - { - if ( aID.Len() > 0 && aID.GetChar(aID.Len()-1) == '*' ) - aID.Erase( aID.Len()-1 ); - - if ( aID.IsNumericAscii() && aID.Len() >= 5 ) - bIsKeyID = TRUE; - } - - if ( bIsKeyID ) - { - aErrorMsg = ByteString( "String contains KeyID" ); - if ( bFixTags ) - { - aFixed += aTestee.Copy( nAfterID ); - bHasBeenFixed = TRUE; - aErrorMsg = ByteString( "FIXED String containing KeyID" ); - } - else - aErrorMsg = ByteString( "String contains KeyID" ); - return FALSE; - } - } - - return TRUE; -} - -/*****************************************************************************/ -BOOL GSIBlock::TestUTF8( GSILine* pTestee, BOOL bFixTags ) -/*****************************************************************************/ -{ - USHORT nErrorPos = 0; - ByteString aErrorMsg; - BOOL bError = FALSE; - ByteString aFixed; - BOOL bHasBeenFixed = FALSE; - if ( !IsUTF8( pTestee->GetText(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) - { - ByteString aContext( pTestee->GetText().Copy( nErrorPos, 20 ) ); - PrintError( aErrorMsg.Append(" in Text at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); - bError = TRUE; - if ( bHasBeenFixed ) - { - pTestee->SetText( aFixed ); - pTestee->SetFixed(); - } - } - if ( !IsUTF8( pTestee->GetQuickHelpText(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) - { - ByteString aContext( pTestee->GetQuickHelpText().Copy( nErrorPos, 20 ) ); - PrintError( aErrorMsg.Append(" in QuickHelpText at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); - bError = TRUE; - if ( bHasBeenFixed ) - { - pTestee->SetQuickHelpText( aFixed ); - pTestee->SetFixed(); - } - } - if ( !IsUTF8( pTestee->GetTitle(), bFixTags, nErrorPos, aErrorMsg, bHasBeenFixed, aFixed ) ) - { - ByteString aContext( pTestee->GetTitle().Copy( nErrorPos, 20 ) ); - PrintError( aErrorMsg.Append(" in Title at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); - bError = TRUE; - if ( bHasBeenFixed ) - { - pTestee->SetTitle( aFixed ); - pTestee->SetFixed(); - } - } - if ( bError ) - pTestee->NotOK(); - return !bError; -} - - -/*****************************************************************************/ -BOOL GSIBlock::HasSuspiciousChars( GSILine* pTestee, GSILine* pSource ) -/*****************************************************************************/ -{ - USHORT nPos = 0; - if ( !bAllowSuspicious && ( nPos = pTestee->GetText().Search("??")) != STRING_NOTFOUND ) - if ( pSource->GetText().Search("??") == STRING_NOTFOUND ) - { - String aUTF8Tester = String( pTestee->GetText(), 0, nPos, RTL_TEXTENCODING_UTF8 ); - USHORT nErrorPos = aUTF8Tester.Len(); - ByteString aContext( pTestee->GetText().Copy( nPos, 20 ) ); - PrintError( ByteString("Found double questionmark in translation only. Looks like an encoding problem at Position " ).Append( ByteString::CreateFromInt32( nErrorPos ) ), "Text format", aContext, pTestee->GetLineNumber(), pTestee->GetUniqId() ); - pTestee->NotOK(); - return TRUE; - } - - return FALSE; -} - - -/*****************************************************************************/ -BOOL GSIBlock::CheckSyntax( ULONG nLine, BOOL bRequireSourceLine, BOOL bFixTags ) -/*****************************************************************************/ -{ - static LingTest aTester; - BOOL bHasError = FALSE; - - if ( !pSourceLine ) - { - if ( bRequireSourceLine ) - { - PrintError( "No source language entry defined!", "File format", "", nLine ); - bHasBlockError = TRUE; - } - } - else - { - aTester.CheckReference( pSourceLine ); - if ( pSourceLine->HasMessages() ) - { - PrintList( pSourceLine->GetMessageList(), "ReferenceString", pSourceLine ); - pSourceLine->NotOK(); - bHasError = TRUE; - } - } - if ( bReference ) - { - if ( !pReferenceLine ) - { - GSILine *pSource; - if ( pSourceLine ) - pSource = pSourceLine; - else - pSource = GetObject( 0 ); // get some other line - if ( pSource ) - PrintError( "No reference line found. Entry is new in source file", "File format", "", pSource->GetLineNumber(), pSource->GetUniqId() ); - else - PrintError( "No reference line found. Entry is new in source file", "File format", "", nLine ); - bHasBlockError = TRUE; - } - else - { - if ( pSourceLine && !pSourceLine->Equals( *pReferenceLine ) ) - { - xub_StrLen nPos = pSourceLine->Match( *pReferenceLine ); - ByteString aContext( pReferenceLine->Copy( nPos - 5, 15) ); - aContext.Append( "\" --> \"" ).Append( pSourceLine->Copy( nPos - 5, 15) ); - PrintError( "Source Language Entry has changed.", "File format", aContext, pSourceLine->GetLineNumber(), pSourceLine->GetUniqId() ); - pSourceLine->NotOK(); - bHasError = TRUE; - } - } - } - - if ( pSourceLine ) - bHasError |= !TestUTF8( pSourceLine, bFixTags ); - - ULONG i; - for ( i = 0; i < Count(); i++ ) - { - aTester.CheckTestee( GetObject( i ), pSourceLine != NULL, bFixTags ); - if ( GetObject( i )->HasMessages() || aTester.HasCompareWarnings() ) - { - if ( GetObject( i )->HasMessages() || aTester.GetCompareWarnings().HasErrors() ) - GetObject( i )->NotOK(); - bHasError = TRUE; - PrintList( GetObject( i )->GetMessageList(), "Translation", GetObject( i ) ); - PrintList( &(aTester.GetCompareWarnings()), "Translation Tag Missmatch", GetObject( i ) ); - } - bHasError |= !TestUTF8( GetObject( i ), bFixTags ); - if ( pSourceLine ) - bHasError |= HasSuspiciousChars( GetObject( i ), pSourceLine ); - } - - return bHasError || bHasBlockError; -} - -void GSIBlock::WriteError( LazySvFileStream &aErrOut, BOOL bRequireSourceLine ) -{ - if ( pSourceLine && pSourceLine->IsOK() && bCheckSourceLang && !bHasBlockError ) - return; - - BOOL bHasError = FALSE; - BOOL bCopyAll = ( !pSourceLine && bRequireSourceLine ) || ( pSourceLine && !pSourceLine->IsOK() && !bCheckTranslationLang ) || bHasBlockError; - ULONG i; - for ( i = 0; i < Count(); i++ ) - { - if ( !GetObject( i )->IsOK() || bCopyAll ) - { - bHasError = TRUE; - aErrOut.LazyOpen(); - aErrOut.WriteLine( *GetObject( i ) ); - } - } - - if ( pSourceLine && ( bHasError || !pSourceLine->IsOK() ) && !( !bHasError && bCheckTranslationLang ) ) - { - aErrOut.LazyOpen(); - aErrOut.WriteLine( *pSourceLine ); - } -} - -void GSIBlock::WriteCorrect( LazySvFileStream &aOkOut, BOOL bRequireSourceLine ) -{ - if ( ( !pSourceLine && bRequireSourceLine ) || ( pSourceLine && !pSourceLine->IsOK() && !bCheckTranslationLang ) ) - return; - - BOOL bHasOK = FALSE; - ULONG i; - for ( i = 0; i < Count(); i++ ) - { - if ( ( GetObject( i )->IsOK() || bCheckSourceLang ) && !bHasBlockError ) - { - bHasOK = TRUE; - aOkOut.LazyOpen(); - aOkOut.WriteLine( *GetObject( i ) ); - } - } - - if ( ( pSourceLine && pSourceLine->IsOK() && ( Count() || !bCheckTranslationLang ) ) || ( bHasOK && bCheckTranslationLang ) ) - { - aOkOut.LazyOpen(); - aOkOut.WriteLine( *pSourceLine ); - } -} - -void GSIBlock::WriteFixed( LazySvFileStream &aFixOut, BOOL /*bRequireSourceLine*/ ) -{ - if ( pSourceLine && !pSourceLine->IsFixed() && bCheckSourceLang ) - return; - - BOOL bHasFixes = FALSE; - ULONG i; - for ( i = 0; i < Count(); i++ ) - { - if ( GetObject( i )->IsFixed() ) - { - bHasFixes = TRUE; - aFixOut.LazyOpen(); - aFixOut.WriteLine( *GetObject( i ) ); - } - } - - if ( pSourceLine && ( bHasFixes || pSourceLine->IsFixed() ) ) - { - aFixOut.LazyOpen(); - aFixOut.WriteLine( *pSourceLine ); - } -} - - -/*****************************************************************************/ -/*****************************************************************************/ -/*****************************************************************************/ -/*****************************************************************************/ -/*****************************************************************************/ -/*****************************************************************************/ -/*****************************************************************************/ - -/*****************************************************************************/ -void Help() -/*****************************************************************************/ -{ - fprintf( stdout, "\n" ); - fprintf( stdout, "gsicheck Version 1.9.0 (c)1999 - 2006 by SUN Microsystems\n" ); - fprintf( stdout, "=========================================================\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "gsicheck checks the syntax of tags in GSI-Files and SDF-Files\n" ); - fprintf( stdout, " checks for inconsistencies and malicious UTF8 encoding\n" ); - fprintf( stdout, " checks tags in Online Help\n" ); - fprintf( stdout, " checks for *new* KeyIDs and relax GID/LID length to %s\n", ByteString::CreateFromInt32(MAX_GID_LID_LEN).GetBuffer() ); - fprintf( stdout, "\n" ); - fprintf( stdout, "Syntax: gsicheck [ -c ] [-f] [ -we ] [ -wef ErrorFilename ] [ -wc ]\n" ); - fprintf( stdout, " [ -wcf CorrectFilename ] [ -s | -t ] [ -l LanguageID ]\n" ); - fprintf( stdout, " [ -r ReferenceFile ] filename\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "-c Add context to error message (Print the line containing the error)\n" ); - fprintf( stdout, "-f try to fix errors. See also -wf -wff \n" ); - fprintf( stdout, "-wf Write File containing all fixed parts\n" ); - fprintf( stdout, "-wff Same as above but give own filename\n" ); - fprintf( stdout, "-we Write File containing all errors\n" ); - fprintf( stdout, "-wef Same as above but give own filename\n" ); - fprintf( stdout, "-wc Write File containing all correct parts\n" ); - fprintf( stdout, "-wcf Same as above but give own filename\n" ); - fprintf( stdout, "-s Check only source language. Should be used before handing out to vendor.\n" ); - fprintf( stdout, "-t Check only Translation language(s). Should be used before merging.\n" ); - fprintf( stdout, "-k Allow KeyIDs to be present in strings\n" ); - fprintf( stdout, "-e disable encoding checks. E.g.: double questionmark \'??\' which may be the\n" ); - fprintf( stdout, " result of false conversions\n" ); - fprintf( stdout, "-l ISO Languagecode or numerical 2 digits Identifier of the source language.\n" ); - fprintf( stdout, " Default is en-US. Use \"\" (empty string) or 'none'\n" ); - fprintf( stdout, " to disable source language dependent checks\n" ); - fprintf( stdout, "-r Reference filename to check that source language entries\n" ); - fprintf( stdout, " have not been changed\n" ); - fprintf( stdout, "\n" ); -} - -/*****************************************************************************/ -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - - BOOL bError = FALSE; - BOOL bPrintContext = FALSE; - BOOL bCheckSourceLang = FALSE; - BOOL bCheckTranslationLang = FALSE; - BOOL bWriteError = FALSE; - BOOL bWriteCorrect = FALSE; - BOOL bWriteFixed = FALSE; - BOOL bFixTags = FALSE; - BOOL bAllowKID = FALSE; - BOOL bAllowSuspicious = FALSE; - String aErrorFilename; - String aCorrectFilename; - String aFixedFilename; - BOOL bFileHasError = FALSE; - ByteString aSourceLang( "en-US" ); // English is default - ByteString aFilename; - ByteString aReferenceFilename; - BOOL bReferenceFile = FALSE; - for ( USHORT i = 1 ; i < argc ; i++ ) - { - if ( *argv[ i ] == '-' ) - { - switch (*(argv[ i ]+1)) - { - case 'c':bPrintContext = TRUE; - break; - case 'w': - { - if ( (*(argv[ i ]+2)) == 'e' ) - { - if ( (*(argv[ i ]+3)) == 'f' ) - if ( (i+1) < argc ) - { - aErrorFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); - bWriteError = TRUE; - i++; - } - else - { - fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); - bError = TRUE; - } - else - bWriteError = TRUE; - } - else if ( (*(argv[ i ]+2)) == 'c' ) - if ( (*(argv[ i ]+3)) == 'f' ) - if ( (i+1) < argc ) - { - aCorrectFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); - bWriteCorrect = TRUE; - i++; - } - else - { - fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); - bError = TRUE; - } - else - bWriteCorrect = TRUE; - else if ( (*(argv[ i ]+2)) == 'f' ) - if ( (*(argv[ i ]+3)) == 'f' ) - if ( (i+1) < argc ) - { - aFixedFilename = String( argv[ i+1 ], RTL_TEXTENCODING_ASCII_US ); - bWriteFixed = TRUE; - bFixTags = TRUE; - i++; - } - else - { - fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); - bError = TRUE; - } - else - { - bWriteFixed = TRUE; - bFixTags = TRUE; - } - else - { - fprintf( stderr, "\nERROR: Unknown Switch %s!\n\n", argv[ i ] ); - bError = TRUE; - } - } - break; - case 's':bCheckSourceLang = TRUE; - break; - case 't':bCheckTranslationLang = TRUE; - break; - case 'l': - { - if ( (i+1) < argc ) - { - aSourceLang = ByteString( argv[ i+1 ] ); - if ( aSourceLang.EqualsIgnoreCaseAscii( "none" ) ) - aSourceLang.Erase(); - i++; - } - else - { - fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); - bError = TRUE; - } - } - break; - case 'r': - { - if ( (i+1) < argc ) - { - aReferenceFilename = argv[ i+1 ]; - bReferenceFile = TRUE; - i++; - } - else - { - fprintf( stderr, "\nERROR: Switch %s requires parameter!\n\n", argv[ i ] ); - bError = TRUE; - } - } - break; - case 'f': - { - bFixTags = TRUE; - } - break; - case 'k': - { - bAllowKID = TRUE; - } - break; - case 'e': - { - bAllowSuspicious = TRUE; - } - break; - default: - fprintf( stderr, "\nERROR: Unknown Switch %s!\n\n", argv[ i ] ); - bError = TRUE; - } - } - else - { - if ( !aFilename.Len()) - aFilename = ByteString( argv[ i ] ); - else - { - fprintf( stderr, "\nERROR: Only one filename may be specified!\n\n"); - bError = TRUE; - } - } - } - - - if ( !aFilename.Len() || bError ) - { - Help(); - exit ( 0 ); - } - - if ( aSourceLang.Len() && !LanguageOK( aSourceLang ) ) - { - fprintf( stderr, "\nERROR: The Language '%s' is invalid!\n\n", aSourceLang.GetBuffer() ); - Help(); - exit ( 1 ); - } - - if ( bCheckSourceLang && bCheckTranslationLang ) - { - fprintf( stderr, "\nERROR: The Options -s and -t are mutually exclusive.\nUse only one of them.\n\n" ); - Help(); - exit ( 1 ); - } - - - - DirEntry aSource = DirEntry( String( aFilename, RTL_TEXTENCODING_ASCII_US )); - if ( !aSource.Exists()) { - fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", aFilename.GetBuffer() ); - exit ( 2 ); - } - - SvFileStream aGSI( String( aFilename, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); - if ( !aGSI.IsOpen()) { - fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", aFilename.GetBuffer() ); - exit ( 3 ); - } - - SvFileStream aReferenceGSI; - if ( bReferenceFile ) - { - DirEntry aReferenceSource = DirEntry( String( aReferenceFilename, RTL_TEXTENCODING_ASCII_US )); - if ( !aReferenceSource.Exists()) { - fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", aFilename.GetBuffer() ); - exit ( 2 ); - } - - aReferenceGSI.Open( String( aReferenceFilename, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); - if ( !aReferenceGSI.IsOpen()) { - fprintf( stderr, "\nERROR: Could not open Input-File %s!\n\n", aFilename.GetBuffer() ); - exit ( 3 ); - } - } - - LazySvFileStream aOkOut; - String aBaseName = aSource.GetBase(); - if ( bWriteCorrect ) - { - if ( !aCorrectFilename.Len() ) - { - String sTmpBase( aBaseName ); - sTmpBase += String( "_ok", RTL_TEXTENCODING_ASCII_US ); - aSource.SetBase( sTmpBase ); - aCorrectFilename = aSource.GetFull(); - } - aOkOut.SetOpenParams( aCorrectFilename , STREAM_STD_WRITE | STREAM_TRUNC ); - } - - LazySvFileStream aErrOut; - if ( bWriteError ) - { - if ( !aErrorFilename.Len() ) - { - String sTmpBase( aBaseName ); - sTmpBase += String( "_err", RTL_TEXTENCODING_ASCII_US ); - aSource.SetBase( sTmpBase ); - aErrorFilename = aSource.GetFull(); - } - aErrOut.SetOpenParams( aErrorFilename , STREAM_STD_WRITE | STREAM_TRUNC ); - } - - LazySvFileStream aFixOut; - if ( bWriteFixed ) - { - if ( !aFixedFilename.Len() ) - { - String sTmpBase( aBaseName ); - sTmpBase += String( "_fix", RTL_TEXTENCODING_ASCII_US ); - aSource.SetBase( sTmpBase ); - aFixedFilename = aSource.GetFull(); - } - aFixOut.SetOpenParams( aFixedFilename , STREAM_STD_WRITE | STREAM_TRUNC ); - } - - - ByteString sReferenceLine; - GSILine* pReferenceLine = NULL; - ByteString aOldReferenceId("No Valid ID"); // just set to something which can never be an ID - ULONG nReferenceLine = 0; - - ByteString sGSILine; - GSILine* pGSILine = NULL; - ByteString aOldId("No Valid ID"); // just set to something which can never be an ID - GSIBlock *pBlock = NULL; - ULONG nLine = 0; - - while ( !aGSI.IsEof() ) - { - aGSI.ReadLine( sGSILine ); - nLine++; - pGSILine = new GSILine( sGSILine, nLine ); - BOOL bDelete = TRUE; - - - if ( pGSILine->Len() ) - { - if ( FORMAT_UNKNOWN == pGSILine->GetLineFormat() ) - { - PrintError( "Format of line is unknown. Ignoring!", "Line format", pGSILine->Copy( 0,40 ), bPrintContext, pGSILine->GetLineNumber() ); - pGSILine->NotOK(); - if ( bWriteError ) - { - bFileHasError = TRUE; - aErrOut.LazyOpen(); - aErrOut.WriteLine( *pGSILine ); - } - } - else if ( pGSILine->GetLineType().EqualsIgnoreCaseAscii("res-comment") ) - { // ignore comment lines, but write them to Correct Items File - if ( bWriteCorrect ) - { - aOkOut.LazyOpen(); - aOkOut.WriteLine( *pGSILine ); - } - } - else - { - ByteString aId = pGSILine->GetUniqId(); - if ( aId != aOldId ) - { - if ( pBlock ) - { - bFileHasError |= pBlock->CheckSyntax( nLine, aSourceLang.Len() != 0, bFixTags ); - - if ( bWriteError ) - pBlock->WriteError( aErrOut, aSourceLang.Len() != 0 ); - if ( bWriteCorrect ) - pBlock->WriteCorrect( aOkOut, aSourceLang.Len() != 0 ); - if ( bWriteFixed ) - pBlock->WriteFixed( aFixOut, aSourceLang.Len() != 0 ); - - delete pBlock; - } - pBlock = new GSIBlock( bPrintContext, bCheckSourceLang, bCheckTranslationLang, bReferenceFile, bAllowKID, bAllowSuspicious ); - - aOldId = aId; - - - // find corresponding line in reference file - if ( bReferenceFile ) - { - BOOL bContinueSearching = TRUE; - while ( ( !aReferenceGSI.IsEof() || pReferenceLine ) && bContinueSearching ) - { - if ( !pReferenceLine ) - { - aReferenceGSI.ReadLine( sReferenceLine ); - nReferenceLine++; - pReferenceLine = new GSILine( sReferenceLine, nReferenceLine ); - } - if ( pReferenceLine->GetLineFormat() != FORMAT_UNKNOWN ) - { - if ( pReferenceLine->GetUniqId() == aId && pReferenceLine->GetLanguageId().Equals( aSourceLang ) ) - { - pBlock->SetReferenceLine( pReferenceLine ); - pReferenceLine = NULL; - } - else if ( pReferenceLine->GetUniqId() > aId ) - { -// if ( pGSILine->GetLanguageId() == aSourceLang ) -// PrintError( "No reference line found. Entry is new in source file", "File format", "", bPrintContext, pGSILine->GetLineNumber(), aId ); - bContinueSearching = FALSE; - } - else - { - if ( pReferenceLine->GetUniqId() < aId && pReferenceLine->GetLanguageId().Equals( aSourceLang ) ) - PrintError( "No Entry in source file found. Entry has been removed from source file", "File format", "", bPrintContext, pGSILine->GetLineNumber(), pReferenceLine->GetUniqId() ); - delete pReferenceLine; - pReferenceLine = NULL; - } - } - else - { - delete pReferenceLine; - pReferenceLine = NULL; - } - - } - } - - } - - pBlock->InsertLine( pGSILine, aSourceLang ); - bDelete = FALSE; - } - } - if ( bDelete ) - delete pGSILine; - - } - if ( pBlock ) - { - bFileHasError |= pBlock->CheckSyntax( nLine, aSourceLang.Len() != 0, bFixTags ); - - if ( bWriteError ) - pBlock->WriteError( aErrOut, aSourceLang.Len() != 0 ); - if ( bWriteCorrect ) - pBlock->WriteCorrect( aOkOut, aSourceLang.Len() != 0 ); - if ( bWriteFixed ) - pBlock->WriteFixed( aFixOut, aSourceLang.Len() != 0 ); - - delete pBlock; - } - aGSI.Close(); - - if ( bWriteError ) - aErrOut.Close(); - if ( bWriteCorrect ) - aOkOut.Close(); - if ( bWriteFixed ) - aFixOut.Close(); - - if ( bFileHasError ) - return 55; - else - return 0; -} diff --git a/transex3/source/gsiconv.cxx b/transex3/source/gsiconv.cxx deleted file mode 100644 index f6dea76ebb51..000000000000 --- a/transex3/source/gsiconv.cxx +++ /dev/null @@ -1,372 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: gsiconv.cxx,v $ - * $Revision: 1.8 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -#include - -// local includes -#include "utf8conv.hxx" - -#define GSI_FILE_UNKNOWN 0x0000 -#define GSI_FILE_OLDSTYLE 0x0001 -#define GSI_FILE_L10NFRAMEWORK 0x0002 - -/*****************************************************************************/ -USHORT GetGSIFileType( SvStream &rStream ) -/*****************************************************************************/ -{ - USHORT nFileType = GSI_FILE_UNKNOWN; - - ULONG nPos( rStream.Tell()); - rStream.Seek( STREAM_SEEK_TO_BEGIN ); - - ByteString sLine; - while( !rStream.IsEof() && !sLine.Len()) - rStream.ReadLine( sLine ); - - if( sLine.Len()) { - if( sLine.Search( "($$)" ) != STRING_NOTFOUND ) - nFileType = GSI_FILE_OLDSTYLE; - else - nFileType = GSI_FILE_L10NFRAMEWORK; - } - - rStream.Seek( nPos ); - - return nFileType; -} - -/*****************************************************************************/ -ByteString GetGSILineId( const ByteString &rLine, USHORT nFileType ) -/*****************************************************************************/ -{ - ByteString sId; - switch ( nFileType ) { - case GSI_FILE_OLDSTYLE: - sId = rLine; - sId.SearchAndReplaceAll( "($$)", "\t" ); - sId = sId.GetToken( 0, '\t' ); - break; - - case GSI_FILE_L10NFRAMEWORK: - sId = rLine.GetToken( 0, '\t' ); - sId += "\t"; - sId += rLine.GetToken( 1, '\t' ); - sId += "\t"; - sId += rLine.GetToken( 4, '\t' ); - sId += "\t"; - sId += rLine.GetToken( 5, '\t' ); - break; - } - return sId; -} - -/*****************************************************************************/ -ByteString GetGSILineLangId( const ByteString &rLine, USHORT nFileType ) -/*****************************************************************************/ -{ - ByteString sLangId; - switch ( nFileType ) { - case GSI_FILE_OLDSTYLE: - sLangId = rLine; - sLangId.SearchAndReplaceAll( "($$)", "\t" ); - sLangId = sLangId.GetToken( 2, '\t' ); - break; - - case GSI_FILE_L10NFRAMEWORK: - sLangId = rLine.GetToken( 9, '\t' ); - break; - } - return sLangId; -} - -/*****************************************************************************/ -void ConvertGSILine( BOOL bToUTF8, ByteString &rLine, - rtl_TextEncoding nEncoding, USHORT nFileType ) -/*****************************************************************************/ -{ - switch ( nFileType ) { - case GSI_FILE_OLDSTYLE: - if ( bToUTF8 ) - rLine = UTF8Converter::ConvertToUTF8( rLine, nEncoding ); - else - rLine = UTF8Converter::ConvertFromUTF8( rLine, nEncoding ); - break; - - case GSI_FILE_L10NFRAMEWORK: { - ByteString sConverted; - for ( USHORT i = 0; i < rLine.GetTokenCount( '\t' ); i++ ) { - ByteString sToken = rLine.GetToken( i, '\t' ); - if (( i > 9 ) && ( i < 14 )) { - if( bToUTF8 ) - sToken = UTF8Converter::ConvertToUTF8( sToken, nEncoding ); - else - sToken = UTF8Converter::ConvertFromUTF8( sToken, nEncoding ); - } - if ( i ) - sConverted += "\t"; - sConverted += sToken; - } - rLine = sConverted; - } - break; - } -} - -/*****************************************************************************/ -void Help() -/*****************************************************************************/ -{ - fprintf( stdout, "\n" ); - fprintf( stdout, "gsiconv (c)1999 by StarOffice Entwicklungs GmbH\n" ); - fprintf( stdout, "===============================================\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "gsiconv converts strings in GSI-Files (Gutschmitt Interface) from or to UTF-8\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "Syntax: gsiconv (-t|-f langid charset)|(-p n) filename\n" ); - fprintf( stdout, "Switches: -t => conversion from charset to UTF-8\n" ); - fprintf( stdout, " -f => conversion from UTF-8 to charset\n" ); - fprintf( stdout, " -p n => creates several files with ca. n lines\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "Allowed charsets:\n" ); - fprintf( stdout, " MS_932 => Japanese\n" ); - fprintf( stdout, " MS_936 => Chinese Simplified\n" ); - fprintf( stdout, " MS_949 => Korean\n" ); - fprintf( stdout, " MS_950 => Chinese Traditional\n" ); - fprintf( stdout, " MS_1250 => East Europe\n" ); - fprintf( stdout, " MS_1251 => Cyrillic\n" ); - fprintf( stdout, " MS_1252 => West Europe\n" ); - fprintf( stdout, " MS_1253 => Greek\n" ); - fprintf( stdout, " MS_1254 => Turkish\n" ); - fprintf( stdout, " MS_1255 => Hebrew\n" ); - fprintf( stdout, " MS_1256 => Arabic\n" ); - fprintf( stdout, "\n" ); - fprintf( stdout, "Allowed langids:\n" ); - fprintf( stdout, " 1 => ENGLISH_US\n" ); - fprintf( stdout, " 3 => PORTUGUESE \n" ); - fprintf( stdout, " 4 => GERMAN_DE (new german style)\n" ); - fprintf( stdout, " 7 => RUSSIAN\n" ); - fprintf( stdout, " 30 => GREEK\n" ); - fprintf( stdout, " 31 => DUTCH\n" ); - fprintf( stdout, " 33 => FRENCH\n" ); - fprintf( stdout, " 34 => SPANISH\n" ); - fprintf( stdout, " 35 => FINNISH\n" ); - fprintf( stdout, " 36 => HUNGARIAN\n" ); - fprintf( stdout, " 39 => ITALIAN\n" ); - fprintf( stdout, " 42 => CZECH\n" ); - fprintf( stdout, " 44 => ENGLISH (UK)\n" ); - fprintf( stdout, " 45 => DANISH\n" ); - fprintf( stdout, " 46 => SWEDISH\n" ); - fprintf( stdout, " 47 => NORWEGIAN\n" ); - fprintf( stdout, " 49 => GERMAN (old german style)\n" ); - fprintf( stdout, " 55 => PORTUGUESE_BRAZILIAN\n" ); - fprintf( stdout, " 81 => JAPANESE\n" ); - fprintf( stdout, " 82 => KOREAN\n" ); - fprintf( stdout, " 86 => CHINESE_SIMPLIFIED\n" ); - fprintf( stdout, " 88 => CHINESE_TRADITIONAL\n" ); - fprintf( stdout, " 90 => TURKISH\n" ); - fprintf( stdout, " 96 => ARABIC\n" ); - fprintf( stdout, " 97 => HEBREW\n" ); - fprintf( stdout, "\n" ); -} - -/*****************************************************************************/ -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - if (( argc != 5 ) && ( argc != 4 )) { - Help(); - exit ( 0 ); - } - - if ( argc == 4 ) { - if ( ByteString( argv[ 1 ] ) == "-p" ) { - - DirEntry aSource = DirEntry( String( argv[ 3 ], RTL_TEXTENCODING_ASCII_US )); - if ( !aSource.Exists()) { - fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); - exit ( 2 ); - } - - DirEntry aOutput( aSource ); - - String sBase = aOutput.GetBase(); - String sExt = aOutput.GetExtension(); - - String sGSI( argv[ 3 ], RTL_TEXTENCODING_ASCII_US ); - SvFileStream aGSI( sGSI, STREAM_STD_READ ); - if ( !aGSI.IsOpen()) { - fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); - exit ( 3 ); - } - - USHORT nFileType( GetGSIFileType( aGSI )); - - ULONG nMaxLines = (ULONG) ByteString( argv[ 2 ] ).ToInt64(); - if ( !nMaxLines ) { - fprintf( stderr, "\nERROR: Linecount must be at least 1!\n\n" ); - exit ( 3 ); - } - - ByteString sGSILine; - ByteString sOldId; - ULONG nLine = 0; - ULONG nOutputFile = 1; - - String sOutput( sBase ); - sOutput += String( "_", RTL_TEXTENCODING_ASCII_US ); - sOutput += String::CreateFromInt64( nOutputFile ); - if ( sExt.Len()) { - sOutput += String( ".", RTL_TEXTENCODING_ASCII_US ); - sOutput += sExt; - } - nOutputFile ++; - - aOutput.SetName( sOutput ); - SvFileStream aOutputStream( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); - - while ( !aGSI.IsEof()) { - - aGSI.ReadLine( sGSILine ); - ByteString sId( GetGSILineId( sGSILine, nFileType )); - - nLine++; - - if (( nLine >= nMaxLines ) && ( sId != sOldId )) { - aOutputStream.Close(); - - ByteString sText( aOutput.GetFull(), gsl_getSystemTextEncoding()); - sText += " with "; - sText += ByteString::CreateFromInt64( nLine ); - sText += " lines written."; - - fprintf( stdout, "%s\n", sText.GetBuffer()); - String sOutput1( sBase ); - sOutput1 += String( "_", RTL_TEXTENCODING_ASCII_US ); - sOutput1 += String::CreateFromInt64( nOutputFile ); - if ( sExt.Len()) { - sOutput1 += String( ".", RTL_TEXTENCODING_ASCII_US ); - sOutput1 += sExt; - } - nOutputFile ++; - - aOutput.SetName( sOutput1 ); - - aOutputStream.Open( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); - nLine = 0; - } - - aOutputStream.WriteLine( sGSILine ); - - sOldId = sId; - } - - aGSI.Close(); - aOutputStream.Close(); - - ByteString sText( aOutput.GetFull(), RTL_TEXTENCODING_ASCII_US ); - sText += " with "; - sText += ByteString::CreateFromInt64( nLine ); - sText += " lines written."; - } - else { - Help(); - exit( 1 ); - } - } - else { - if ( ByteString( argv[ 1 ] ) == "-t" || ByteString( argv[ 1 ] ) == "-f" ) { - rtl_TextEncoding nEncoding; - - ByteString sCurLangId( argv[ 2 ] ); - - ByteString sCharset( argv[ 3 ] ); - sCharset.ToUpperAscii(); - - if ( sCharset == "MS_932" ) nEncoding = RTL_TEXTENCODING_MS_932; - else if ( sCharset == "MS_936" ) nEncoding = RTL_TEXTENCODING_MS_936; - else if ( sCharset == "MS_949" ) nEncoding = RTL_TEXTENCODING_MS_949; - else if ( sCharset == "MS_950" ) nEncoding = RTL_TEXTENCODING_MS_950; - else if ( sCharset == "MS_1250" ) nEncoding = RTL_TEXTENCODING_MS_1250; - else if ( sCharset == "MS_1251" ) nEncoding = RTL_TEXTENCODING_MS_1251; - else if ( sCharset == "MS_1252" ) nEncoding = RTL_TEXTENCODING_MS_1252; - else if ( sCharset == "MS_1253" ) nEncoding = RTL_TEXTENCODING_MS_1253; - else if ( sCharset == "MS_1254" ) nEncoding = RTL_TEXTENCODING_MS_1254; - else if ( sCharset == "MS_1255" ) nEncoding = RTL_TEXTENCODING_MS_1255; - else if ( sCharset == "MS_1256" ) nEncoding = RTL_TEXTENCODING_MS_1256; - else if ( sCharset == "MS_1257" ) nEncoding = RTL_TEXTENCODING_MS_1257; - else if ( sCharset == "UTF8" ) nEncoding = RTL_TEXTENCODING_UTF8; - - else { - Help(); - exit ( 1 ); - } - - DirEntry aSource = DirEntry( String( argv[ 4 ], RTL_TEXTENCODING_ASCII_US )); - if ( !aSource.Exists()) { - fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); - exit ( 2 ); - } - - String sGSI( argv[ 4 ], RTL_TEXTENCODING_ASCII_US ); - SvFileStream aGSI( sGSI, STREAM_STD_READ ); - if ( !aGSI.IsOpen()) { - fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); - exit ( 3 ); - } - USHORT nFileType( GetGSIFileType( aGSI )); - - ByteString sGSILine; - while ( !aGSI.IsEof()) { - - aGSI.ReadLine( sGSILine ); - ByteString sLangId( GetGSILineLangId( sGSILine, nFileType )); - if ( sLangId == sCurLangId ) - ConvertGSILine(( ByteString( argv[ 1 ] ) == "-t" ), sGSILine, nEncoding, nFileType ); - - fprintf( stdout, "%s\n", sGSILine.GetBuffer()); - } - - aGSI.Close(); - } - else { - Help(); - exit( 1 ); - } - } - return 0; -} diff --git a/transex3/source/help/HelpCompiler.cxx b/transex3/source/help/HelpCompiler.cxx deleted file mode 100644 index 5001d0907972..000000000000 --- a/transex3/source/help/HelpCompiler.cxx +++ /dev/null @@ -1,593 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: HelpCompiler.cxx,v $ - * $Revision: 1.9 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - - -#include "HelpCompiler.hxx" -#include -#include -#include -#include -#include -#include -#include -#ifdef __MINGW32__ -#include -#include -#endif -#include - -static void impl_sleep( sal_uInt32 nSec ) -{ - TimeValue aTime; - aTime.Seconds = nSec; - aTime.Nanosec = 0; - - osl::Thread::wait( aTime ); -} - -HelpCompiler::HelpCompiler(StreamTable &in_streamTable, const fs::path &in_inputFile, - const fs::path &in_src, const fs::path &in_resEmbStylesheet, - const std::string &in_module, const std::string &in_lang, bool in_bExtensionMode) - : streamTable(in_streamTable), inputFile(in_inputFile), - src(in_src), module(in_module), lang(in_lang), resEmbStylesheet(in_resEmbStylesheet), - bExtensionMode( in_bExtensionMode ) -{ - xmlKeepBlanksDefaultValue = 0; -} - -xmlDocPtr HelpCompiler::getSourceDocument(const fs::path &filePath) -{ - static const char *params[4 + 1]; - static xsltStylesheetPtr cur = NULL; - - xmlDocPtr res; - if( bExtensionMode ) - { - res = xmlParseFile(filePath.native_file_string().c_str()); - if( !res ){ - impl_sleep( 3 ); - res = xmlParseFile(filePath.native_file_string().c_str()); - } - } - else - { - if (!cur) - { - static std::string fsroot('\'' + src.toUTF8() + '\''); - static std::string esclang('\'' + lang + '\''); - - xmlSubstituteEntitiesDefault(1); - xmlLoadExtDtdDefaultValue = 1; - cur = xsltParseStylesheetFile((const xmlChar *)resEmbStylesheet.native_file_string().c_str()); - - int nbparams = 0; - params[nbparams++] = "Language"; - params[nbparams++] = esclang.c_str(); - params[nbparams++] = "fsroot"; - params[nbparams++] = fsroot.c_str(); - params[nbparams] = NULL; - } - xmlDocPtr doc = xmlParseFile(filePath.native_file_string().c_str()); - if( !doc ) - { - impl_sleep( 3 ); - doc = xmlParseFile(filePath.native_file_string().c_str()); - } - - //???res = xmlParseFile(filePath.native_file_string().c_str()); - - res = xsltApplyStylesheet(cur, doc, params); - xmlFreeDoc(doc); - } - return res; -} - -HashSet HelpCompiler::switchFind(xmlDocPtr doc) -{ - HashSet hs; - xmlChar *xpath = (xmlChar*)"//switchinline"; - - xmlXPathContextPtr context = xmlXPathNewContext(doc); - xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context); - xmlXPathFreeContext(context); - if (result) - { - xmlNodeSetPtr nodeset = result->nodesetval; - for (int i = 0; i < nodeset->nodeNr; i++) - { - xmlNodePtr el = nodeset->nodeTab[i]; - xmlChar *select = xmlGetProp(el, (xmlChar*)"select"); - if (select) - { - if (!strcmp((const char*)select, "appl")) - { - xmlNodePtr n1 = el->xmlChildrenNode; - while (n1) - { - if ((!xmlStrcmp(n1->name, (const xmlChar*)"caseinline"))) - { - xmlChar *appl = xmlGetProp(n1, (xmlChar*)"select"); - hs.push_back(std::string((const char*)appl)); - xmlFree(appl); - } - else if ((!xmlStrcmp(n1->name, (const xmlChar*)"defaultinline"))) - hs.push_back(std::string("DEFAULT")); - n1 = n1->next; - } - } - xmlFree(select); - } - } - xmlXPathFreeObject(result); - } - hs.push_back(std::string("DEFAULT")); - return hs; -} - -// returns a node representing the whole stuff compiled for the current -// application. -xmlNodePtr HelpCompiler::clone(xmlNodePtr node, const std::string& appl) -{ - xmlNodePtr parent = xmlCopyNode(node, 2); - xmlNodePtr n = node->xmlChildrenNode; - while (n != NULL) - { - bool isappl = false; - if ( (!strcmp((const char*)n->name, "switchinline")) || - (!strcmp((const char*)n->name, "switch")) ) - { - xmlChar *select = xmlGetProp(n, (xmlChar*)"select"); - if (select) - { - if (!strcmp((const char*)select, "appl")) - isappl = true; - xmlFree(select); - } - } - if (isappl) - { - xmlNodePtr caseNode = n->xmlChildrenNode; - if (appl == "DEFAULT") - { - while (caseNode) - { - if (!strcmp((const char*)caseNode->name, "defaultinline")) - { - xmlNodePtr cnl = caseNode->xmlChildrenNode; - while (cnl) - { - xmlAddChild(parent, clone(cnl, appl)); - cnl = cnl->next; - } - break; - } - caseNode = caseNode->next; - } - } - else - { - while (caseNode) - { - isappl=false; - if (!strcmp((const char*)caseNode->name, "caseinline")) - { - xmlChar *select = xmlGetProp(n, (xmlChar*)"select"); - if (select) - { - if (!strcmp((const char*)select, appl.c_str())) - isappl = true; - xmlFree(select); - } - if (isappl) - { - xmlNodePtr cnl = caseNode->xmlChildrenNode; - while (cnl) - { - xmlAddChild(parent, clone(cnl, appl)); - cnl = cnl->next; - } - break; - } - - } - caseNode = caseNode->next; - } - } - - } - else - xmlAddChild(parent, clone(n, appl)); - - n = n->next; - } - return parent; -} - -class myparser -{ -public: - std::string documentId; - std::string fileName; - std::string title; - HashSet *hidlist; - Hashtable *keywords; - Stringtable *helptexts; -private: - HashSet extendedHelpText; -public: - myparser(const std::string &indocumentId, const std::string &infileName, - const std::string &intitle) : documentId(indocumentId), fileName(infileName), - title(intitle) - { - hidlist = new HashSet; - keywords = new Hashtable; - helptexts = new Stringtable; - } - void traverse( xmlNodePtr parentNode ); -private: - std::string dump(xmlNodePtr node); -}; - -std::string myparser::dump(xmlNodePtr node) -{ - std::string app; - if (node->xmlChildrenNode) - { - xmlNodePtr list = node->xmlChildrenNode; - while (list) - { - app += dump(list); - list = list->next; - } - } - if (xmlNodeIsText(node)) - { - xmlChar *pContent = xmlNodeGetContent(node); - app += std::string((const char*)pContent); - xmlFree(pContent); - // std::cout << app << std::endl; - } - return app; -} - -void trim(std::string& str) -{ - std::string::size_type pos = str.find_last_not_of(' '); - if(pos != std::string::npos) - { - str.erase(pos + 1); - pos = str.find_first_not_of(' '); - if(pos != std::string::npos) - str.erase(0, pos); - } - else - str.erase(str.begin(), str.end()); -} - -void myparser::traverse( xmlNodePtr parentNode ) -{ - // traverse all nodes that belong to the parent - xmlNodePtr test ; - for (test = parentNode->xmlChildrenNode; test; test = test->next) - { - if (fileName.empty() && !strcmp((const char*)test->name, "filename")) - { - xmlNodePtr node = test->xmlChildrenNode; - if (xmlNodeIsText(node)) - { - xmlChar *pContent = xmlNodeGetContent(node); - fileName = std::string((const char*)pContent); - xmlFree(pContent); - } - } - else if (title.empty() && !strcmp((const char*)test->name, "title")) - { - title = dump(test); - if (title.empty()) - title = ""; - } - else if (!strcmp((const char*)test->name, "bookmark")) - { - xmlChar *branchxml = xmlGetProp(test, (const xmlChar*)"branch"); - xmlChar *idxml = xmlGetProp(test, (const xmlChar*)"id"); - std::string branch((const char*)branchxml); - std::string anchor((const char*)idxml); - xmlFree (branchxml); - xmlFree (idxml); - - std::string hid; - - if (branch.find("hid") == 0) - { - size_t index = branch.find('/'); - if (index != std::string::npos) - { - hid = branch.substr(1 + index); - // one shall serve as a documentId - if (documentId.empty()) - documentId = hid; - extendedHelpText.push_back(hid); - std::string foo = anchor.empty() ? hid : hid + "#" + anchor; - HCDBG(std::cerr << "hid pushback" << foo << std::endl); - hidlist->push_back( anchor.empty() ? hid : hid + "#" + anchor); - } - else - continue; - } - else if (branch.compare("index") == 0) - { - LinkedList ll; - - for (xmlNodePtr nd = test->xmlChildrenNode; nd; nd = nd->next) - { - if (strcmp((const char*)nd->name, "bookmark_value")) - continue; - - std::string embedded; - xmlChar *embeddedxml = xmlGetProp(nd, (const xmlChar*)"embedded"); - if (embeddedxml) - { - embedded = std::string((const char*)embeddedxml); - xmlFree (embeddedxml); - std::transform (embedded.begin(), embedded.end(), - embedded.begin(), tolower); - } - - bool isEmbedded = !embedded.empty() && embedded.compare("true") == 0; - if (isEmbedded) - continue; - - std::string keyword = dump(nd); - size_t keywordSem = keyword.find(';'); - if (keywordSem != std::string::npos) - { - std::string tmppre = - keyword.substr(0,keywordSem); - trim(tmppre); - std::string tmppos = - keyword.substr(1+keywordSem); - trim(tmppos); - keyword = tmppre + ";" + tmppos; - } - ll.push_back(keyword); - } - if (!ll.empty()) - (*keywords)[anchor] = ll; - } - else if (branch.compare("contents") == 0) - { - // currently not used - } - } - else if (!strcmp((const char*)test->name, "ahelp")) - { - std::string text = dump(test); - trim(text); - std::string name; - - HashSet::const_iterator aEnd = extendedHelpText.end(); - for (HashSet::const_iterator iter = extendedHelpText.begin(); iter != aEnd; - ++iter) - { - name = *iter; - (*helptexts)[name] = text; - } - extendedHelpText.clear(); - } - - // traverse children - traverse(test); - } -} - -bool HelpCompiler::compile( void ) throw( HelpProcessingException ) -{ - // we now have the jaroutputstream, which will contain the document. - // now determine the document as a dom tree in variable docResolved - - xmlDocPtr docResolvedOrg = getSourceDocument(inputFile); - - // now add path to the document - // resolve the dom - if (!docResolvedOrg) - { - impl_sleep( 3 ); - docResolvedOrg = getSourceDocument(inputFile); - if( !docResolvedOrg ) - { - std::stringstream aStrStream; - aStrStream << "ERROR: file not existing: " << inputFile.native_file_string().c_str() << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - } - - // now find all applications for which one has to compile - std::string documentId; - std::string fileName; - std::string title; - // returns all applications for which one has to compile - HashSet applications = switchFind(docResolvedOrg); - - HashSet::const_iterator aEnd = applications.end(); - for (HashSet::const_iterator aI = applications.begin(); aI != aEnd; ++aI) - { - std::string appl = *aI; - std::string modulename = appl; - if (modulename[0] == 'S') - { - modulename = modulename.substr(1); - std::transform(modulename.begin(), modulename.end(), modulename.begin(), tolower); - } - if (modulename != "DEFAULT" && modulename != module) - continue; - - // returns a clone of the document with swich-cases resolved - xmlNodePtr docResolved = clone(xmlDocGetRootElement(docResolvedOrg), appl); - myparser aparser(documentId, fileName, title); - aparser.traverse(docResolved); - - documentId = aparser.documentId; - fileName = aparser.fileName; - title = aparser.title; - - HCDBG(std::cerr << documentId << " : " << fileName << " : " << title << std::endl); - - xmlDocPtr docResolvedDoc = xmlCopyDoc(docResolvedOrg, false); - xmlDocSetRootElement(docResolvedDoc, docResolved); - - if (modulename == "DEFAULT") - { - streamTable.dropdefault(); - streamTable.default_doc = docResolvedDoc; - streamTable.default_hidlist = aparser.hidlist; - streamTable.default_helptexts = aparser.helptexts; - streamTable.default_keywords = aparser.keywords; - } - else if (modulename == module) - { - streamTable.dropappl(); - streamTable.appl_doc = docResolvedDoc; - streamTable.appl_hidlist = aparser.hidlist; - streamTable.appl_helptexts = aparser.helptexts; - streamTable.appl_keywords = aparser.keywords; - } - else - { - std::stringstream aStrStream; - aStrStream << "ERROR: Found unexpected module name \"" << modulename - << "\" in file" << src.native_file_string().c_str() << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - } // end iteration over all applications - - streamTable.document_id = documentId; - streamTable.document_path = fileName; - streamTable.document_title = title; - std::string actMod = module; - if ( !bExtensionMode && !fileName.empty()) - { - if (fileName.find("/text/") == 0) - { - int len = strlen("/text/"); - actMod = fileName.substr(len); - actMod = actMod.substr(0, actMod.find('/')); - } - } - streamTable.document_module = actMod; - - xmlFreeDoc(docResolvedOrg); - return true; -} - -namespace fs -{ - rtl_TextEncoding getThreadTextEncoding( void ) - { - static bool bNeedsInit = true; - static rtl_TextEncoding nThreadTextEncoding; - if( bNeedsInit ) - { - bNeedsInit = false; - nThreadTextEncoding = osl_getThreadTextEncoding(); - } - return nThreadTextEncoding; - } - - void create_directory(const fs::path indexDirName) - { - HCDBG( - std::cerr << "creating " << - rtl::OUStringToOString(indexDirName.data, RTL_TEXTENCODING_UTF8).getStr() - << std::endl - ); - osl::Directory::createPath(indexDirName.data); - } - - void rename(const fs::path &src, const fs::path &dest) - { - osl::File::move(src.data, dest.data); - } - - void copy(const fs::path &src, const fs::path &dest) - { - osl::File::copy(src.data, dest.data); - } - - bool exists(const fs::path &in) - { - osl::File tmp(in.data); - return (tmp.open(osl_File_OpenFlag_Read) == osl::FileBase::E_None); - } - - void remove(const fs::path &in) - { - osl::File::remove(in.data); - } - - void removeRecursive(rtl::OUString const& _suDirURL) - { - { - osl::Directory aDir(_suDirURL); - aDir.open(); - if (aDir.isOpen()) - { - osl::DirectoryItem aItem; - osl::FileStatus aStatus(osl_FileStatus_Mask_FileName | osl_FileStatus_Mask_Attributes); - while (aDir.getNextItem(aItem) == ::osl::FileBase::E_None) - { - if (osl::FileBase::E_None == aItem.getFileStatus(aStatus) && - aStatus.isValid(osl_FileStatus_Mask_FileName | osl_FileStatus_Mask_Attributes)) - { - rtl::OUString suFilename = aStatus.getFileName(); - rtl::OUString suFullFileURL; - suFullFileURL += _suDirURL; - suFullFileURL += rtl::OUString::createFromAscii("/"); - suFullFileURL += suFilename; - - if (aStatus.getFileType() == osl::FileStatus::Directory) - removeRecursive(suFullFileURL); - else - osl::File::remove(suFullFileURL); - } - } - aDir.close(); - } - } - osl::Directory::remove(_suDirURL); - } - - void remove_all(const fs::path &in) - { - removeRecursive(in.data); - } -} - -/* vi:set tabstop=4 shiftwidth=4 expandtab: */ diff --git a/transex3/source/help/HelpCompiler.hxx b/transex3/source/help/HelpCompiler.hxx deleted file mode 100644 index 7ffb096bd635..000000000000 --- a/transex3/source/help/HelpCompiler.hxx +++ /dev/null @@ -1,320 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: HelpCompiler.hxx,v $ - * $Revision: 1.8 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef HELPCOMPILER_HXX -#define HELPCOMPILER_HXX - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef SYSTEM_DB -#include -#else -#include -#endif - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#define EMULATEORIGINAL 1 - -#ifdef CMCDEBUG - #define HCDBG(foo) do { if (1) foo; } while(0) -#else - #define HCDBG(foo) do { if (0) foo; } while(0) -#endif - -namespace fs -{ - rtl_TextEncoding getThreadTextEncoding( void ); - - enum convert { native }; - class path - { - public: - ::rtl::OUString data; - public: - path() {} - path(const path &rOther) : data(rOther.data) {} - path(const std::string &in, convert) - { - rtl::OUString sWorkingDir; - osl_getProcessWorkingDir(&sWorkingDir.pData); - - rtl::OString tmp(in.c_str()); - rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); - osl::File::getFileURLFromSystemPath(ustrSystemPath, data); - osl::File::getAbsoluteFileURL(sWorkingDir, data, data); - } - path(const std::string &FileURL) - { - rtl::OString tmp(FileURL.c_str()); - data = rtl::OStringToOUString(tmp, getThreadTextEncoding()); - } - std::string native_file_string() const - { - ::rtl::OUString ustrSystemPath; - osl::File::getSystemPathFromFileURL(data, ustrSystemPath); - rtl::OString tmp(rtl::OUStringToOString(ustrSystemPath, getThreadTextEncoding())); - HCDBG(std::cerr << "native_file_string is " << tmp.getStr() << std::endl); - return std::string(tmp.getStr()); - } - std::string native_directory_string() const { return native_file_string(); } - std::string toUTF8() const - { - rtl::OString tmp(rtl::OUStringToOString(data, RTL_TEXTENCODING_UTF8)); - return std::string(tmp.getStr()); - } - bool empty() const { return data.getLength() == 0; } - path operator/(const std::string &in) const - { - path ret(*this); - HCDBG(std::cerr << "orig was " << - rtl::OUStringToOString(ret.data, RTL_TEXTENCODING_UTF8).getStr() << std::endl); - rtl::OString tmp(in.c_str()); - rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); - ret.data += rtl::OUString(sal_Unicode('/')); - ret.data += ustrSystemPath; - HCDBG(std::cerr << "final is " << - rtl::OUStringToOString(ret.data, RTL_TEXTENCODING_UTF8).getStr() << std::endl); - return ret; - } - void append(const char *in) - { - rtl::OString tmp(in); - rtl::OUString ustrSystemPath(rtl::OStringToOUString(tmp, getThreadTextEncoding())); - data = data + ustrSystemPath; - } - void append(const std::string &in) { append(in.c_str()); } - }; - - void create_directory(const fs::path indexDirName); - void rename(const fs::path &src, const fs::path &dest); - void copy(const fs::path &src, const fs::path &dest); - bool exists(const fs::path &in); - void remove_all(const fs::path &in); - void remove(const fs::path &in); -} - -struct joaat_hash -{ - size_t operator()(const std::string &str) const - { - size_t hash = 0; - const char *key = str.data(); - for (size_t i = 0; i < str.size(); i++) - { - hash += key[i]; - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } -}; - -#define get16bits(d) ((((sal_uInt32)(((const sal_uInt8 *)(d))[1])) << 8)\ - +(sal_uInt32)(((const sal_uInt8 *)(d))[0]) ) - -struct SuperFastHash -{ - size_t operator()(const std::string &str) const - { - const char * data = str.data(); - int len = str.size(); - size_t hash = len, tmp; - if (len <= 0 || data == NULL) return 0; - - int rem = len & 3; - len >>= 2; - - /* Main loop */ - for (;len > 0; len--) - { - hash += get16bits (data); - tmp = (get16bits (data+2) << 11) ^ hash; - hash = (hash << 16) ^ tmp; - data += 2*sizeof (sal_uInt16); - hash += hash >> 11; - } - - /* Handle end cases */ - switch (rem) - { - case 3: hash += get16bits (data); - hash ^= hash << 16; - hash ^= data[sizeof (sal_uInt16)] << 18; - hash += hash >> 11; - break; - case 2: hash += get16bits (data); - hash ^= hash << 11; - hash += hash >> 17; - break; - case 1: hash += *data; - hash ^= hash << 10; - hash += hash >> 1; - } - - /* Force "avalanching" of final 127 bits */ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - - return hash; - } -}; - -#define pref_hash joaat_hash - -typedef std::hash_map Stringtable; -typedef std::list LinkedList; -typedef std::vector HashSet; - -typedef std::hash_map Hashtable; - -class StreamTable -{ -public: - std::string document_id; - std::string document_path; - std::string document_module; - std::string document_title; - - HashSet *appl_hidlist; - Hashtable *appl_keywords; - Stringtable *appl_helptexts; - xmlDocPtr appl_doc; - - HashSet *default_hidlist; - Hashtable *default_keywords; - Stringtable *default_helptexts; - xmlDocPtr default_doc; - - StreamTable() : - appl_hidlist(NULL), appl_keywords(NULL), appl_helptexts(NULL), appl_doc(NULL), - default_hidlist(NULL), default_keywords(NULL), default_helptexts(NULL), default_doc(NULL) - {} - void dropdefault() - { - delete default_hidlist; - delete default_keywords; - delete default_helptexts; - if (default_doc) xmlFreeDoc(default_doc); - } - void dropappl() - { - delete appl_hidlist; - delete appl_keywords; - delete appl_helptexts; - if (appl_doc) xmlFreeDoc(appl_doc); - } - ~StreamTable() - { - dropappl(); - dropdefault(); - } -}; - -struct HelpProcessingException -{ - HelpProcessingErrorClass m_eErrorClass; - std::string m_aErrorMsg; - std::string m_aXMLParsingFile; - int m_nXMLParsingLine; - - HelpProcessingException( HelpProcessingErrorClass eErrorClass, const std::string& aErrorMsg ) - : m_eErrorClass( eErrorClass ) - , m_aErrorMsg( aErrorMsg ) - {} - HelpProcessingException( const std::string& aErrorMsg, const std::string& aXMLParsingFile, int nXMLParsingLine ) - : m_eErrorClass( HELPPROCESSING_XMLPARSING_ERROR ) - , m_aErrorMsg( aErrorMsg ) - , m_aXMLParsingFile( aXMLParsingFile ) - , m_nXMLParsingLine( nXMLParsingLine ) - {} -}; - -class HelpCompiler -{ -public: - HelpCompiler(StreamTable &streamTable, - const fs::path &in_inputFile, - const fs::path &in_src, - const fs::path &in_resEmbStylesheet, - const std::string &in_module, - const std::string &in_lang, - bool in_bExtensionMode); - bool compile( void ) throw (HelpProcessingException); - void addEntryToJarFile(const std::string &prefix, - const std::string &entryName, const std::string &bytesToAdd); - void addEntryToJarFile(const std::string &prefix, - const std::string &entryName, const HashSet &bytesToAdd); - void addEntryToJarFile(const std::string &prefix, - const std::string &entryName, const Stringtable &bytesToAdd); - void addEntryToJarFile(const std::string &prefix, - const std::string &entryName, const Hashtable &bytesToAdd); -private: - xmlDocPtr getSourceDocument(const fs::path &filePath); - HashSet switchFind(xmlDocPtr doc); - xmlNodePtr clone(xmlNodePtr node, const std::string& appl); - StreamTable &streamTable; - const fs::path inputFile, src; - const std::string module, lang; - const fs::path resEmbStylesheet; - bool bExtensionMode; -}; - -#endif - -/* vi:set tabstop=4 shiftwidth=4 expandtab: */ diff --git a/transex3/source/help/HelpFileDocument.java b/transex3/source/help/HelpFileDocument.java deleted file mode 100644 index 2212db27f251..000000000000 --- a/transex3/source/help/HelpFileDocument.java +++ /dev/null @@ -1,89 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: HelpFileDocument.java,v $ - * $Revision: 1.2 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.help; - -import java.io.File; -import java.io.Reader; -import java.io.FileInputStream; -import java.io.InputStreamReader; -//import java.io.FileReader; -import java.io.StringReader; - -import org.apache.lucene.document.Document; -import org.apache.lucene.document.Field; - -/** Lucene Document for help files */ -public class HelpFileDocument -{ - /** Creates reader for UTF-8 files - */ - private static Reader getReaderForFile( File aFile ) - throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException { - Reader aReader; - if( aFile != null ) { - FileInputStream fis = new FileInputStream( aFile ); - aReader = new InputStreamReader( fis, "UTF-8" ); - } - else { - aReader = new StringReader( "" ); - } - return aReader; - } - - /** Makes a document for a File. - */ - public static Document Document( String aModule, File aCaptionFile, File aContentFile ) - throws java.io.FileNotFoundException, java.io.UnsupportedEncodingException { - Document doc = new Document(); - - // Add the path of the file as a field named "path". Use a field that is - // indexed (i.e. searchable), but don't tokenize the field into words. - File aFile = aCaptionFile != null ? aCaptionFile : aContentFile; - if( aFile != null ) - { - String aPath = "#HLP#" + aModule + "/" + aFile.getName(); - doc.add(new Field("path", aPath, Field.Store.YES, Field.Index.UN_TOKENIZED)); - } - - // Add the caption of the file to a field named "caption". Specify a Reader, - // so that the text of the file is tokenized and indexed, but not stored. - doc.add( new Field( "caption", getReaderForFile( aCaptionFile ) ) ); - - // Add the contents of the file to a field named "content". Specify a Reader, - // so that the text of the file is tokenized and indexed, but not stored. - doc.add( new Field( "content", getReaderForFile( aContentFile ) ) ); - - // return the document - return doc; - } - - private HelpFileDocument() {} -} diff --git a/transex3/source/help/HelpIndexerTool.java b/transex3/source/help/HelpIndexerTool.java deleted file mode 100644 index 6bf22d1ac344..000000000000 --- a/transex3/source/help/HelpIndexerTool.java +++ /dev/null @@ -1,372 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: HelpIndexer.java,v $ - * $Revision: 1.21 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -package com.sun.star.help; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -import java.util.zip.CRC32; -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.analysis.cjk.CJKAnalyzer; -import org.apache.lucene.analysis.Analyzer; -import org.apache.lucene.index.IndexWriter; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Date; - -public class HelpIndexerTool -{ - public HelpIndexerTool() - { - } - - - /** - * @param args the command line arguments - */ - public static void main( String[] args ) - { - boolean bExtensionMode = false; - mainImpl( args, bExtensionMode ); - } - - public static void mainImpl( String[] args, boolean bExtensionMode ) - { - String aDirToZipStr = ""; - String aSrcDirStr = ""; - String aLanguageStr = ""; - String aModule = ""; - String aTargetZipFileStr = ""; - String aCfsName = ""; - - // Scan arguments - boolean bLang = false; - boolean bMod = false; - boolean bZipDir = false; - boolean bSrcDir = false; - boolean bOutput = false; - boolean bCfsName = false; - - int nArgCount = args.length; - for( int i = 0 ; i < nArgCount ; i++ ) - { - if( "-lang".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aLanguageStr = args[i + 1]; - bLang = true; - } - i++; - } - else if( "-mod".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aModule = args[i + 1]; - bMod = true; - } - i++; - } - else if( "-zipdir".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aDirToZipStr = args[i + 1]; - bZipDir = true; - } - i++; - } - else if( "-srcdir".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aSrcDirStr = args[i + 1]; - bSrcDir = true; - } - i++; - } - else if( "-o".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aTargetZipFileStr = args[i + 1]; - bOutput = true; - } - i++; - } - else if( "-checkcfsname".equals(args[i]) ) - { - if( i + 1 < nArgCount ) - { - aCfsName = args[i + 1] + ".cfs"; - bCfsName = true; - } - i++; - } - } - - if( !bLang || !bMod || !bZipDir || (!bOutput && !bExtensionMode) ) - { - if( bExtensionMode ) - return; - - System.out.println("Usage: HelpIndexer -lang ISOLangCode -mod HelpModule -zipdir TempZipDir -o OutputZipFile"); - System.exit( -1 ); - } - - String aIndexDirName = aModule + ".idxl"; - File aIndexDir = new File( aDirToZipStr + File.separator + aIndexDirName ); - if( !bSrcDir ) - aSrcDirStr = aDirToZipStr; - File aCaptionFilesDir = new File( aSrcDirStr + File.separator + "caption" ); - File aContentFilesDir = new File( aSrcDirStr + File.separator + "content" ); - - try - { - Date start = new Date(); - Analyzer analyzer = aLanguageStr.equals("ja") ? (Analyzer)new CJKAnalyzer() : (Analyzer)new StandardAnalyzer(); - IndexWriter writer = new IndexWriter( aIndexDir, analyzer, true ); - if( !bExtensionMode ) - System.out.println( "Lucene: Indexing to directory '" + aIndexDir + "'..." ); - int nRet = indexDocs( writer, aModule, bExtensionMode, aCaptionFilesDir, aContentFilesDir ); - if( nRet != -1 ) - { - if( !bExtensionMode ) - { - System.out.println(); - System.out.println( "Optimizing ..." ); - } - writer.optimize(); - } - writer.close(); - - boolean bCfsFileOk = true; - if( bCfsName && !bExtensionMode && nRet != -1 ) - { - String aCompleteCfsFileName = aDirToZipStr + File.separator + aIndexDirName + File.separator + aCfsName; - File aCfsFile = new File( aCompleteCfsFileName ); - bCfsFileOk = aCfsFile.exists(); - System.out.println( "Checking cfs file " + aCfsName+ ": " + (bCfsFileOk ? "Found" : "Not found") ); - } - - if( bExtensionMode ) - { - if( !bSrcDir ) - { - deleteRecursively( aCaptionFilesDir ); - deleteRecursively( aContentFilesDir ); - } - } - else - { - if( nRet == -1 ) - deleteRecursively( aIndexDir ); - - if( bCfsFileOk ) - System.out.println( "Zipping ..." ); - File aDirToZipFile = new File( aDirToZipStr ); - createZipFile( aDirToZipFile, aTargetZipFileStr ); - deleteRecursively( aDirToZipFile ); - } - - if( !bCfsFileOk ) - { - System.out.println( "cfs file check failed, terminating..." ); - System.exit( -1 ); - } - - Date end = new Date(); - if( !bExtensionMode ) - System.out.println(end.getTime() - start.getTime() + " total milliseconds"); - } - catch (IOException e) - { - if( bExtensionMode ) - return; - - System.out.println(" caught a " + e.getClass() + - "\n with message: " + e.getMessage()); - System.exit( -1 ); - } - } - - private static int indexDocs(IndexWriter writer, String aModule, boolean bExtensionMode, - File aCaptionFilesDir, File aContentFilesDir) throws IOException - { - if( !aCaptionFilesDir.canRead() || !aCaptionFilesDir.isDirectory() ) - { - if( !bExtensionMode ) - System.out.println( "Not found: " + aCaptionFilesDir ); - return -1; - } - if( !aContentFilesDir.canRead() || !aContentFilesDir.isDirectory() ) - { - if( !bExtensionMode ) - System.out.println( "Not found: " + aContentFilesDir ); - return -1; - } - - String[] aCaptionFiles = aCaptionFilesDir.list(); - List aCaptionFilesList = Arrays.asList( aCaptionFiles ); - HashSet aCaptionFilesHashSet = new HashSet( aCaptionFilesList ); - - String[] aContentFiles = aContentFilesDir.list(); - List aContentFilesList = Arrays.asList( aContentFiles ); - HashSet aContentFilesHashSet = new HashSet( aContentFilesList ); - - // Loop over caption files and find corresponding content file - if( !bExtensionMode ) - System.out.println( "Indexing, adding files" ); - int nCaptionFilesLen = aCaptionFiles.length; - for( int i = 0 ; i < nCaptionFilesLen ; i++ ) - { - String aCaptionFileStr = aCaptionFiles[i]; - File aCaptionFile = new File( aCaptionFilesDir, aCaptionFileStr ); - File aContentFile = null; - if( aContentFilesHashSet.contains( aCaptionFileStr ) ) - aContentFile = new File( aContentFilesDir, aCaptionFileStr ); - - if( !bExtensionMode ) - System.out.print( "." ); - writer.addDocument( HelpFileDocument.Document( aModule, aCaptionFile, aContentFile ) ); - } - - // Loop over content files to find remaining files not mapped to caption files - int nContentFilesLen = aContentFiles.length; - for( int i = 0 ; i < nContentFilesLen ; i++ ) - { - String aContentFileStr = aContentFiles[i]; - if( !aCaptionFilesHashSet.contains( aContentFileStr ) ) - { - // Not already handled in caption files loop - File aCaptionFile = null; - File aContentFile = new File( aContentFilesDir, aContentFileStr ); - if( !bExtensionMode ) - System.out.print( "." ); - writer.addDocument( HelpFileDocument.Document( aModule, aCaptionFile, aContentFile ) ); - } - } - return 0; - } - - public static void createZipFile( File aDirToZip, String aTargetZipFileStr ) - throws FileNotFoundException, IOException - { - FileOutputStream fos = new FileOutputStream( aTargetZipFileStr ); - ZipOutputStream zos = new ZipOutputStream( fos ); - - File[] aChildrenFiles = aDirToZip.listFiles(); - int nFileCount = aChildrenFiles.length; - for( int i = 0 ; i < nFileCount ; i++ ) - addToZipRecursively( zos, aChildrenFiles[i], null ); - - zos.close(); - } - - public static void addToZipRecursively( ZipOutputStream zos, File aFile, String aBasePath ) - throws FileNotFoundException, IOException - { - if( aFile.isDirectory() ) - { - String aDirName = aFile.getName(); - if( aDirName.equalsIgnoreCase( "caption" ) || aDirName.equalsIgnoreCase( "content" ) ) - return; - - File[] aChildrenFiles = aFile.listFiles(); - String aNewBasePath = ""; - if( aBasePath != null ) - aNewBasePath += aBasePath + File.separator; - aNewBasePath += aDirName; - - int nFileCount = aChildrenFiles.length; - for( int i = 0 ; i < nFileCount ; i++ ) - addToZipRecursively( zos, aChildrenFiles[i], aNewBasePath ); - - return; - } - - // No directory - // read contents of file we are going to put in the zip - int fileLength = (int) aFile.length(); - FileInputStream fis = new FileInputStream( aFile ); - byte[] wholeFile = new byte[fileLength]; - int bytesRead = fis.read( wholeFile, 0, fileLength ); - fis.close(); - - String aFileName = aFile.getName(); - String aEntryName = ""; - if( aBasePath != null ) - aEntryName += aBasePath + "/"; - aEntryName += aFileName; - ZipEntry aZipEntry = new ZipEntry( aEntryName ); - aZipEntry.setTime( aFile.lastModified() ); - aZipEntry.setSize( fileLength ); - - int nMethod = ( aFileName.toLowerCase().endsWith( ".jar" ) ) - ? ZipEntry.STORED : ZipEntry.DEFLATED; - aZipEntry.setMethod( nMethod ); - - CRC32 tempCRC = new CRC32(); - tempCRC.update( wholeFile, 0, wholeFile.length ); - aZipEntry.setCrc( tempCRC.getValue() ); - - // write the contents into the zip element - zos.putNextEntry( aZipEntry ); - zos.write( wholeFile, 0, fileLength ); - zos.closeEntry(); - } - - static public boolean deleteRecursively( File aFile ) - { - if( aFile.isDirectory() ) - { - File[] aChildrenFiles = aFile.listFiles(); - int nFileCount = aChildrenFiles.length; - for( int i = 0 ; i < nFileCount ; i++ ) - { - File aChildrenFile = aChildrenFiles[i]; - boolean bSuccess = deleteRecursively( aChildrenFile ); - if( !bSuccess ) - return false; - } - } - - return aFile.delete(); - } -} - diff --git a/transex3/source/help/HelpLinker.cxx b/transex3/source/help/HelpLinker.cxx deleted file mode 100644 index 7dfe4ee4a2a2..000000000000 --- a/transex3/source/help/HelpLinker.cxx +++ /dev/null @@ -1,1173 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: HelpLinker.cxx,v $ - * $Revision: 1.16 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#include "HelpCompiler.hxx" - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include - -#define DBHELP_ONLY - - -class IndexerPreProcessor -{ -private: - std::string m_aModuleName; - fs::path m_fsIndexBaseDir; - fs::path m_fsCaptionFilesDirName; - fs::path m_fsContentFilesDirName; - - xsltStylesheetPtr m_xsltStylesheetPtrCaption; - xsltStylesheetPtr m_xsltStylesheetPtrContent; - -public: - IndexerPreProcessor( const std::string& aModuleName, const fs::path& fsIndexBaseDir, - const fs::path& idxCaptionStylesheet, const fs::path& idxContentStylesheet ); - ~IndexerPreProcessor(); - - void processDocument( xmlDocPtr doc, const std::string& EncodedDocPath ); -}; - -IndexerPreProcessor::IndexerPreProcessor - ( const std::string& aModuleName, const fs::path& fsIndexBaseDir, - const fs::path& idxCaptionStylesheet, const fs::path& idxContentStylesheet ) - : m_aModuleName( aModuleName ) - , m_fsIndexBaseDir( fsIndexBaseDir ) -{ - m_fsCaptionFilesDirName = fsIndexBaseDir / "caption"; - fs::create_directory( m_fsCaptionFilesDirName ); - - m_fsContentFilesDirName = fsIndexBaseDir / "content"; - fs::create_directory( m_fsContentFilesDirName ); - - m_xsltStylesheetPtrCaption = xsltParseStylesheetFile - ((const xmlChar *)idxCaptionStylesheet.native_file_string().c_str()); - m_xsltStylesheetPtrContent = xsltParseStylesheetFile - ((const xmlChar *)idxContentStylesheet.native_file_string().c_str()); -} - -IndexerPreProcessor::~IndexerPreProcessor() -{ - if( m_xsltStylesheetPtrCaption ) - xsltFreeStylesheet( m_xsltStylesheetPtrCaption ); - if( m_xsltStylesheetPtrContent ) - xsltFreeStylesheet( m_xsltStylesheetPtrContent ); -} - - -std::string getEncodedPath( const std::string& Path ) -{ - rtl::OString aOStr_Path( Path.c_str() ); - rtl::OUString aOUStr_Path( rtl::OStringToOUString - ( aOStr_Path, fs::getThreadTextEncoding() ) ); - rtl::OUString aPathURL; - osl::File::getFileURLFromSystemPath( aOUStr_Path, aPathURL ); - rtl::OString aOStr_PathURL( rtl::OUStringToOString - ( aPathURL, fs::getThreadTextEncoding() ) ); - std::string aStdStr_PathURL( aOStr_PathURL.getStr() ); - return aStdStr_PathURL; -} - -void IndexerPreProcessor::processDocument - ( xmlDocPtr doc, const std::string &EncodedDocPath ) -{ - std::string aStdStr_EncodedDocPathURL = getEncodedPath( EncodedDocPath ); - - if( m_xsltStylesheetPtrCaption ) - { - xmlDocPtr resCaption = xsltApplyStylesheet( m_xsltStylesheetPtrCaption, doc, NULL ); - xmlNodePtr pResNodeCaption = resCaption->xmlChildrenNode; - if( pResNodeCaption ) - { - fs::path fsCaptionPureTextFile_docURL = m_fsCaptionFilesDirName / aStdStr_EncodedDocPathURL; - std::string aCaptionPureTextFileStr_docURL = fsCaptionPureTextFile_docURL.native_file_string(); - FILE* pFile_docURL = fopen( aCaptionPureTextFileStr_docURL.c_str(), "w" ); - if( pFile_docURL ) - { - fprintf( pFile_docURL, "%s\n", pResNodeCaption->content ); - fclose( pFile_docURL ); - } - } - xmlFreeDoc(resCaption); - } - - if( m_xsltStylesheetPtrContent ) - { - xmlDocPtr resContent = xsltApplyStylesheet( m_xsltStylesheetPtrContent, doc, NULL ); - xmlNodePtr pResNodeContent = resContent->xmlChildrenNode; - if( pResNodeContent ) - { - fs::path fsContentPureTextFile_docURL = m_fsContentFilesDirName / aStdStr_EncodedDocPathURL; - std::string aContentPureTextFileStr_docURL = fsContentPureTextFile_docURL.native_file_string(); - FILE* pFile_docURL = fopen( aContentPureTextFileStr_docURL.c_str(), "w" ); - if( pFile_docURL ) - { - fprintf( pFile_docURL, "%s\n", pResNodeContent->content ); - fclose( pFile_docURL ); - } - } - xmlFreeDoc(resContent); - } -} - -struct Data -{ - std::vector _idList; - typedef std::vector::const_iterator cIter; - - void append(const std::string &id) - { - _idList.push_back(id); - } - - std::string getString() const - { - std::string ret; - cIter aEnd = _idList.end(); - for (cIter aIter = _idList.begin(); aIter != aEnd; ++aIter) - ret += *aIter + ";"; - return ret; - } -}; - -void writeKeyValue_DBHelp( FILE* pFile, const std::string& aKeyStr, const std::string& aValueStr ) -{ - if( pFile == NULL ) - return; - char cLF = 10; - unsigned int nKeyLen = aKeyStr.length(); - unsigned int nValueLen = aValueStr.length(); - fprintf( pFile, "%x ", nKeyLen ); - if( nKeyLen > 0 ) - { - if (fwrite( aKeyStr.c_str(), 1, nKeyLen, pFile ) != nKeyLen) - fprintf(stderr, "fwrite to db failed\n"); - } - if (fprintf( pFile, " %x ", nValueLen ) < 0) - fprintf(stderr, "fwrite to db failed\n"); - if( nValueLen > 0 ) - { - if (fwrite( aValueStr.c_str(), 1, nValueLen, pFile ) != nValueLen) - fprintf(stderr, "fwrite to db failed\n"); - } - if (fprintf( pFile, "%c", cLF ) < 0) - fprintf(stderr, "fwrite to db failed\n"); -} - -class HelpKeyword -{ -private: - typedef std::hash_map DataHashtable; - DataHashtable _hash; - -public: - void insert(const std::string &key, const std::string &id) - { - Data &data = _hash[key]; - data.append(id); - } - - void dump(DB* table) - { - DataHashtable::const_iterator aEnd = _hash.end(); - for (DataHashtable::const_iterator aIter = _hash.begin(); aIter != aEnd; ++aIter) - { - const std::string &keystr = aIter->first; - DBT key; - memset(&key, 0, sizeof(key)); - key.data = const_cast(keystr.c_str()); - key.size = keystr.length(); - - const Data &data = aIter->second; - std::string str = data.getString(); - DBT value; - memset(&value, 0, sizeof(value)); - value.data = const_cast(str.c_str()); - value.size = str.length(); - - table->put(table, NULL, &key, &value, 0); - } - } - - void dump_DBHelp( const std::string& rFileName ) - { - FILE* pFile = fopen( rFileName.c_str(), "wb" ); - if( pFile == NULL ) - return; - - DataHashtable::const_iterator aEnd = _hash.end(); - for (DataHashtable::const_iterator aIter = _hash.begin(); aIter != aEnd; ++aIter) - writeKeyValue_DBHelp( pFile, aIter->first, aIter->second.getString() ); - - fclose( pFile ); - } -}; - -class HelpLinker -{ -public: - void main(std::vector &args, - std::string* pExtensionPath = NULL, const rtl::OUString* pOfficeHelpPath = NULL ) - throw( HelpProcessingException ); - - HelpLinker() - : init(true) - , m_pIndexerPreProcessor(NULL) - {} - ~HelpLinker() - { delete m_pIndexerPreProcessor; } - -private: - int locCount, totCount; - Stringtable additionalFiles; - HashSet helpFiles; - fs::path sourceRoot; - fs::path embeddStylesheet; - fs::path idxCaptionStylesheet; - fs::path idxContentStylesheet; - fs::path zipdir; - fs::path outputFile; - std::string module; - std::string lang; - std::string hid; - std::string extensionPath; - bool bExtensionMode; - fs::path indexDirName; - Stringtable hidlistTranslation; - fs::path indexDirParentName; - bool init; - IndexerPreProcessor* m_pIndexerPreProcessor; - void initIndexerPreProcessor(); - void link() throw( HelpProcessingException ); - void addBookmark( DB* dbBase, FILE* pFile_DBHelp, std::string thishid, - const std::string& fileB, const std::string& anchorB, - const std::string& jarfileB, const std::string& titleB ); -#if 0 - /** - * @param outputFile - * @param module - * @param lang - * @param hid - * @param helpFiles - * @param additionalFiles - */ - - private HelpURLStreamHandlerFactory urlHandler = null; -#endif -}; - -namespace URLEncoder -{ - static std::string encode(const std::string &rIn) - { - const char *good = "!$&'()*+,-.=@_"; - static const char hex[17] = "0123456789ABCDEF"; - - std::string result; - for (size_t i=0; i < rIn.length(); ++i) - { - unsigned char c = rIn[i]; - if (isalnum (c) || strchr (good, c)) - result += c; - else { - result += '%'; - result += hex[c >> 4]; - result += hex[c & 0xf]; - } - } - return result; - } -} - -void HelpLinker::addBookmark( DB* dbBase, FILE* pFile_DBHelp, std::string thishid, - const std::string& fileB, const std::string& anchorB, - const std::string& jarfileB, const std::string& titleB) -{ - HCDBG(std::cerr << "HelpLinker::addBookmark " << thishid << " " << - fileB << " " << anchorB << " " << jarfileB << " " << titleB << std::endl); - - std::string temp = thishid; - std::transform (temp.begin(), temp.end(), temp.begin(), toupper); - std::replace(temp.begin(), temp.end(), ':', '_'); - const std::string& translatedHid = hidlistTranslation[temp]; - if (!translatedHid.empty()) - thishid = translatedHid; - - thishid = URLEncoder::encode(thishid); - - DBT key; - memset(&key, 0, sizeof(key)); - key.data = const_cast(thishid.c_str()); - key.size = thishid.length(); - - int fileLen = fileB.length(); - if (!anchorB.empty()) - fileLen += (1 + anchorB.length()); - int dataLen = 1 + fileLen + 1 + jarfileB.length() + 1 + titleB.length(); - - std::vector dataB(dataLen); - size_t i = 0; - dataB[i++] = static_cast(fileLen); - for (size_t j = 0; j < fileB.length(); ++j) - dataB[i++] = fileB[j]; - if (!anchorB.empty()) - { - dataB[i++] = '#'; - for (size_t j = 0; j < anchorB.length(); ++j) - dataB[i++] = anchorB[j]; - } - dataB[i++] = static_cast(jarfileB.length()); - for (size_t j = 0; j < jarfileB.length(); ++j) - dataB[i++] = jarfileB[j]; - - dataB[i++] = static_cast(titleB.length()); - for (size_t j = 0; j < titleB.length(); ++j) - dataB[i++] = titleB[j]; - - DBT data; - memset(&data, 0, sizeof(data)); - data.data = &dataB[0]; - data.size = dataB.size(); - - if( dbBase != NULL ) - dbBase->put(dbBase, NULL, &key, &data, 0); - - if( pFile_DBHelp != NULL ) - { - std::string aValueStr( dataB.begin(), dataB.end() ); - writeKeyValue_DBHelp( pFile_DBHelp, thishid, aValueStr ); - } -} - -void HelpLinker::initIndexerPreProcessor() -{ - if( m_pIndexerPreProcessor ) - delete m_pIndexerPreProcessor; - std::string mod = module; - std::transform (mod.begin(), mod.end(), mod.begin(), tolower); - m_pIndexerPreProcessor = new IndexerPreProcessor( mod, indexDirParentName, - idxCaptionStylesheet, idxContentStylesheet ); -} - -/** -* -*/ -void HelpLinker::link() throw( HelpProcessingException ) -{ - bool bIndexForExtension = true; - - if( bExtensionMode ) - { - indexDirParentName = sourceRoot; - } - else - { - indexDirParentName = zipdir; - fs::create_directory(indexDirParentName); - } - -#ifdef CMC_DEBUG - std::cerr << "will not delete tmpdir of " << indexDirParentName.native_file_string().c_str() << std::endl; -#endif - - std::string mod = module; - std::transform (mod.begin(), mod.end(), mod.begin(), tolower); - - // do the work here - // continue with introduction of the overall process thing into the - // here all hzip files will be worked on - std::string appl = mod; - if (appl[0] == 's') - appl = appl.substr(1); - - bool bUse_ = true; -#ifdef DBHELP_ONLY - if( !bExtensionMode ) - bUse_ = false; -#endif - - DB* helpText(0); -#ifndef DBHELP_ONLY - fs::path helpTextFileName(indexDirParentName / (mod + ".ht")); - db_create(&helpText,0,0); - helpText->open(helpText, NULL, helpTextFileName.native_file_string().c_str(), NULL, DB_BTREE, - DB_CREATE | DB_TRUNCATE, 0644); -#endif - - fs::path helpTextFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".ht_" : ".ht"))); - FILE* pFileHelpText_DBHelp = fopen - ( helpTextFileName_DBHelp.native_file_string().c_str(), "wb" ); - - DB* dbBase(0); -#ifndef DBHELP_ONLY - fs::path dbBaseFileName(indexDirParentName / (mod + ".db")); - db_create(&dbBase,0,0); - dbBase->open(dbBase, NULL, dbBaseFileName.native_file_string().c_str(), NULL, DB_BTREE, - DB_CREATE | DB_TRUNCATE, 0644); -#endif - - fs::path dbBaseFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".db_" : ".db"))); - FILE* pFileDbBase_DBHelp = fopen - ( dbBaseFileName_DBHelp.native_file_string().c_str(), "wb" ); - -#ifndef DBHELP_ONLY - DB* keyWord(0); - fs::path keyWordFileName(indexDirParentName / (mod + ".key")); - db_create(&keyWord,0,0); - keyWord->open(keyWord, NULL, keyWordFileName.native_file_string().c_str(), NULL, DB_BTREE, - DB_CREATE | DB_TRUNCATE, 0644); -#endif - - fs::path keyWordFileName_DBHelp(indexDirParentName / (mod + (bUse_ ? ".key_" : ".key"))); - - HelpKeyword helpKeyword; - - // catch HelpProcessingException to avoid locking data bases - try - { - - std::ifstream fileReader(hid.c_str()); - while (fileReader) - { - std::string key; - fileReader >> key; - std::transform (key.begin(), key.end(), key.begin(), toupper); - std::replace(key.begin(), key.end(), ':', '_'); - std::string data; - fileReader >> data; - if (!key.empty() && !data.empty()) - hidlistTranslation[key] = data; - } - fileReader.close(); - - // lastly, initialize the indexBuilder - if ( (!bExtensionMode || bIndexForExtension) && !helpFiles.empty()) - initIndexerPreProcessor(); - - if( !bExtensionMode ) - { -#ifndef OS2 // YD @TODO@ crashes libc runtime :-( - std::cout << "Making " << outputFile.native_file_string() << - " from " << helpFiles.size() << " input files" << std::endl; -#endif - } - - // here we start our loop over the hzip files. - HashSet::iterator end = helpFiles.end(); - for (HashSet::iterator iter = helpFiles.begin(); iter != end; ++iter) - { - if( !bExtensionMode ) - { - std::cout << "."; - std::cout.flush(); - } - - // process one file - // streamTable contains the streams in the hzip file - StreamTable streamTable; - const std::string &xhpFileName = *iter; - - if (!bExtensionMode && xhpFileName.rfind(".xhp") != xhpFileName.length()-4) - { - // only work on .xhp - files - std::cerr << - "ERROR: input list entry '" - << xhpFileName - << "' has the wrong extension (only files with extension .xhp " - << "are accepted)"; - continue; - } - - fs::path langsourceRoot(sourceRoot); - fs::path xhpFile; - - if( bExtensionMode ) - { - // langsourceRoot == sourceRoot for extensions - std::string xhpFileNameComplete( extensionPath ); - xhpFileNameComplete.append( '/' + xhpFileName ); - xhpFile = fs::path( xhpFileNameComplete ); - } - else - { - langsourceRoot.append('/' + lang + '/'); - xhpFile = fs::path(xhpFileName, fs::native); - } - - HelpCompiler hc( streamTable, xhpFile, langsourceRoot, - embeddStylesheet, module, lang, bExtensionMode ); - - HCDBG(std::cerr << "before compile of " << xhpFileName << std::endl); - bool success = hc.compile(); - HCDBG(std::cerr << "after compile of " << xhpFileName << std::endl); - - if (!success && !bExtensionMode) - { - std::stringstream aStrStream; - aStrStream << - "\nERROR: compiling help particle '" - << xhpFileName - << "' for language '" - << lang - << "' failed!"; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - const std::string documentBaseId = streamTable.document_id; - std::string documentPath = streamTable.document_path; - if (documentPath.find("/") == 0) - documentPath = documentPath.substr(1); - - std::string documentJarfile = streamTable.document_module + ".jar"; - - std::string documentTitle = streamTable.document_title; - if (documentTitle.empty()) - documentTitle = ""; - -#if 0 - std::cout << "for " << xhpFileName << " documentBaseId is " << documentBaseId << "\n"; - std::cout << "for " << xhpFileName << " documentPath is " << documentPath << "\n"; - std::cout << "for " << xhpFileName << " documentJarfile is " << documentJarfile << "\n"; - std::cout << "for " << xhpFileName << " documentPath is " << documentTitle << "\n"; -#endif - - const std::string& fileB = documentPath; - const std::string& jarfileB = documentJarfile; - std::string& titleB = documentTitle; - - // add once this as its own id. - addBookmark(dbBase, pFileDbBase_DBHelp, documentPath, fileB, std::string(), jarfileB, titleB); - - // first the database *.db - // ByteArrayInputStream bais = null; - // ObjectInputStream ois = null; - - const HashSet *hidlist = streamTable.appl_hidlist; - if (!hidlist) - hidlist = streamTable.default_hidlist; - if (hidlist && !hidlist->empty()) - { - // now iterate over all elements of the hidlist - HashSet::const_iterator aEnd = hidlist->end(); - for (HashSet::const_iterator hidListIter = hidlist->begin(); - hidListIter != aEnd; ++hidListIter) - { - std::string thishid = *hidListIter; - - std::string anchorB; - size_t index = thishid.rfind('#'); - if (index != std::string::npos) - { - anchorB = thishid.substr(1 + index); - thishid = thishid.substr(0, index); - } - addBookmark(dbBase, pFileDbBase_DBHelp, thishid, fileB, anchorB, jarfileB, titleB); - } - } - - // now the keywords - const Hashtable *anchorToLL = streamTable.appl_keywords; - if (!anchorToLL) - anchorToLL = streamTable.default_keywords; - if (anchorToLL && !anchorToLL->empty()) - { - std::string fakedHid = URLEncoder::encode(documentPath); - Hashtable::const_iterator aEnd = anchorToLL->end(); - for (Hashtable::const_iterator enumer = anchorToLL->begin(); - enumer != aEnd; ++enumer) - { - const std::string &anchor = enumer->first; - addBookmark(dbBase, pFileDbBase_DBHelp, documentPath, fileB, - anchor, jarfileB, titleB); - std::string totalId = fakedHid + "#" + anchor; - // std::cerr << hzipFileName << std::endl; - const LinkedList& ll = enumer->second; - LinkedList::const_iterator aOtherEnd = ll.end(); - for (LinkedList::const_iterator llIter = ll.begin(); - llIter != aOtherEnd; ++llIter) - { - helpKeyword.insert(*llIter, totalId); - } - } - - } - - // and last the helptexts - const Stringtable *helpTextHash = streamTable.appl_helptexts; - if (!helpTextHash) - helpTextHash = streamTable.default_helptexts; - if (helpTextHash && !helpTextHash->empty()) - { - Stringtable::const_iterator aEnd = helpTextHash->end(); - for (Stringtable::const_iterator helpTextIter = helpTextHash->begin(); - helpTextIter != aEnd; ++helpTextIter) - { - std::string helpTextId = helpTextIter->first; - const std::string& helpTextText = helpTextIter->second; - - std::string temp = helpTextId; - std::transform (temp.begin(), temp.end(), temp.begin(), toupper); - std::replace(temp.begin(), temp.end(), ':', '_'); - - const std::string& tHid = hidlistTranslation[temp]; - if (!tHid.empty()) - helpTextId = tHid; - helpTextId = URLEncoder::encode(helpTextId); - - DBT keyDbt; - memset(&keyDbt, 0, sizeof(keyDbt)); - keyDbt.data = const_cast(helpTextId.c_str()); - keyDbt.size = helpTextId.length(); - - DBT textDbt; - memset(&textDbt, 0, sizeof(textDbt)); - textDbt.data = const_cast(helpTextText.c_str()); - textDbt.size = helpTextText.length(); - - if( helpText != NULL ) - helpText->put(helpText, NULL, &keyDbt, &textDbt, 0); - - if( pFileHelpText_DBHelp != NULL ) - writeKeyValue_DBHelp( pFileHelpText_DBHelp, helpTextId, helpTextText ); - } - } - - //IndexerPreProcessor - if( !bExtensionMode || bIndexForExtension ) - { - // now the indexing - xmlDocPtr document = streamTable.appl_doc; - if (!document) - document = streamTable.default_doc; - if (document) - { - std::string temp = module; - std::transform (temp.begin(), temp.end(), temp.begin(), tolower); - m_pIndexerPreProcessor->processDocument(document, URLEncoder::encode(documentPath) ); - } - } - - } // while loop over hzip files ending - if( !bExtensionMode ) - std::cout << std::endl; - - } // try - catch( HelpProcessingException& ) - { - // catch HelpProcessingException to avoid locking data bases -#ifndef DBHELP_ONLY - helpText->close(helpText, 0); - dbBase->close(dbBase, 0); - keyWord->close(keyWord, 0); -#endif - if( pFileHelpText_DBHelp != NULL ) - fclose( pFileHelpText_DBHelp ); - if( pFileDbBase_DBHelp != NULL ) - fclose( pFileDbBase_DBHelp ); - throw; - } - -#ifndef DBHELP_ONLY - helpText->close(helpText, 0); - dbBase->close(dbBase, 0); - helpKeyword.dump(keyWord); - keyWord->close(keyWord, 0); -#endif - if( pFileHelpText_DBHelp != NULL ) - fclose( pFileHelpText_DBHelp ); - if( pFileDbBase_DBHelp != NULL ) - fclose( pFileDbBase_DBHelp ); - - helpKeyword.dump_DBHelp( keyWordFileName_DBHelp.native_file_string() ); - - if( !bExtensionMode ) - { - // New index - Stringtable::iterator aEnd = additionalFiles.end(); - for (Stringtable::iterator enumer = additionalFiles.begin(); enumer != aEnd; - ++enumer) - { - const std::string &additionalFileName = enumer->second; - const std::string &additionalFileKey = enumer->first; - - fs::path fsAdditionalFileName( additionalFileName, fs::native ); - std::string aNativeStr = fsAdditionalFileName.native_file_string(); - const char* pStr = aNativeStr.c_str(); - std::cerr << pStr; - - fs::path fsTargetName( indexDirParentName / additionalFileKey ); - - fs::copy( fsAdditionalFileName, fsTargetName ); - } - } - -/* - ///////////////////////////////////////////////////////////////////////// - /// remove temprary directory for index creation - ///////////////////////////////////////////////////////////////////////// -#ifndef CMC_DEBUG - if( !bExtensionMode ) - fs::remove_all( indexDirParentName ); -#endif -*/ -} - - -void HelpLinker::main( std::vector &args, - std::string* pExtensionPath, const rtl::OUString* pOfficeHelpPath ) - throw( HelpProcessingException ) -{ - rtl::OUString aOfficeHelpPath; - - bExtensionMode = false; - if( pExtensionPath && pExtensionPath->length() > 0 && pOfficeHelpPath ) - { - helpFiles.clear(); - bExtensionMode = true; - extensionPath = *pExtensionPath; - sourceRoot = fs::path(extensionPath); - - aOfficeHelpPath = *pOfficeHelpPath; - } - if (args.size() > 0 && args[0][0] == '@') - { - std::vector stringList; - std::string strBuf; - std::ifstream fileReader(args[0].substr(1).c_str()); - - while (fileReader) - { - std::string token; - fileReader >> token; - if (!token.empty()) - stringList.push_back(token); - } - fileReader.close(); - - args = stringList; - } - - size_t i = 0; - - while (i < args.size()) - { - if (args[i].compare("-src") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "sourceroot missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - if( !bExtensionMode ) - sourceRoot = fs::path(args[i], fs::native); - } - else if (args[i].compare("-sty") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "embeddingStylesheet missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - embeddStylesheet = fs::path(args[i], fs::native); - } - else if (args[i].compare("-zipdir") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "idxtemp missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - zipdir = fs::path(args[i], fs::native); - } - else if (args[i].compare("-idxcaption") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "idxcaption stylesheet missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - idxCaptionStylesheet = fs::path(args[i], fs::native); - } - else if (args[i].compare("-idxcontent") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "idxcontent stylesheet missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - idxContentStylesheet = fs::path(args[i], fs::native); - } - else if (args[i].compare("-o") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "outputfilename missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - outputFile = fs::path(args[i], fs::native); - } - else if (args[i].compare("-mod") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "module name missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - module = args[i]; - } - else if (args[i].compare("-lang") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "language name missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - lang = args[i]; - } - else if (args[i].compare("-hid") == 0) - { - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "hid list missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - hid = args[i]; - } - else if (args[i].compare("-add") == 0) - { - std::string addFile, addFileUnderPath; - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "pathname missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - addFileUnderPath = args[i]; - ++i; - if (i >= args.size()) - { - std::stringstream aStrStream; - aStrStream << "pathname missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - addFile = args[i]; - if (!addFileUnderPath.empty() && !addFile.empty()) - additionalFiles[addFileUnderPath] = addFile; - } - else - helpFiles.push_back(args[i]); - ++i; - } - - if (!bExtensionMode && zipdir.empty()) - { - std::stringstream aStrStream; - aStrStream << "no index dir given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (!bExtensionMode && idxCaptionStylesheet.empty()) - { - std::stringstream aStrStream; - aStrStream << "no index caption stylesheet given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - else if ( bExtensionMode ) - { - rtl::OUString aIdxCaptionPathFileURL( aOfficeHelpPath ); - aIdxCaptionPathFileURL += rtl::OUString::createFromAscii( "/idxcaption.xsl" ); - - rtl::OString aOStr_IdxCaptionPathFileURL( rtl::OUStringToOString - ( aIdxCaptionPathFileURL, fs::getThreadTextEncoding() ) ); - std::string aStdStr_IdxCaptionPathFileURL( aOStr_IdxCaptionPathFileURL.getStr() ); - - idxCaptionStylesheet = fs::path( aStdStr_IdxCaptionPathFileURL ); - } - if (!bExtensionMode && idxContentStylesheet.empty()) - { - std::stringstream aStrStream; - aStrStream << "no index content stylesheet given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - else if ( bExtensionMode ) - { - rtl::OUString aIdxContentPathFileURL( aOfficeHelpPath ); - aIdxContentPathFileURL += rtl::OUString::createFromAscii( "/idxcontent.xsl" ); - - rtl::OString aOStr_IdxContentPathFileURL( rtl::OUStringToOString - ( aIdxContentPathFileURL, fs::getThreadTextEncoding() ) ); - std::string aStdStr_IdxContentPathFileURL( aOStr_IdxContentPathFileURL.getStr() ); - - idxContentStylesheet = fs::path( aStdStr_IdxContentPathFileURL ); - } - if (!bExtensionMode && embeddStylesheet.empty()) - { - std::stringstream aStrStream; - aStrStream << "no embedding resolving file given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (sourceRoot.empty()) - { - std::stringstream aStrStream; - aStrStream << "no sourceroot given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (!bExtensionMode && outputFile.empty()) - { - std::stringstream aStrStream; - aStrStream << "no output file given" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (module.empty()) - { - std::stringstream aStrStream; - aStrStream << "module missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (!bExtensionMode && lang.empty()) - { - std::stringstream aStrStream; - aStrStream << "language missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - if (!bExtensionMode && hid.empty()) - { - std::stringstream aStrStream; - aStrStream << "hid list missing" << std::endl; - throw HelpProcessingException( HELPPROCESSING_GENERAL_ERROR, aStrStream.str() ); - } - - link(); -} - -int main(int argc, char**argv) -{ - sal_uInt32 starttime = osl_getGlobalTimer(); - std::vector args; - for (int i = 1; i < argc; ++i) - args.push_back(std::string(argv[i])); - try - { - HelpLinker* pHelpLinker = new HelpLinker(); - pHelpLinker->main( args ); - delete pHelpLinker; - } - catch( const HelpProcessingException& e ) - { - std::cerr << e.m_aErrorMsg; - exit(1); - } - sal_uInt32 endtime = osl_getGlobalTimer(); -#ifndef OS2 // YD @TODO@ crashes libc runtime :-( - std::cout << "time taken was " << (endtime-starttime)/1000.0 << " seconds" << std::endl; -#endif - return 0; -} - -// Variable to set an exception in "C" StructuredXMLErrorFunction -static const HelpProcessingException* GpXMLParsingException = NULL; - -extern "C" void StructuredXMLErrorFunction(void *userData, xmlErrorPtr error) -{ - (void)userData; - (void)error; - - std::string aErrorMsg = error->message; - std::string aXMLParsingFile; - if( error->file != NULL ) - aXMLParsingFile = error->file; - int nXMLParsingLine = error->line; - HelpProcessingException* pException = new HelpProcessingException( aErrorMsg, aXMLParsingFile, nXMLParsingLine ); - GpXMLParsingException = pException; - - // Reset error handler - xmlSetStructuredErrorFunc( NULL, NULL ); -} - -HelpProcessingErrorInfo& HelpProcessingErrorInfo::operator=( const struct HelpProcessingException& e ) -{ - m_eErrorClass = e.m_eErrorClass; - rtl::OString tmpErrorMsg( e.m_aErrorMsg.c_str() ); - m_aErrorMsg = rtl::OStringToOUString( tmpErrorMsg, fs::getThreadTextEncoding() ); - rtl::OString tmpXMLParsingFile( e.m_aXMLParsingFile.c_str() ); - m_aXMLParsingFile = rtl::OStringToOUString( tmpXMLParsingFile, fs::getThreadTextEncoding() ); - m_nXMLParsingLine = e.m_nXMLParsingLine; - return *this; -} - - -// Returns true in case of success, false in case of error -HELPLINKER_DLLPUBLIC bool compileExtensionHelp -( - const rtl::OUString& aOfficeHelpPath, - const rtl::OUString& aExtensionName, - const rtl::OUString& aExtensionLanguageRoot, - sal_Int32 nXhpFileCount, const rtl::OUString* pXhpFiles, - HelpProcessingErrorInfo& o_rHelpProcessingErrorInfo -) -{ - bool bSuccess = true; - - sal_Int32 argc = nXhpFileCount + 3; - const char** argv = new const char*[argc]; - argv[0] = ""; - argv[1] = "-mod"; - rtl::OString aOExtensionName = rtl::OUStringToOString( aExtensionName, fs::getThreadTextEncoding() ); - argv[2] = aOExtensionName.getStr(); - - for( sal_Int32 iXhp = 0 ; iXhp < nXhpFileCount ; ++iXhp ) - { - rtl::OUString aXhpFile = pXhpFiles[iXhp]; - - rtl::OString aOXhpFile = rtl::OUStringToOString( aXhpFile, fs::getThreadTextEncoding() ); - char* pArgStr = new char[aOXhpFile.getLength() + 1]; - strcpy( pArgStr, aOXhpFile.getStr() ); - argv[iXhp + 3] = pArgStr; - } - - std::vector args; - for( sal_Int32 i = 1; i < argc; ++i ) - args.push_back(std::string( argv[i]) ); - - for( sal_Int32 iXhp = 0 ; iXhp < nXhpFileCount ; ++iXhp ) - delete argv[iXhp + 3]; - delete[] argv; - - rtl::OString aOExtensionLanguageRoot = rtl::OUStringToOString( aExtensionLanguageRoot, fs::getThreadTextEncoding() ); - const char* pExtensionPath = aOExtensionLanguageRoot.getStr(); - std::string aStdStrExtensionPath = pExtensionPath; - - // Set error handler - xmlSetStructuredErrorFunc( NULL, (xmlStructuredErrorFunc)StructuredXMLErrorFunction ); - try - { - HelpLinker* pHelpLinker = new HelpLinker(); - pHelpLinker->main( args, &aStdStrExtensionPath, &aOfficeHelpPath ); - delete pHelpLinker; - } - catch( const HelpProcessingException& e ) - { - if( GpXMLParsingException != NULL ) - { - o_rHelpProcessingErrorInfo = *GpXMLParsingException; - delete GpXMLParsingException; - GpXMLParsingException = NULL; - } - else - { - o_rHelpProcessingErrorInfo = e; - } - bSuccess = false; - } - // Reset error handler - xmlSetStructuredErrorFunc( NULL, NULL ); - - // i83624: Tree files - ::rtl::OUString aTreeFileURL = aExtensionLanguageRoot; - aTreeFileURL += rtl::OUString::createFromAscii( "/help.tree" ); - osl::DirectoryItem aTreeFileItem; - osl::FileBase::RC rcGet = osl::DirectoryItem::get( aTreeFileURL, aTreeFileItem ); - osl::FileStatus aFileStatus( FileStatusMask_FileSize ); - if( rcGet == osl::FileBase::E_None && - aTreeFileItem.getFileStatus( aFileStatus ) == osl::FileBase::E_None && - aFileStatus.isValid( FileStatusMask_FileSize ) ) - { - sal_uInt64 ret, len = aFileStatus.getFileSize(); - char* s = new char[ int(len) ]; // the buffer to hold the installed files - osl::File aFile( aTreeFileURL ); - aFile.open( OpenFlag_Read ); - aFile.read( s, len, ret ); - aFile.close(); - - XML_Parser parser = XML_ParserCreate( 0 ); - int parsed = XML_Parse( parser, s, int( len ), true ); - - if( parsed == 0 ) - { - XML_Error nError = XML_GetErrorCode( parser ); - o_rHelpProcessingErrorInfo.m_eErrorClass = HELPPROCESSING_XMLPARSING_ERROR; - o_rHelpProcessingErrorInfo.m_aErrorMsg = rtl::OUString::createFromAscii( XML_ErrorString( nError ) );; - o_rHelpProcessingErrorInfo.m_aXMLParsingFile = aTreeFileURL; - // CRAHSES!!! o_rHelpProcessingErrorInfo.m_nXMLParsingLine = XML_GetCurrentLineNumber( parser ); - bSuccess = false; - } - - XML_ParserFree( parser ); - delete[] s; - } - - return bSuccess; -} - -// vnd.sun.star.help://swriter/52821?Language=en-US&System=UNIX -/* vi:set tabstop=4 shiftwidth=4 expandtab: */ - diff --git a/transex3/source/help/compilehelp.hxx b/transex3/source/help/compilehelp.hxx deleted file mode 100644 index d123d628be27..000000000000 --- a/transex3/source/help/compilehelp.hxx +++ /dev/null @@ -1,81 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: compilehelp.hxx,v $ - * $Revision: 1.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -#ifndef COMPILE_HXX -#define COMPILE_HXX - -#include "sal/types.h" - -#if defined(HELPLINKER_DLLIMPLEMENTATION) -#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_EXPORT -#else -#define HELPLINKER_DLLPUBLIC SAL_DLLPUBLIC_IMPORT -#endif -#define HELPLINKER_DLLPRIVATE SAL_DLLPRIVATE - - -//#include -#include - -enum HelpProcessingErrorClass -{ - HELPPROCESSING_NO_ERROR, - HELPPROCESSING_GENERAL_ERROR, // Missing files, options etc. - HELPPROCESSING_INTERNAL_ERROR, // Unexpected problems - HELPPROCESSING_XMLPARSING_ERROR // Errors thrown by libxml -}; - -struct HelpProcessingErrorInfo -{ - HelpProcessingErrorClass m_eErrorClass; - rtl::OUString m_aErrorMsg; - rtl::OUString m_aXMLParsingFile; - sal_Int32 m_nXMLParsingLine; - - HelpProcessingErrorInfo( void ) - : m_eErrorClass( HELPPROCESSING_NO_ERROR ) - , m_nXMLParsingLine( -1 ) - {} - - HelpProcessingErrorInfo& operator=( const struct HelpProcessingException& e ); -}; - - -// Returns true in case of success, false in case of error -HELPLINKER_DLLPUBLIC bool compileExtensionHelp -( - const rtl::OUString& aOfficeHelpPath, - const rtl::OUString& aExtensionName, - const rtl::OUString& aExtensionLanguageRoot, - sal_Int32 nXhpFileCount, const rtl::OUString* pXhpFiles, - HelpProcessingErrorInfo& o_rHelpProcessingErrorInfo -); - -#endif diff --git a/transex3/source/help/helplinker.pmk b/transex3/source/help/helplinker.pmk deleted file mode 100644 index 569c5f4dbdee..000000000000 --- a/transex3/source/help/helplinker.pmk +++ /dev/null @@ -1,35 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: helplinker.pmk,v $ -# -# $Revision: 1.4 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -# define HELPLINKER_DLLIMPLEMENTATION (see @ inc/xmlhelp/helplinkerdllapi.h) -CDEFS += -DHELPLINKER_DLLIMPLEMENTATION - -VISIBILITY_HIDDEN=TRUE diff --git a/transex3/source/help/makefile.mk b/transex3/source/help/makefile.mk deleted file mode 100644 index 6fc823a1b59a..000000000000 --- a/transex3/source/help/makefile.mk +++ /dev/null @@ -1,120 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.38 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ = ..$/.. -PRJNAME = xmlhelp -TARGET = HelpLinker -LIBBASENAME = helplinker -PACKAGE = com$/sun$/star$/help -TARGETTYPE=CUI - -# --- Settings ----------------------------------------------------- - -.INCLUDE : settings.mk -.INCLUDE : helplinker.pmk - -.IF "$(SYSTEM_LIBXSLT)" == "YES" -CFLAGS+= $(LIBXSLT_CFLAGS) -.ELSE -LIBXSLTINCDIR=external$/libxslt -CFLAGS+= -I$(SOLARINCDIR)$/$(LIBXSLTINCDIR) -.ENDIF - -.IF "$(SYSTEM_DB)" == "YES" -CFLAGS+=-DSYSTEM_DB -I$(DB_INCLUDES) -.ENDIF - -.IF "$(SYSTEM_EXPAT)" == "YES" -CFLAGS+=-DSYSTEM_EXPAT -.ENDIF - -OBJFILES=\ - $(OBJ)$/HelpLinker.obj \ - $(OBJ)$/HelpCompiler.obj -SLOFILES=\ - $(SLO)$/HelpLinker.obj \ - $(SLO)$/HelpCompiler.obj - -EXCEPTIONSFILES=\ - $(OBJ)$/HelpLinker.obj \ - $(OBJ)$/HelpCompiler.obj \ - $(SLO)$/HelpLinker.obj \ - $(SLO)$/HelpCompiler.obj -.IF "$(OS)" == "MACOSX" && "$(CPU)" == "P" && "$(COM)" == "GCC" -# There appears to be a GCC 4.0.1 optimization error causing _file:good() to -# report true right before the call to writeOut at HelpLinker.cxx:1.12 l. 954 -# but out.good() to report false right at the start of writeOut at -# HelpLinker.cxx:1.12 l. 537: -NOOPTFILES=\ - $(OBJ)$/HelpLinker.obj \ - $(SLO)$/HelpLinker.obj -.ENDIF - -APP1TARGET= $(TARGET) -APP1OBJS=\ - $(OBJ)$/HelpLinker.obj \ - $(OBJ)$/HelpCompiler.obj - -APP1STDLIBS+=$(SALLIB) $(BERKELEYLIB) $(XSLTLIB) $(EXPATASCII3RDLIB) - -SHL1TARGET =$(LIBBASENAME)$(DLLPOSTFIX) -SHL1LIBS= $(SLB)$/$(TARGET).lib -SHL1IMPLIB =i$(LIBBASENAME) -SHL1DEF =$(MISC)$/$(SHL1TARGET).def -SHL1STDLIBS =$(SALLIB) $(BERKELEYLIB) $(XSLTLIB) $(EXPATASCII3RDLIB) -SHL1USE_EXPORTS =ordinal - -DEF1NAME =$(SHL1TARGET) -DEFLIB1NAME =$(TARGET) - -JAVAFILES = \ - HelpIndexerTool.java \ - HelpFileDocument.java - - -JAVACLASSFILES = \ - $(CLASSDIR)$/$(PACKAGE)$/HelpIndexerTool.class \ - $(CLASSDIR)$/$(PACKAGE)$/HelpFileDocument.class - -.IF "$(SYSTEM_LUCENE)" == "YES" -CLASSPATH!:=$(CLASSPATH)$(PATH_SEPERATOR)$(LUCENE_CORE_JAR)$(PATH_SEPERATOR)$(LUCENE_ANALYZERS_JAR) -.ELSE -JARFILES += lucene-core-2.3.jar lucene-analyzers-2.3.jar -.ENDIF -JAVAFILES = $(subst,$(CLASSDIR)$/$(PACKAGE)$/, $(subst,.class,.java $(JAVACLASSFILES))) - -JARCLASSDIRS = $(PACKAGE)/* -JARTARGET = HelpIndexerTool.jar -JARCOMPRESS = TRUE - -# --- Targets ------------------------------------------------------ - -.INCLUDE : target.mk diff --git a/transex3/source/helpex.cxx b/transex3/source/helpex.cxx deleted file mode 100644 index f4a1589b530e..000000000000 --- a/transex3/source/helpex.cxx +++ /dev/null @@ -1,299 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: helpex.cxx,v $ - * $Revision: 1.14 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include - -// local includes -#include "helpmerge.hxx" - -// defines to parse command line -#define STATE_NON 0x0001 -#define STATE_INPUT 0x0002 -#define STATE_OUTPUT 0x0003 -#define STATE_PRJ 0x0004 -#define STATE_ROOT 0x0005 -#define STATE_SDFFILE 0x0006 -#define STATE_ERRORLOG 0x0007 -#define STATE_BREAKHELP 0x0008 -#define STATE_UNMERGE 0x0009 -#define STATE_UTF8 0x000A -#define STATE_LANGUAGES 0x000B -#define STATE_FORCE_LANGUAGES 0x000C -#define STATE_OUTPUTX 0xfe -#define STATE_OUTPUTY 0xff - -// set of global variables -ByteString sInputFile; -BOOL bEnableExport; -BOOL bMergeMode; -BOOL bErrorLog; -BOOL bUTF8; -ByteString sPrj; -ByteString sPrjRoot; -ByteString sOutputFile; -ByteString sOutputFileX; -ByteString sOutputFileY; -ByteString sSDFFile; -bool bQuiet; - -/*****************************************************************************/ -BOOL ParseCommandLine( int argc, char* argv[]) -/*****************************************************************************/ -{ - bEnableExport = FALSE; - bMergeMode = FALSE; - bErrorLog = TRUE; - bUTF8 = TRUE; - sPrj = ""; - sPrjRoot = ""; - bQuiet = false; - Export::sLanguages = ""; - Export::sForcedLanguages = ""; - - USHORT nState = STATE_NON; - BOOL bInput = FALSE; - - // parse command line - for( int i = 1; i < argc; i++ ) { - if ( ByteString( argv[ i ]).ToUpperAscii() == "-I" ) { - nState = STATE_INPUT; // next tokens specifies source files - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-O" ) { - nState = STATE_OUTPUT; // next token specifies the dest file - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-X" ) { - nState = STATE_OUTPUTX; // next token specifies the dest file - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-Y" ) { - nState = STATE_OUTPUTY; // next token specifies the dest file - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-P" ) { - nState = STATE_PRJ; // next token specifies the cur. project - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-LF" ) { - nState = STATE_FORCE_LANGUAGES; - } - - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-R" ) { - nState = STATE_ROOT; // next token specifies path to project root - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-M" ) { - nState = STATE_SDFFILE; // next token specifies the merge database - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-E" ) { - nState = STATE_ERRORLOG; - bErrorLog = FALSE; - } - else if ( ByteString( argv[ i ] ).ToUpperAscii() == "-QQ" ) { - bQuiet = true; - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-UTF8" ) { - nState = STATE_UTF8; - bUTF8 = TRUE; - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-NOUTF8" ) { - nState = STATE_UTF8; - bUTF8 = FALSE; - } - else if ( ByteString( argv[ i ]).ToUpperAscii() == "-L" ) { - nState = STATE_LANGUAGES; - } - else { - switch ( nState ) { - case STATE_NON: { - return FALSE; // no valid command line - } - //break; - case STATE_INPUT: { - sInputFile = argv[ i ]; - bInput = TRUE; // source file found - } - break; - case STATE_OUTPUT: { - sOutputFile = argv[ i ]; // the dest. file - } - break; - case STATE_OUTPUTX: { - sOutputFileX = argv[ i ]; // the dest. file - } - break; - case STATE_OUTPUTY: { - sOutputFileY = argv[ i ]; // the dest. file - } - break; - case STATE_PRJ: { - sPrj = argv[ i ]; -// sPrj.ToLowerAscii(); // the project - } - break; - case STATE_ROOT: { - sPrjRoot = argv[ i ]; // path to project root - } - break; - case STATE_SDFFILE: { - sSDFFile = argv[ i ]; - bMergeMode = TRUE; // activate merge mode, cause merge database found - } - break; - case STATE_LANGUAGES: { - Export::sLanguages = argv[ i ]; - } - case STATE_FORCE_LANGUAGES:{ - Export::sForcedLanguages = argv[ i ]; - } - break; - } - } - } - - if ( bInput ) { - // command line is valid - bEnableExport = TRUE; - return TRUE; - } - - // command line is not valid - return FALSE; -} - - -/*****************************************************************************/ -void Help() -/*****************************************************************************/ -{ - fprintf( stdout, "Syntax: HELPEX[-p Prj][-r PrjRoot]-i FileIn ( -o FileOut | -x path -y relfile )[-m DataBase][-e][-b][-u][-L l1,l2,...][-QQ] -LF l1,l2 \n" ); - fprintf( stdout, " Prj: Project\n" ); - fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); - fprintf( stdout, " FileIn: Source file (*.lng)\n" ); - fprintf( stdout, " FileOut: Destination file (*.*)\n" ); - fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); - fprintf( stdout, " -QQ: quiet output\n" ); - fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (en-US,fr,de...)\n" ); - fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); - fprintf( stdout, " f1, f2,... are also elements of (en-US,fr,de...)\n" ); - fprintf( stdout, " Example: -L fr=en-US\n" ); - fprintf( stdout, " Restriction to fr, en-US will be fallback for fr\n" ); - fprintf( stdout, " -LF: Force the creation of that languages\n" ); - -} - -/*****************************************************************************/ -#ifndef TESTDRIVER - -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - - if ( !ParseCommandLine( argc, argv )) { - Help(); - return 1; - } - //sal_uInt32 startfull = Export::startMessure(); - - bool hasInputList = sInputFile.GetBuffer()[0]=='@'; -// printf("x = %s , y = %s , o = %s\n", sOutputFileX.GetBuffer(), sOutputFileY.GetBuffer() , sOutputFile.GetBuffer() ); - bool hasNoError = true; - - if ( sOutputFile.Len() ){ // Merge single file ? - //printf("DBG: Inputfile = %s\n",sInputFile.GetBuffer()); - HelpParser aParser( sInputFile, bUTF8 , false ); - - if ( bMergeMode ) - { - - //sal_uInt64 startreadloc = Export::startMessure(); - MergeDataFile aMergeDataFile( sSDFFile, sInputFile , FALSE, RTL_TEXTENCODING_MS_1252 ); - //MergeDataFile aMergeDataFile( sSDFFile, sInputFile , FALSE, RTL_TEXTENCODING_MS_1252, false ); - //Export::stopMessure( ByteString("read localize.sdf") , startreadloc ); - - hasNoError = aParser.Merge( sSDFFile, sOutputFile , Export::sLanguages , aMergeDataFile ); - } - else - hasNoError = aParser.CreateSDF( sOutputFile, sPrj, sPrjRoot, sInputFile, new XMLFile( '0' ), "help" ); - }else if ( sOutputFileX.Len() && sOutputFileY.Len() && hasInputList ) { // Merge multiple files ? - if ( bMergeMode ){ - - ifstream aFStream( sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() , ios::in ); - - if( !aFStream ){ - cerr << "ERROR: - helpex - Can't open the file " << sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() << "\n"; - exit(-1); - } - - vector filelist; - rtl::OStringBuffer filename; - sal_Char aChar; - while( aFStream.get( aChar ) ) - { - if( aChar == ' ' || aChar == '\n') - filelist.push_back( ByteString( filename.makeStringAndClear().getStr() ) ); - else - filename.append( aChar ); - } - if( filename.getLength() > 0 ) - filelist.push_back( ByteString ( filename.makeStringAndClear().getStr() ) ); - - aFStream.close(); - ByteString sHelpFile(""); // dummy - //MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , FALSE, RTL_TEXTENCODING_MS_1252, false ); - MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , FALSE, RTL_TEXTENCODING_MS_1252 ); - - //aMergeDataFile.Dump(); - std::vector aLanguages; - HelpParser::parse_languages( aLanguages , aMergeDataFile ); - - bool bCreateDir = true; - for( vector::iterator pos = filelist.begin() ; pos != filelist.end() ; ++pos ) - { - sHelpFile = *pos; - cout << ".";cout.flush(); - - HelpParser aParser( sHelpFile , bUTF8 , true ); - hasNoError = aParser.Merge( sSDFFile , sOutputFileX , sOutputFileY , true , aLanguages , aMergeDataFile , bCreateDir ); - bCreateDir = false; - } - } - } else - cerr << "helpex ERROR: Wrong input parameters!\n"; - - //Export::stopMessure( ByteString("full cycle") , startfull ); - if( hasNoError ) - return 0; - else - return 1; -} -#endif diff --git a/transex3/source/helpmerge.cxx b/transex3/source/helpmerge.cxx deleted file mode 100644 index 8aafc692f14c..000000000000 --- a/transex3/source/helpmerge.cxx +++ /dev/null @@ -1,730 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: helpmerge.cxx,v $ - * $Revision: 1.24 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -// local includes -#include -#include -#include "helpmerge.hxx" -#include "utf8conv.hxx" -#include -#include -#include -#include -#include -#include -#include "rtl/strbuf.hxx" -#ifdef WNT -#include -//#include -#include "tools/prewin.h" -#include -#include "tools/postwin.h" -#endif - -/*****************************************************************************/ -void HelpParser::FillInFallbacks( LangHashMap& rElem_out, ByteString sLangIdx_in ){ -/*****************************************************************************/ - static const ByteString ENGLISH_LANGUAGECODE( "en-US" ); - static const ByteString GERMAN_LANGUAGECODE ( "de" ); - ByteString sCur; - XMLElement* pTmp = NULL; - XMLElement* pTmp2 = NULL; - - sCur = sLangIdx_in; - ByteString sFallback( sCur ); - GetIsoFallback( sFallback ); - if( (rElem_out.find( sFallback ) != rElem_out.end()) && rElem_out[ sFallback ] != NULL ){ - pTmp2 = rElem_out[ sFallback ]; - pTmp = new XMLElement( *pTmp2 ) ; // Copy - pTmp->SetPos( pTmp2->GetPos()+1 ); - pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US) ); - rElem_out[ sLangIdx_in ] = pTmp; - pTmp2 = NULL; - } - else if( (rElem_out.find( ENGLISH_LANGUAGECODE ) != rElem_out.end()) && rElem_out[ ENGLISH_LANGUAGECODE ] != NULL ){// No English - pTmp2 = rElem_out[ ENGLISH_LANGUAGECODE ]; - pTmp = new XMLElement( *pTmp2 ) ; // Copy - pTmp->SetPos( pTmp2->GetPos()+1 ); - pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US) ); - rElem_out[ sCur ] = pTmp; - pTmp2 = NULL; - } - else if( (rElem_out.find( GERMAN_LANGUAGECODE ) != rElem_out.end() ) && rElem_out[ GERMAN_LANGUAGECODE ] != NULL ){// No English - pTmp2 = rElem_out[ GERMAN_LANGUAGECODE ]; - pTmp = new XMLElement( *pTmp2 ); // Copy - pTmp->SetPos( pTmp2->GetPos()+1 ); - pTmp->ChangeLanguageTag( String( sLangIdx_in , RTL_TEXTENCODING_ASCII_US ) ); - rElem_out[ sCur ] = pTmp; - pTmp2 = NULL; - }else{ - fprintf(stdout,"ERROR: No Fallback found for language %s:\n",sCur.GetBuffer()); - rElem_out[ sCur ]=new XMLElement(); // Use dummy element - } -} - -/*****************************************************************************/ -void HelpParser::Dump(XMLHashMap* rElem_in) { -/*****************************************************************************/ - for(XMLHashMap::iterator pos = rElem_in->begin();pos != rElem_in->end(); ++pos){ - Dump(pos->second,pos->first); - } -} -/*****************************************************************************/ -void HelpParser::Dump(LangHashMap* rElem_in,const ByteString sKey_in) { -/*****************************************************************************/ - ByteString x; - OString y; - fprintf(stdout,"+------------%s-----------+\n",sKey_in.GetBuffer() ); - for(LangHashMap::iterator posn=rElem_in->begin();posn!=rElem_in->end();++posn){ - x=posn->first; - y=posn->second->ToOString(); - fprintf(stdout,"key=%s value=%s\n",x.GetBuffer(),y.getStr()); - } - fprintf(stdout,"+--------------------------+\n"); -} - -HelpParser::HelpParser( const ByteString &rHelpFile, bool rUTF8 , bool rHasInputList ) - : sHelpFile( rHelpFile ), - bUTF8 ( rUTF8 ), - bHasInputList( rHasInputList ) - {}; - -/*****************************************************************************/ -bool HelpParser::CreateSDF( -/*****************************************************************************/ - const ByteString &rSDFFile_in, const ByteString &rPrj_in,const ByteString &rRoot_in, - const ByteString &sHelpFile, XMLFile *pXmlFile, const ByteString &rGsi1){ - // GSI File constants - static const String GSI_SEQUENCE1( String::CreateFromAscii("\t0\t") ); - static const String GSI_SEQUENCE2( String::CreateFromAscii("\t\t\t0\t") ); - static const String GSI_TAB ( String::CreateFromAscii("\t") ); - static const String GSI_SEQUENCE4( String::CreateFromAscii("\t\t\t\t") ); - static const String ret ( String::CreateFromAscii("\n") ); - static const String ret_char ( String::CreateFromAscii("") ); - static const String tab ( String::CreateFromAscii("\t") ); - static const String tab_char ( String::CreateFromAscii("") ); - - SimpleXMLParser aParser; - String sUsedTempFile; - String sXmlFile; - - if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ){ - DirEntry aTempFile = Export::GetTempFile(); - DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); - aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); - String sTempFile = aTempFile.GetFull(); - Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); - sUsedTempFile = sTempFile; - sXmlFile = sTempFile; - }else{ - sUsedTempFile = String::CreateFromAscii(""); - sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); - } - -// ByteString fullFilePath; - //DirEntry aFile( sXmlFile ); - //makeAbsolutePath( sHelpFile , rRoot_in); - ByteString fullFilePath = rPrj_in; - fullFilePath.Append( "\\" ); - fullFilePath.Append( makeAbsolutePath( sHelpFile , rRoot_in ) ); - fullFilePath.SearchAndReplaceAll( "\\", "/" ); - - String strFullPath( fullFilePath.GetBuffer() , RTL_TEXTENCODING_ASCII_US ); - - //printf( "%s\n", fullFilePath.GetBuffer() ); - std::auto_ptr file ( aParser.Execute( strFullPath , sXmlFile, pXmlFile ) ); - - if(file.get() == NULL){ - printf("%s\n",ByteString(aParser.GetError().sMessage,RTL_TEXTENCODING_ASCII_US).GetBuffer()); - exit(-1); - //return false; - } - file->Extract(); - if( !file->CheckExportStatus() ){ - return true; - } - SvFileStream aSDFStream( String( rSDFFile_in, RTL_TEXTENCODING_ASCII_US ), - STREAM_STD_WRITE | STREAM_TRUNC ); - - if ( !aSDFStream.IsOpen()) { - fprintf(stdout,"Can't open file %s\n",rSDFFile_in.GetBuffer()); - return false; - } - - ByteString sActFileName = makeAbsolutePath( sHelpFile , rRoot_in ); - -/* DirEntry aEntry( String( sHelpFile, RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - String sFullEntry = aEntry.GetFull(); - aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( rRoot_in ); - ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); - ByteString sActFileName( - sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); - - sActFileName.SearchAndReplaceAll( "/", "\\" ); -*/ - XMLHashMap* aXMLStrHM = file->GetStrings(); - LangHashMap* pElem; - XMLElement* pXMLElement = NULL; - - //Dump(aXMLStrHM); - - ByteString sTimeStamp( Export::GetTimeStamp() ); - OUString sOUTimeStamp( sTimeStamp.GetBuffer() , sTimeStamp.Len() , RTL_TEXTENCODING_ASCII_US ); - - OUStringBuffer sBuffer; - const OUString sOUPrj( rPrj_in.GetBuffer() , rPrj_in.Len() , RTL_TEXTENCODING_ASCII_US ); - const OUString sOUActFileName(sActFileName.GetBuffer() , sActFileName.Len() , RTL_TEXTENCODING_ASCII_US ); - const OUString sOUGsi1( rGsi1.GetBuffer() , rGsi1.Len() , RTL_TEXTENCODING_ASCII_US ); - - Export::InitLanguages( false ); - std::vector aLanguages = Export::GetLanguages(); - - std::vector order = file->getOrder(); - std::vector::iterator pos; - XMLHashMap::iterator posm; - - for( pos = order.begin(); pos != order.end() ; ++pos ) - { - posm = aXMLStrHM->find( *pos ); - pElem = posm->second; - ByteString sCur; - - for( unsigned int n = 0; n < aLanguages.size(); n++ ) - { - sCur = aLanguages[ n ]; - if(pElem->find( sCur )==pElem->end()) - { - FillInFallbacks( *pElem , sCur ); - } - pXMLElement = (*pElem)[ sCur ]; - - if( pXMLElement != NULL ) - { - OUString data = pXMLElement->ToOUString(); - String sTmp = String(data.getStr()); - sTmp.SearchAndReplaceAll(ret,ret_char); // Remove \n - sTmp.SearchAndReplaceAll(tab,tab_char); // Remove \t - - data = OUString( sTmp ); - sBuffer.append( sOUPrj ); - sBuffer.append( GSI_TAB ); //"\t"; - if ( rRoot_in.Len()) - sBuffer.append( sOUActFileName ); - sBuffer.append( GSI_SEQUENCE1 ); //"\t0\t"; - sBuffer.append( sOUGsi1 ); //"help"; - sBuffer.append( GSI_TAB ); //"\t"; - ByteString sID = posm->first; // ID - sBuffer.append( OUString( sID.GetBuffer() , sID.Len() , RTL_TEXTENCODING_UTF8 ) ); - sBuffer.append( GSI_TAB ); //"\t"; - ByteString sOldRef = pXMLElement->GetOldref(); // oldref - sBuffer.append( OUString(sOldRef.GetBuffer() , sOldRef.Len() , RTL_TEXTENCODING_UTF8 ) ); - sBuffer.append( GSI_SEQUENCE2 ); //"\t\t\t0\t"; - sBuffer.append( OUString( sCur.GetBuffer() , sCur.Len() , RTL_TEXTENCODING_UTF8 ) ); - sBuffer.append( GSI_TAB ); //"\t"; - sBuffer.append( data ); - sBuffer.append( GSI_SEQUENCE4 ); //"\t\t\t\t"; - sBuffer.append( sOUTimeStamp ); - ByteString sOut( sBuffer.makeStringAndClear().getStr() , RTL_TEXTENCODING_UTF8 ); - //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( rPrj_in ) ) ) - //{ - if( data.getLength() > 0 ) aSDFStream.WriteLine( sOut ); - //} - pXMLElement=NULL; - }else fprintf(stdout,"\nDBG: NullPointer in HelpParser::CreateSDF , Language %s\n",sCur.GetBuffer() ); - } - - } - //Dump(aXMLStrHM); - aSDFStream.Close(); - - if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ - DirEntry aTempFile( sUsedTempFile ); - aTempFile.Kill(); - } - return TRUE; -} - -ByteString HelpParser::makeAbsolutePath( const ByteString& sHelpFile , const ByteString& rRoot_in ) -{ - DirEntry aEntry( String( sHelpFile, RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - String sFullEntry = aEntry.GetFull(); - aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( rRoot_in ); - ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); - ByteString sActFileName( - sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); - - sActFileName.SearchAndReplaceAll( "/", "\\" ); - return sActFileName; -} -bool HelpParser::Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile , - ByteString& sLanguage , MergeDataFile& aMergeDataFile ) -{ - - (void) rSDFFile; - bool hasNoError = true; - - SimpleXMLParser aParser; - - String sUsedTempFile; - String sXmlFile; - - if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ){ - DirEntry aTempFile = Export::GetTempFile(); - DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); - aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); - String sTempFile = aTempFile.GetFull(); - Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); - sUsedTempFile = sTempFile; - sXmlFile = sTempFile; - }else{ - sUsedTempFile = String::CreateFromAscii(""); - sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); - } - - OUString sOUHelpFile( sXmlFile ); - String fullFilePath; - DirEntry aFile( sXmlFile ); - - XMLFile* xmlfile = ( aParser.Execute( aFile.GetFull() , sOUHelpFile, new XMLFile( '0' ) ) ); - printf("Dest file %s\n",rDestinationFile.GetBuffer()); - hasNoError = MergeSingleFile( xmlfile , aMergeDataFile , sLanguage , rDestinationFile ); - delete xmlfile; - if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ){ - DirEntry aTempFile( sUsedTempFile ); - aTempFile.Kill(); - } - return hasNoError; -} - -bool ByteStringEqual( const ByteString& rKey1, const ByteString& rKey2 ) { - return rKey1.CompareTo( rKey2 )==COMPARE_EQUAL; -}; -bool ByteStringLess( const ByteString& rKey1, const ByteString& rKey2 ) { - return rKey1.CompareTo( rKey2 )==COMPARE_LESS; -} - -void HelpParser::parse_languages( std::vector& aLanguages , MergeDataFile& aMergeDataFile ){ - std::vector aTmp; - - const ByteString DE ("de"); - const ByteString ENUS ("en-US"); - static const ByteString ALL( "ALL" ); - - Export::InitLanguages( false ); - - if( Export::sLanguages.EqualsIgnoreCaseAscii( ALL ) ) - { - aLanguages = aMergeDataFile.GetLanguages(); - aLanguages.push_back( DE ); - aLanguages.push_back( ENUS ); - - if( !Export::sForcedLanguages.Equals("") ) - { - std::vector aFL = Export::GetForcedLanguages(); - std::copy( aFL.begin() , - aFL.end() , - back_inserter( aLanguages ) - ); - std::sort( aLanguages.begin() , aLanguages.end() , ByteStringLess ); - std::vector::iterator unique_iter = std::unique( aLanguages.begin() , aLanguages.end() , ByteStringEqual ); - std::copy( aLanguages.begin() , unique_iter , back_inserter( aTmp ) ); - aLanguages = aTmp; - } - } - else{ - aLanguages = Export::GetLanguages(); - } - -} - -bool HelpParser::Merge( - const ByteString &rSDFFile, const ByteString &rPathX , const ByteString &rPathY , bool bISO , - const std::vector& aLanguages , MergeDataFile& aMergeDataFile , bool bCreateDir ) -{ - - - (void) rSDFFile ; - bool hasNoError = true; - SimpleXMLParser aParser; - String sUsedTempFile; - String sXmlFile; - - if( Export::fileHasUTF8ByteOrderMarker( sHelpFile ) ) - { - DirEntry aTempFile = Export::GetTempFile(); - DirEntry aSourceFile( String( sHelpFile , RTL_TEXTENCODING_ASCII_US ) ); - aSourceFile.CopyTo( aTempFile , FSYS_ACTION_COPYFILE ); - String sTempFile = aTempFile.GetFull(); - Export::RemoveUTF8ByteOrderMarkerFromFile( ByteString( sTempFile , RTL_TEXTENCODING_ASCII_US ) ); - sUsedTempFile = sTempFile; - sXmlFile = sTempFile; - } - else - { - sUsedTempFile = String::CreateFromAscii(""); - sXmlFile = String( sHelpFile , RTL_TEXTENCODING_ASCII_US ); - } - - - OUString sOUHelpFile( sXmlFile ); - String fullFilePath; - DirEntry aFile( sXmlFile ); - - XMLFile* xmlfile = ( aParser.Execute( aFile.GetFull() , sOUHelpFile, new XMLFile( '0' ) ) ); - xmlfile->Extract(); - - if( xmlfile == NULL) - { - printf("%s\n",ByteString(aParser.GetError().sMessage,RTL_TEXTENCODING_UTF8).GetBuffer()); - exit(-1); - //return false; - } - - - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - ByteString sFilepath; - if( bISO ) sFilepath = GetOutpath( rPathX , sCur , rPathY ); - else sFilepath = rPathX; - if( bCreateDir ) MakeDir( sFilepath ); - - XMLFile* file = new XMLFile( *xmlfile ); - sFilepath.Append( sHelpFile ); - hasNoError = MergeSingleFile( file , aMergeDataFile , sCur , sFilepath ); - delete file; - - if( !hasNoError ) return false; // Stop on error - } - - if( !sUsedTempFile.EqualsIgnoreCaseAscii( "" ) ) - { - DirEntry aTempFile( sUsedTempFile ); - aTempFile.Kill(); - } - delete xmlfile; - return hasNoError; -} - -bool HelpParser::MergeSingleFile( XMLFile* file , MergeDataFile& aMergeDataFile , const ByteString& sLanguage , - ByteString sPath ) -{ - file->Extract(); - - XMLHashMap* aXMLStrHM = file->GetStrings(); - LangHashMap* aLangHM; - static ResData pResData( "","",""); - pResData.sResTyp = "help"; - - ByteString sTmp = Export::sLanguages; - - sTmp.EraseLeadingAndTrailingChars(); - - for(XMLHashMap::iterator pos=aXMLStrHM->begin();pos!=aXMLStrHM->end();++pos) // Merge every l10n related string - { - - aLangHM = pos->second; - //printf("*********************DUMPING HASHMAP***************************************"); - //Dump( aXMLStrHM ); - //printf("DBG: sHelpFile = %s\n",sHelpFile.GetBuffer() ); - - pResData.sGId = pos->first; - pResData.sFilename = sHelpFile; - - ProcessHelp( aLangHM , sLanguage, &pResData , aMergeDataFile ); - } - - - // Init temp and target file - ByteString sTempFile; - ByteString sTargetFile( sPath ); - ByteString sTempFileCopy; - - static const ByteString INPATH = Export::GetEnv( "INPATH" ); - Export::getRandomName( sPath , sTempFile , INPATH ); - Export::getRandomName( sPath , sTempFileCopy , INPATH ); - // Write in the temp file - bool hasNoError = file->Write ( sTempFile ); - if( !hasNoError ) - { - cerr << "ERROR: file->Write failed\n"; - return false; - } - - DirEntry aTmp( sTempFile ); - DirEntry aTmp2( sTempFileCopy ); - DirEntry aTar( sTargetFile ); - - if( !Export::CopyFile( sTempFile , sTempFileCopy ) ) - { -#if defined(UNX) || defined(OS2) - sleep( 3 ); -#else - Sleep( 3 ); -#endif - if( !Export::CopyFile( sTempFile , sTempFileCopy ) ) - { - cerr << "ERROR: Can not copy file from " << sTempFile.GetBuffer() << " to " << sTempFileCopy.GetBuffer() << "\n"; - return false; - } - } - //remove( sTargetFile.GetBuffer() ); - - FileStat aFSTest( aTar ); - if( aFSTest.GetSize() < 1 ) - { - remove( sTargetFile.GetBuffer() ); - } - int rc; -#if defined(UNX) || defined(OS2) - rc = rename( sTempFile.GetBuffer() , sTargetFile.GetBuffer() ); -#else - rc = MoveFileEx( sTempFile.GetBuffer() , sTargetFile.GetBuffer(), MOVEFILE_REPLACE_EXISTING ); -#endif - FileStat aFS( aTar ); - - //cout << "mv " << sTempFile.GetBuffer() << " " << sTargetFile.GetBuffer() << "\n"; - //cout << "rc -> " << rc << " filesize -> " << aFS.GetSize() << "\n"; -// Windows rename returns -1 if the file already exits -//#ifdef UNX - if( rc < 0 || aFS.GetSize() < 1 ) -//#else -// if( aFS.GetSize() < 1 ) -//#endif - { -#if defined(UNX) || defined(OS2) - sleep( 3 ); -#else - Sleep( 3 ); -#endif - aFSTest.Update( aTar ); - if( aFSTest.GetSize() < 1 ) - { - remove( sTargetFile.GetBuffer() ); - } -#if defined(UNX) || defined(OS2) - rc = rename( sTempFileCopy.GetBuffer() , sTargetFile.GetBuffer() ); -#else - rc = MoveFileEx( sTempFileCopy.GetBuffer() , sTargetFile.GetBuffer() , MOVEFILE_REPLACE_EXISTING ); -#endif - aFS.Update( aTar ); - - //cout << "mv2 " << sTempFileCopy.GetBuffer() << " " << sTargetFile.GetBuffer() << "\n"; - //cout << "rc -> " << rc << " filesize -> " << aFS.GetSize() << "\n"; - -// Windows rename returns -1 if the file already exits -//#ifdef WNT -// if( aFS.GetSize() < 1 ) -//#else - if( rc < 0 || aFS.GetSize() < 1 ) -//#endif - { - cerr << "ERROR: helpex Can't rename file " << sTempFileCopy.GetBuffer() << " to " << sTargetFile.GetBuffer() << " rename rc=" << rc << " filesize=" << aFS.GetSize() << "\n"; - aTmp.Kill(); - aTmp2.Kill(); - if( aFS.GetSize() < 1 ) - aTar.Kill(); - return false; - } - } - aTmp.Kill(); - aTmp2.Kill(); - - return true; -} - -ByteString HelpParser::GetOutpath( const ByteString& rPathX , const ByteString& sCur , const ByteString& rPathY ){ - ByteString testpath = rPathX; - static const ByteString sDelimiter( DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - testpath.EraseTrailingChars( '/' ); - testpath.EraseTrailingChars( '\\' ); - testpath += sDelimiter; - testpath += sCur; - testpath += sDelimiter; - ByteString sRelativePath( rPathY ); - sRelativePath.EraseLeadingChars( '/' ); - sRelativePath.EraseLeadingChars( '\\' ); - testpath += sRelativePath; - testpath += sDelimiter; - return testpath; -} -void HelpParser::MakeDir( const ByteString& sPath ){ - ByteString sTPath( sPath ); - ByteString sDelimiter( DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - sTPath.SearchAndReplaceAll( sDelimiter , '/' ); - USHORT cnt = sTPath.GetTokenCount( '/' ); - ByteString sCreateDir; - for( USHORT i = 0 ; i < cnt ; i++ ) - { - sCreateDir += sTPath.GetToken( i , '/' ); - sCreateDir += sDelimiter; -#ifdef WNT - _mkdir( sCreateDir.GetBuffer() ); -#else - mkdir( sCreateDir.GetBuffer() , S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ); -#endif - } -} - - -/* ProcessHelp Methode: search for en-US entry and replace it with the current language*/ -void HelpParser::ProcessHelp( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ){ - - XMLElement* pXMLElement = NULL; - PFormEntrys *pEntrys = NULL; - XMLData *data = NULL; - XMLParentNode *parent = NULL; - - String sNewdata; - ByteString sLId; - ByteString sGId; - - pEntrys = NULL; - -#ifdef MERGE_SOURCE_LANGUAGES - if( true ){ // Merge en-US! -#else - if( !sCur.EqualsIgnoreCaseAscii("en-US") ){ -#endif - pXMLElement = (*aLangHM)[ "en-US" ]; - if( pXMLElement == NULL ) - { - printf("Error: Can't find en-US entry\n"); - } - if( pXMLElement != NULL ) - { - parent = pXMLElement->GetParent(); - sLId = pXMLElement->GetOldref(); - pResData->sId = sLId; - - pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); - if( pEntrys != NULL) - { - ByteString sNewText; - pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur , true ); - sNewdata = String( sNewText , RTL_TEXTENCODING_UTF8 ); - if ( sNewdata.Len()) - { - if( pXMLElement != NULL ) - { - data = new XMLData( sNewdata , NULL , true ); // Add new one - pXMLElement->RemoveAndDeleteAllChilds(); - pXMLElement->AddChild( data ); - aLangHM->erase( sCur ); - } - } - }else if( pResData == NULL ){fprintf(stdout,"Can't find GID=%s LID=%s TYP=%s\n",pResData->sGId.GetBuffer(),pResData->sId.GetBuffer(),pResData->sResTyp.GetBuffer());} - pXMLElement->ChangeLanguageTag( String( sCur , RTL_TEXTENCODING_ASCII_US) ); - } - - } -} -/* Process() Method merges */ -void HelpParser::Process( LangHashMap* aLangHM , const ByteString& sCur , ResData *pResData , MergeDataFile& aMergeDataFile ){ - - XMLElement* pXMLElement = NULL; - PFormEntrys *pEntrys = NULL; - XMLData *data = NULL; - XMLParentNode *parent = NULL; - XMLDefault *xmldefault = NULL; - - short curLang = 0; - String sNewdata; - bool isFallback = false; - ByteString sLId; - ByteString sGId; - - pEntrys = NULL; - -#ifdef MERGE_SOURCE_LANGUAGES - if( true ){ // Merge en-US! -#else - if( !sCur.EqualsIgnoreCaseAscii("en-US") ){ -#endif - pXMLElement = (*aLangHM)[ sCur ]; - if( pXMLElement == NULL ) - { - FillInFallbacks( *aLangHM , sCur ); - pXMLElement = ( *aLangHM )[ sCur ]; - isFallback = true; - } - if( pXMLElement != NULL ) - { - parent = pXMLElement->GetParent(); - sLId = pXMLElement->GetOldref(); - pResData->sId = sLId; - - pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); - if( pEntrys != NULL) - { - ByteString sNewText; - pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur , true ); - sNewdata = String( sNewText , RTL_TEXTENCODING_UTF8 ); - if ( sNewdata.Len()) - { - printf("Entries found\n"); - if( pXMLElement != NULL ) - { - data = new XMLData( sNewdata , NULL , true ); // Add new one - if( pXMLElement->ToOUString().compareTo( OUString(data->GetData()) ) != 0 ) - { - pXMLElement->RemoveAndDeleteAllChilds(); - pXMLElement->AddChild( data ); - } - if( isFallback ) - { - xmldefault = new XMLDefault( String::CreateFromAscii("\n") , NULL ); - int pos = parent->GetPosition( pXMLElement->GetId() ); - if( pos != -1 ){ - parent->AddChild(xmldefault , pos+1 ); - parent->AddChild(pXMLElement , pos+2 ); - } - else fprintf(stdout,"ERROR: Can't find reference Element of id %s language %d\n",pXMLElement->GetId().GetBuffer(),curLang); - } - - aLangHM->erase( sCur ); - } - } - delete pResData; - }else if( pResData == NULL ){fprintf(stdout,"Can't find GID=%s LID=%s TYP=%s\n",pResData->sGId.GetBuffer(),pResData->sId.GetBuffer(),pResData->sResTyp.GetBuffer());} - } - - } -} - diff --git a/transex3/source/inireader.cxx b/transex3/source/inireader.cxx deleted file mode 100644 index 1ff34fad8e95..000000000000 --- a/transex3/source/inireader.cxx +++ /dev/null @@ -1,132 +0,0 @@ -#include -#include -#include -#include -#include -#include "inireader.hxx" - -using namespace std; -namespace transex3 -{ - -bool INIreader::read( INImap& myMap , string& filename ) -{ - ifstream aFStream( filename.c_str() ); - if( aFStream && aFStream.is_open()) - { - string line; - string section; - string param_key; - string param_value; - stringmap* myvalues = 0; - - while( std::getline( aFStream , line ) ) - { - trim( line ); - if( line.empty() ){ - } - else if( is_section( line , section ) ) - { - //cerr << "[" << section << "]\n"; - myvalues = new stringmap(); - myMap[ section ] = myvalues ; - } - else if ( is_parameter( line , param_key , param_value ) ) - { - //cerr << "" << param_key << " = " << param_value << "\n"; - if( myvalues ) - { - (*myvalues)[ param_key ] = param_value ; - } - else - { - cerr << "ERROR: The INI file " << filename << " appears to be broken ... parameters without a section?!?\n"; - if( aFStream.is_open() ) aFStream.close(); - return false; - } - } - } - - if( aFStream.is_open() ) - aFStream.close(); - - return true; - } - else - { - cerr << "ERROR: Can't open file '" << filename << "'\n"; - } - return false; -} - -bool INIreader::is_section( string& line , string& section_str ) -{ - // Error in regex ? - check_status( section_status ); - UnicodeString target( line.c_str() , line.length() ); - - section_match->reset( target ); - check_status( section_status ); - - if( section_match->find() ) - { - check_status( section_status ); - UnicodeString result( section_match->group( 1 , section_status) ); - check_status( section_status ); - toStlString( result , section_str ); - - return true; - } - return false; -} - -bool INIreader::is_parameter( string& line , string& parameter_key , string& parameter_value ) -{ - // Error in regex ? - check_status( parameter_status ); - UnicodeString target( line.c_str() , line.length() ); - - parameter_match->reset( target ); - check_status( parameter_status ); - - if( parameter_match->find() ) - { - check_status( parameter_status ); - - UnicodeString result1( parameter_match->group( 1 , parameter_status) ); - check_status( parameter_status ); - toStlString( result1 , parameter_key ); - UnicodeString result2( parameter_match->group( 2 , parameter_status) ); - check_status( parameter_status ); - toStlString( result2 , parameter_value ); - - return true; - } - return false; -} - -void INIreader::check_status( UErrorCode status ) -{ - if( U_FAILURE( status) ) - { - cerr << "Error in or while using regex: " << u_errorName( status ) << "\n"; - exit(-1); - } -} - -void INIreader::toStlString( const UnicodeString& str , string& stl_str) -{ - // convert to string - char* buffer = new char[ str.length()*3 ]; - str.extract( 0 , str.length() , buffer ); - stl_str = string( buffer ); - delete[] buffer; -} - -void INIreader::trim( string& str ) -{ - string str1 = str.substr( 0 , str.find_last_not_of(' ') + 1 ); - str = str1.empty() ? str1 : str1.substr( str1.find_first_not_of(' ') ); -} - -} diff --git a/transex3/source/lngex.cxx b/transex3/source/lngex.cxx deleted file mode 100644 index 53c97de6e045..000000000000 --- a/transex3/source/lngex.cxx +++ /dev/null @@ -1,226 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: lngex.cxx,v $ - * $Revision: 1.18 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include - -// local includes -#include "lngmerge.hxx" - -// defines to parse command line -#define STATE_NON 0x0001 -#define STATE_INPUT 0x0002 -#define STATE_OUTPUT 0x0003 -#define STATE_PRJ 0x0004 -#define STATE_ROOT 0x0005 -#define STATE_MERGESRC 0x0006 -#define STATE_ERRORLOG 0x0007 -#define STATE_BREAKHELP 0x0008 -#define STATE_UNMERGE 0x0009 -#define STATE_UTF8 0x000A -#define STATE_ULF 0x000B -#define STATE_LANGUAGES 0x000C - -// set of global variables -ByteString sInputFile; -BOOL bEnableExport; -BOOL bMergeMode; -BOOL bErrorLog; -BOOL bUTF8; -BOOL bULF; // ULF = Unicode Language File -bool bQuiet; -ByteString sPrj; -ByteString sPrjRoot; -ByteString sOutputFile; -ByteString sMergeSrc; - -/*****************************************************************************/ -BOOL ParseCommandLine( int argc, char* argv[]) -/*****************************************************************************/ -{ - bEnableExport = FALSE; - bMergeMode = FALSE; - bErrorLog = TRUE; - bUTF8 = TRUE; - bULF = FALSE; - bQuiet = false; - sPrj = ""; - sPrjRoot = ""; - Export::sLanguages = ""; - - USHORT nState = STATE_NON; - BOOL bInput = FALSE; - - // parse command line - for( int i = 1; i < argc; i++ ) { - ByteString sSwitch( argv[ i ] ); - sSwitch.ToUpperAscii(); - if ( sSwitch == "-I" ) { - nState = STATE_INPUT; // next tokens specifies source files - } - else if ( sSwitch == "-O" ) { - nState = STATE_OUTPUT; // next token specifies the dest file - } - else if ( sSwitch == "-P" ) { - nState = STATE_PRJ; // next token specifies the cur. project - } - else if ( sSwitch == "-R" ) { - nState = STATE_ROOT; // next token specifies path to project root - } - else if ( sSwitch == "-QQ" ) { - bQuiet = true; - } - else if ( sSwitch == "-M" ) { - nState = STATE_MERGESRC; // next token specifies the merge database - } - else if ( sSwitch == "-E" ) { - nState = STATE_ERRORLOG; - bErrorLog = FALSE; - } - else if ( sSwitch == "-UTF8" ) { - nState = STATE_UTF8; - bUTF8 = TRUE; - } -/* else if ( sSwitch == "-NOUTF8" ) { - nState = STATE_UTF8; - bUTF8 = FALSE; - }*/ -/* else if ( sSwitch == "-ULF" ) { - nState = STATE_ULF; - bULF = TRUE; - }*/ - else if ( sSwitch == "-L" ) { - nState = STATE_LANGUAGES; - } - else { - switch ( nState ) { - case STATE_NON: { - return FALSE; // no valid command line - } - //break; - case STATE_INPUT: { - sInputFile = argv[ i ]; - bInput = TRUE; // source file found - } - break; - case STATE_OUTPUT: { - sOutputFile = argv[ i ]; // the dest. file - } - break; - case STATE_PRJ: { - sPrj = argv[ i ]; -// sPrj.ToLowerAscii(); // the project - } - break; - case STATE_ROOT: { - sPrjRoot = argv[ i ]; // path to project root - } - break; - case STATE_MERGESRC: { - sMergeSrc = argv[ i ]; - bMergeMode = TRUE; // activate merge mode, cause merge database found - } - break; - case STATE_LANGUAGES: { - Export::sLanguages = argv[ i ]; - } - break; - } - } - } - - if ( bInput ) { - // command line is valid - bULF = TRUE; - bEnableExport = TRUE; - return TRUE; - } - - // command line is not valid - return FALSE; -} - - -/*****************************************************************************/ -void Help() -/*****************************************************************************/ -{ - //fprintf( stdout, "Syntax:ULFEX[-p Prj][-r PrjRoot]-i FileIn -o FileOut[-m DataBase][-e][-b][-u][-NOUTF8][-ULF][-L l1,l2,...]\n" ); - fprintf( stdout, "Syntax:ULFEX[-p Prj][-r PrjRoot]-i FileIn -o FileOut[-m DataBase][-L l1,l2,...]\n" ); - fprintf( stdout, " Prj: Project\n" ); - fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); - fprintf( stdout, " FileIn: Source file (*.lng)\n" ); - fprintf( stdout, " FileOut: Destination file (*.*)\n" ); - fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); - fprintf( stdout, " -QQ: quite output\n" ); - //fprintf( stdout, " -NOUTF8: disable UTF8 as language independent encoding\n" ); - //fprintf( stdout, " -ULF: enables Unicode Language File format, leads to UTF8 encoded version of lng files" ); - fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); - fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); - fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); - fprintf( stdout, " Example: -L de,es=en-US\n" ); - fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); -} - -/*****************************************************************************/ -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - if ( !ParseCommandLine( argc, argv )) { - Help(); - return 1; - } - if( !bQuiet ){ - fprintf( stdout, "\nUlfEx 1 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); - fprintf( stdout, "====================================================================\n" ); - fprintf( stdout, "\nProcessing File %s ...\n", sInputFile.GetBuffer()); - }else - { - fprintf(stdout, "."); - fflush( stdout ); - } - - if ( sOutputFile.Len()) { - LngParser aParser( sInputFile, bUTF8, bULF , bQuiet ); - if ( bMergeMode ) - aParser.Merge( sMergeSrc, sOutputFile , sPrj ); - else - aParser.CreateSDF( sOutputFile, sPrj, sPrjRoot ); - } - - if( !bQuiet ) fprintf( stdout, "\n=================================================\n\n" ); - - return 0; -} diff --git a/transex3/source/lngmerge.cxx b/transex3/source/lngmerge.cxx deleted file mode 100644 index e55fdc83ce37..000000000000 --- a/transex3/source/lngmerge.cxx +++ /dev/null @@ -1,360 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: lngmerge.cxx,v $ - * $Revision: 1.29 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include - -// local includes -#include "lngmerge.hxx" -#include "utf8conv.hxx" -#include -using namespace std; -// -// class LngParser -// -/*****************************************************************************/ -LngParser::LngParser( const ByteString &rLngFile, BOOL bUTF8, BOOL bULFFormat , bool bQuiet_in ) -/*****************************************************************************/ - : - nError( LNG_OK ), - pLines( NULL ), - sSource( rLngFile ), - bDBIsUTF8( bUTF8 ), - bULF( bULFFormat ), - bQuiet( bQuiet_in ) -{ - pLines = new LngLineList( 100, 100 ); - DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); - if ( aEntry.Exists()) { - SvFileStream aStream( String( sSource, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); - if ( aStream.IsOpen()) { - ByteString sLine; - bool bFirstLine = true; - while ( !aStream.IsEof()) { - aStream.ReadLine( sLine ); - - if( bFirstLine ){ // Always remove UTF8 BOM from the first line - Export::RemoveUTF8ByteOrderMarker( sLine ); - bFirstLine = false; - } - - pLines->Insert( new ByteString( sLine ), LIST_APPEND ); - } - } - else - nError = LNG_COULD_NOT_OPEN; - } - else - nError = LNG_FILE_NOTFOUND; -} - -/*****************************************************************************/ -LngParser::~LngParser() -/*****************************************************************************/ -{ - for ( ULONG i = 0; i < pLines->Count(); i++ ) - delete pLines->GetObject( i ); - delete pLines; -} - -/*****************************************************************************/ -void LngParser::FillInFallbacks( ByteStringHashMap Text ) -/*****************************************************************************/ -{ - ByteString sCur; - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - - if( Export::isAllowed( sCur ) ){ - ByteString sFallbackLang = Export::GetFallbackLanguage( sCur ); - if( sFallbackLang.Len() ){ - Text[ sCur ] = Text[ sFallbackLang ]; - } - } - } -} - -/*****************************************************************************/ -BOOL LngParser::CreateSDF( - const ByteString &rSDFFile, const ByteString &rPrj, - const ByteString &rRoot ) -/*****************************************************************************/ -{ - - Export::InitLanguages( false ); - aLanguages = Export::GetLanguages(); - SvFileStream aSDFStream( String( rSDFFile, RTL_TEXTENCODING_ASCII_US ), - STREAM_STD_WRITE | STREAM_TRUNC ); - if ( !aSDFStream.IsOpen()) { - nError = SDF_COULD_NOT_OPEN; - } - aSDFStream.SetStreamCharSet( RTL_TEXTENCODING_UTF8 ); - nError = SDF_OK; - DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - String sFullEntry = aEntry.GetFull(); - aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( rRoot ); - ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); - ByteString sActFileName( - sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); - sActFileName.SearchAndReplaceAll( "/", "\\" ); - - ULONG nPos = 0; - BOOL bStart = true; - ByteString sGroup; - ByteStringHashMap Text; - ByteString sID; - ByteString sLine; - - while( nPos < pLines->Count() ){ - sLine = *pLines->GetObject( nPos++ ); - while( nPos < pLines->Count() && !isNextGroup( sGroup , sLine ) ){ - ReadLine( sLine , Text ); - sID = sGroup; - sLine = *pLines->GetObject( nPos++ ); - }; - if( bStart ){ - bStart = false; - sID = sGroup; - } - else { - - WriteSDF( aSDFStream , Text , rPrj , rRoot , sActFileName , sID ); - } - } - aSDFStream.Close(); - return true; -} - - void LngParser::WriteSDF( SvFileStream &aSDFStream , ByteStringHashMap &rText_inout , - const ByteString &rPrj , const ByteString &rRoot , - const ByteString &sActFileName , const ByteString &sID ) - { - - BOOL bExport = true; - if ( bExport ) { - ByteString sTimeStamp( Export::GetTimeStamp()); - ByteString sCur; - FillInFallbacks( rText_inout ); - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - ByteString sAct = rText_inout[ sCur ]; - if ( !sAct.Len() && sCur.Len() ) - sAct = rText_inout[ ByteString("en-US") ]; - - ByteString sOutput( rPrj ); sOutput += "\t"; - if ( rRoot.Len()) - sOutput += sActFileName; - sOutput += "\t0\t"; - sOutput += "LngText\t"; - sOutput += sID; sOutput += "\t\t\t\t0\t"; - sOutput += sCur; sOutput += "\t"; - sOutput += sAct; sOutput += "\t\t\t\t"; - sOutput += sTimeStamp; - //if( !sCur.EqualsIgnoreCaseAscii("de") ||( sCur.EqualsIgnoreCaseAscii("de") && !Export::isMergingGermanAllowed( rPrj ) ) ) - aSDFStream.WriteLine( sOutput ); - } - } - } - bool LngParser::isNextGroup( ByteString &sGroup_out , ByteString &sLine_in ){ - sLine_in.EraseLeadingChars( ' ' ); - sLine_in.EraseTrailingChars( ' ' ); - if (( sLine_in.GetChar( 0 ) == '[' ) && - ( sLine_in.GetChar( sLine_in.Len() - 1 ) == ']' )){ - sGroup_out = sLine_in.GetToken( 1, '[' ).GetToken( 0, ']' ); - sGroup_out.EraseLeadingChars( ' ' ); - sGroup_out.EraseTrailingChars( ' ' ); - return true; - } - return false; - } - void LngParser::ReadLine( const ByteString &sLine_in , ByteStringHashMap &rText_inout){ - //printf("sLine -> '%s'\n",sLine_in.GetBuffer()); - ByteString sLang = sLine_in.GetToken( 0, '=' ); - sLang.EraseLeadingChars( ' ' ); - sLang.EraseTrailingChars( ' ' ); - ByteString sText = sLine_in.GetToken( 1, '\"' ).GetToken( 0, '\"' ); - if( sLang.Len() ) - rText_inout[ sLang ] = sText; - } - -/*****************************************************************************/ -BOOL LngParser::Merge( - const ByteString &rSDFFile, const ByteString &rDestinationFile , const ByteString& rPrj ) -/*****************************************************************************/ -{ - (void) rPrj; - Export::InitLanguages( true ); - SvFileStream aDestination( - String( rDestinationFile, RTL_TEXTENCODING_ASCII_US ), - STREAM_STD_WRITE | STREAM_TRUNC ); - if ( !aDestination.IsOpen()) { - nError = LNG_COULD_NOT_OPEN; - } - nError = LNG_OK; -// MergeDataFile( const ByteString &rFileName, const ByteString& rFile , BOOL bErrLog, CharSet aCharSet, BOOL bUTF8 ); - - MergeDataFile aMergeDataFile( rSDFFile, sSource , FALSE, RTL_TEXTENCODING_MS_1252);//, bDBIsUTF8 ); - ByteString sTmp( Export::sLanguages ); - if( sTmp.ToUpperAscii().Equals("ALL") ) - Export::SetLanguages( aMergeDataFile.GetLanguages() ); - aLanguages = Export::GetLanguages(); - - ULONG nPos = 0; - BOOL bGroup = FALSE; - ByteString sGroup; - - // seek to next group - while ( nPos < pLines->Count() && !bGroup ) { - ByteString sLine( *pLines->GetObject( nPos )); - sLine.EraseLeadingChars( ' ' ); - sLine.EraseTrailingChars( ' ' ); - if (( sLine.GetChar( 0 ) == '[' ) && - ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) - { - sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); - sGroup.EraseLeadingChars( ' ' ); - sGroup.EraseTrailingChars( ' ' ); - bGroup = TRUE; - } - nPos ++; - } - - while ( nPos < pLines->Count()) { - ByteStringHashMap Text; - ByteString sID( sGroup ); - ULONG nLastLangPos = 0; - - ResData *pResData = new ResData( "", sID , sSource ); - pResData->sResTyp = "LngText"; - PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); - // read languages - bGroup = FALSE; - - ByteString sLanguagesDone; - - while ( nPos < pLines->Count() && !bGroup ) { - ByteString sLine( *pLines->GetObject( nPos )); - sLine.EraseLeadingChars( ' ' ); - sLine.EraseTrailingChars( ' ' ); - if (( sLine.GetChar( 0 ) == '[' ) && - ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) - { - sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); - sGroup.EraseLeadingChars( ' ' ); - sGroup.EraseTrailingChars( ' ' ); - bGroup = TRUE; - nPos ++; - sLanguagesDone = ""; - } - else if ( sLine.GetTokenCount( '=' ) > 1 ) { - ByteString sLang = sLine.GetToken( 0, '=' ); - sLang.EraseLeadingChars( ' ' ); - sLang.EraseTrailingChars( ' ' ); - - ByteString sSearch( ";" ); - sSearch += sLang; - sSearch += ";"; - - if (( sLanguagesDone.Search( sSearch ) != STRING_NOTFOUND )) { - pLines->Remove( nPos ); - } - if( bULF && pEntrys ) - { - // this is a valid text line - ByteString sText = sLine.GetToken( 1, '\"' ).GetToken( 0, '\"' ); - if( sLang.Len() ){ - ByteString sNewText; - pEntrys->GetText( sNewText, STRING_TYP_TEXT, sLang, TRUE ); - - if ( sNewText.Len()) { - ByteString *pLine = pLines->GetObject( nPos ); - - ByteString sText1( sLang ); - sText1 += " = \""; - sText1 += sNewText; - sText1 += "\""; - *pLine = sText1; - //} - Text[ sLang ] = sNewText; - } - } - nLastLangPos = nPos; - nPos ++; - sLanguagesDone += sSearch; - } - else { - nLastLangPos = nPos; - nPos ++; - sLanguagesDone += sSearch; - } - } - else - nPos++; - } - ByteString sCur; - if ( nLastLangPos ) { - for( unsigned int n = 0; n < aLanguages.size(); n++ ){ - sCur = aLanguages[ n ]; - if( //( !sCur.EqualsIgnoreCaseAscii("de") || - //( sCur.EqualsIgnoreCaseAscii("de") && Export::isMergingGermanAllowed( rPrj ) ) ) - !sCur.EqualsIgnoreCaseAscii("en-US") && !Text[ sCur ].Len() && pEntrys ){ - - ByteString sNewText; - pEntrys->GetText( sNewText, STRING_TYP_TEXT, sCur, TRUE ); - if (( sNewText.Len()) && - !(( sCur.Equals("x-comment") ) && ( sNewText == "-" ))) - { - ByteString sLine; - sLine += sCur; - sLine += " = \""; - sLine += sNewText; - sLine += "\""; - - nLastLangPos++; - nPos++; - - pLines->Insert( new ByteString( sLine ), nLastLangPos ); - } - } - } - } - - delete pResData; - } - - for ( ULONG i = 0; i < pLines->Count(); i++ ) - aDestination.WriteLine( *pLines->GetObject( i )); - - aDestination.Close(); - return TRUE; -} diff --git a/transex3/source/localize.cxx b/transex3/source/localize.cxx deleted file mode 100644 index e23165ee657c..000000000000 --- a/transex3/source/localize.cxx +++ /dev/null @@ -1,986 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: localize.cxx,v $ - * $Revision: 1.50 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" - -#include "srciter.hxx" -#include "export.hxx" -#include "treeconfig.hxx" -#include -#include -#include -#include -#include "tools/errcode.hxx" -#include "tools/fsys.hxx" - -#ifndef TRANSEX_FILE_HXX -#define TRANSEX_FILE_HXX -#include -#endif - -namespace transex3 -{ - -// -// SourceTreeLocalizer -// - -const char *ExeTable[][5] = { - { "src", "transex3", " -UTF8 -e", "negative", "noiso" }, - { "hrc", "transex3", " -UTF8 -e", "positive", "noiso" }, - //{ "src", "transex3", "-UTF8 -e", "negative", "noiso" }, - //{ "hrc", "transex3", "-UTF8 -e", "positive", "noiso" }, - - //{ "lng", "lngex", "-UTF8 -e", "negative", "noiso" }, - { "ulf", "ulfex", " -e", "negative", "noiso" }, - { "xrb", "xmlex", "-UTF8 -e", "negative", "iso" }, - { "xxl", "xmlex", "-UTF8 -e", "negative", "iso" }, - { "xgf", "xmlex", "-UTF8 -e -t:xgf", "negative", "iso" }, - { "xcd", "cfgex", "-UTF8 -e", "negative", "iso" }, - { "xcu", "cfgex", "-UTF8 -e", "negative", "iso" }, - { "xcs", "cfgex", "-UTF8 -e -f", "negative", "iso" }, - { "xrm", "xrmex", "-UTF8 -e", "negative", "iso" }, - { "xhp", "helpex", " -e", "negative", "noiso" }, - { "NULL", "NULL", "NULL", "NULL", "NULL" } -}; - -const char *NegativeList[] = { - "officecfg/data/org.openoffice.Office.Labels.xcd", - "officecfg/data/org/openoffice/Office/Labels.xcd", - "officecfg/data/org/openoffice/Office/SFX.xcd", - "officecfg/data/org/openoffice/Office/Accelerators.xcu", - "hidother.src", - "NULL" -}; - -const char *PositiveList[] = { - "svx/inc/globlmn_tmpl.hrc", - "sw/source/ui/inc/swmn_tmpl.hrc", - "sw/source/ui/inc/swacc_tmpl.hrc", - "sw/source/ui/inc/toolbox_tmpl.hrc", - "offmgr/inc/offmenu_tmpl.hrc", - "offmgr/source/offapp/intro/intro_tmpl.hrc", - "dbaccess/source/ui/inc/toolbox_tmpl.hrc", - "svx/source/intro/intro_tmpl.hrc", - "dbaccess/source/ui/dlg/AutoControls_tmpl.hrc", - "svx/source/unodialogs/textconversiondlgs/chinese_direction_tmpl.hrc", - "chart2/source/controller/dialogs/res_DataLabel_tmpl.hrc", - "chart2/source/controller/dialogs/res_LegendPosition_tmpl.hrc", - "chart2/source/controller/dialogs/res_Statistic_tmpl.hrc", - "chart2/source/controller/dialogs/res_Titlesx_tmpl.hrc", - "chart2/source/controller/dialogs/res_SecondaryAxisCheckBoxes_tmpl.hrc", - "chart2/source/controller/menu/MenuItems_tmpl.hrc", - "chart2/source/controller/dialogs/res_ErrorBar_tmpl.hrc", - "chart2/source/controller/dialogs/res_Trendline_tmpl.hrc", - "svx.link/inc/globlmn_tmpl.hrc", - "sw.link/source/ui/inc/swmn_tmpl.hrc", - "sw.link/source/ui/inc/swacc_tmpl.hrc", - "sw.link/source/ui/inc/toolbox_tmpl.hrc", - "offmgr.link/inc/offmenu_tmpl.hrc", - "offmgr.link/source/offapp/intro/intro_tmpl.hrc", - "dbaccess.link/source/ui/inc/toolbox_tmpl.hrc", - "svx.link/source/intro/intro_tmpl.hrc", - "dbaccess.link/source/ui/dlg/AutoControls_tmpl.hrc", - "svx.link/source/unodialogs/textconversiondlgs/chinese_direction_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_DataLabel_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_LegendPosition_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_Statistic_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_Titlesx_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_SecondaryAxisCheckBoxes_tmpl.hrc", - "chart2.link/source/controller/menu/MenuItems_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_ErrorBar_tmpl.hrc", - "chart2.link/source/controller/dialogs/res_Trendline_tmpl.hrc", - "NULL" -}; - - -const char PRJ_DIR_NAME[] = "prj"; -const char DLIST_NAME[] = "d.lst"; - -#define LOCALIZE_NONE 0x0000 -#define LOCALIZE_EXTRACT 0x0001 -#define LOCALIZE_MERGE 0x0002 - -class SourceTreeLocalizer : public SourceTreeIterator -{ -private: - SvFileStream aSDF; - USHORT nMode; - - ByteString sLanguageRestriction; - - ByteString sOutputFile; - bool bQuiet2; - - int nFileCnt; - - const ByteString GetProjectName( BOOL bAbs = FALSE ); - const ByteString GetProjectRootRel(); - - - BOOL CheckNegativeList( const ByteString &rFileName ); - BOOL CheckPositiveList( const ByteString &rFileName ); - - void WorkOnFile( - const ByteString &rFileName, - const ByteString &rExecutable, - const ByteString &rParameter - ); - - void WorkOnFileType( - const ByteString &rDirectory, - const ByteString &rExtension, - const ByteString &rExecutable, - const ByteString &rParameter, - const ByteString &rCollectMode - ); - void WorkOnDirectory( const ByteString &rDirectory ); - BOOL ExecuteMerge(); - BOOL MergeSingleFile( - const ByteString &rPrj, - const ByteString &rFile, - const ByteString &rSDFFile - ); - -public: - SourceTreeLocalizer( const ByteString &rRoot, const ByteString &rVersion , bool bLocal , bool bQuiet2_in , bool skip_links ); - ~SourceTreeLocalizer(); - - ByteString getSourceLanguages( ByteString sLanguageRestriction , ByteString sCommand ); - - void SetLanguageRestriction( const ByteString& rRestrictions ) - { sLanguageRestriction = rRestrictions; } - int getFileCnt(); - BOOL Extract( const ByteString &rDestinationFile ); - BOOL Merge( const ByteString &rSourceFile , const ByteString &rOutput ); - int GetFileCnt(); - virtual void OnExecuteDirectory( const rtl::OUString &rDirectory ); -}; - -/*****************************************************************************/ -SourceTreeLocalizer::SourceTreeLocalizer( - const ByteString &rRoot, const ByteString &rVersion, bool bLocal_in , bool bQuiet2_in , bool skip_links ) -/*****************************************************************************/ - : SourceTreeIterator( rRoot, rVersion , bLocal_in ), - nMode( LOCALIZE_NONE ), - bQuiet2( bQuiet2_in ), - nFileCnt( 0 ) -{ - bSkipLinks = skip_links ; -} - -/*****************************************************************************/ -SourceTreeLocalizer::~SourceTreeLocalizer() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -const ByteString SourceTreeLocalizer::GetProjectName( BOOL bAbs ) -/*****************************************************************************/ -{ - BOOL bFound = FALSE; - DirEntry aCur; - aCur.ToAbs(); - - for ( ; ! bFound && aCur.Level() > 1; aCur.CutName() ) - { - DirEntry aTest = aCur + DirEntry(PRJ_DIR_NAME) + DirEntry(DLIST_NAME); - if ( aTest.Exists() ) - { - if ( bAbs ) - return ByteString( aCur.GetFull(), RTL_TEXTENCODING_ASCII_US ); - else - return ByteString( aCur.GetName(), RTL_TEXTENCODING_ASCII_US ); - } - } - - return ""; -} -/*****************************************************************************/ -int SourceTreeLocalizer::GetFileCnt(){ -/*****************************************************************************/ - return nFileCnt; -} - -/*****************************************************************************/ -const ByteString SourceTreeLocalizer::GetProjectRootRel() -/*****************************************************************************/ -{ - ByteString sProjectRoot( GetProjectName( TRUE )); - DirEntry aCur; - aCur.ToAbs(); - ByteString sCur( aCur.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - if( sCur.SearchAndReplace( sProjectRoot, "" ) == STRING_NOTFOUND ) - return ""; - - ByteString sDelimiter( - DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - - sCur.SearchAndReplaceAll( sDelimiter, "/" ); - sCur.EraseLeadingChars( '/' ); - ULONG nCount = sCur.GetTokenCount( '/' ); - - ByteString sProjectRootRel; - for ( ULONG i = 0; i < nCount; i++ ) { - if ( sProjectRootRel.Len()) - sProjectRootRel += sDelimiter; - sProjectRootRel += ".."; - } - if ( sProjectRootRel.Len()) - return sProjectRootRel; - - return "."; -} - -bool skipProject( ByteString sPrj ) -{ - static const ByteString READLICENSE( "readlicense" ); - return sPrj.EqualsIgnoreCaseAscii( READLICENSE ); -} - -/*****************************************************************************/ -void SourceTreeLocalizer::WorkOnFile( - const ByteString &rFileName, const ByteString &rExecutable, - const ByteString &rParameter ) -/*****************************************************************************/ -{ - String sFull( rFileName, RTL_TEXTENCODING_ASCII_US ); - DirEntry aEntry( sFull ); - ByteString sFileName( aEntry.GetName(), RTL_TEXTENCODING_ASCII_US ); - - // set current working directory - DirEntry aPath( aEntry.GetPath()); - DirEntry aOldCWD; - aPath.SetCWD(); - - ByteString sPrj( GetProjectName()); - if ( sPrj.Len() && !skipProject( sPrj ) ) - { - ByteString sRoot( GetProjectRootRel()); - - DirEntry aTemp( Export::GetTempFile()); - ByteString sTempFile( aTemp.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - ByteString sDel; -#if defined(WNT) || defined(OS2) - sDel=ByteString("\\"); -#else - sDel=ByteString("/"); -#endif - ByteString sPath1( Export::GetEnv("SOLARVER") ); - ByteString sPath2( Export::GetEnv("INPATH") ); - ByteString sPath3( "bin" ); - ByteString sPath4( Export::GetEnv("UPDMINOREXT") ); - ByteString sExecutable( sPath1 ); - sExecutable += sDel ; - sExecutable += sPath2 ; - sExecutable += sDel; - sExecutable += sPath3 ; - sExecutable += sPath4 ; - sExecutable += sDel ; - sExecutable += rExecutable ; - - - ByteString sCommand( sExecutable ); - sCommand += " "; - sCommand += rParameter; - sCommand += " -p "; - sCommand += sPrj; - sCommand += " -r "; - sCommand += sRoot; - sCommand += " -i "; - sCommand += sFileName; - sCommand += " -o "; - sCommand += sTempFile; - if ( sLanguageRestriction.Len()) { - sCommand += " -l "; - sCommand += getSourceLanguages( sLanguageRestriction , sCommand ); - } - - if( bQuiet2 ){ - sCommand +=" -QQ "; - } - //printf("DBG: %s\n",sCommand.GetBuffer()); - if (system(sCommand.GetBuffer()) == -1) - fprintf(stderr, "%s failed\n", sCommand.GetBuffer()); - nFileCnt++; - printf("."); - fflush( stdout ); - - SvFileStream aSDFIn( aTemp.GetFull(), STREAM_READ ); - ByteString sLine; - while ( aSDFIn.IsOpen() && !aSDFIn.IsEof()) { - aSDFIn.ReadLine( sLine ); - if ( sLine.Len()) { - aSDF.WriteLine( sLine ); - } - } - aSDFIn.Close(); - - aTemp.Kill(); - - } - // reset current working directory - aOldCWD.SetCWD(); -} - -ByteString SourceTreeLocalizer::getSourceLanguages( ByteString sLanguageRestriction_inout , ByteString sCommand ) -{ - // Source languages in helpcontent2 and macromigration en-US only! - if( sCommand.Search("helpex") != STRING_NOTFOUND ) { - sLanguageRestriction_inout.Assign( ByteString("en-US") ); - } - else if( sCommand.Search("xmlex") != STRING_NOTFOUND ){ - sLanguageRestriction_inout.Assign( ByteString("en-US") ); - } - return sLanguageRestriction_inout; -} - -/*****************************************************************************/ -BOOL SourceTreeLocalizer::CheckNegativeList( const ByteString &rFileName ) -/*****************************************************************************/ -{ - ULONG nIndex = 0; - BOOL bReturn = TRUE; - - ByteString sDelimiter( - DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - - ByteString sFileName( rFileName ); - sFileName.ToLowerAscii(); - - ByteString sNegative( NegativeList[ nIndex ] ); - while( !sNegative.Equals( "NULL" ) && bReturn ) { - sNegative.SearchAndReplaceAll( "\\", sDelimiter ); - sNegative.SearchAndReplaceAll( "/", sDelimiter ); - sNegative.ToLowerAscii(); - - if( sFileName.Search( sNegative ) == sFileName.Len() - sNegative.Len()) - bReturn = FALSE; - - nIndex++; - sNegative = NegativeList[ nIndex ]; - } - - return bReturn; -} - -/*****************************************************************************/ -BOOL SourceTreeLocalizer::CheckPositiveList( const ByteString &rFileName ) -/*****************************************************************************/ -{ - ULONG nIndex = 0; - BOOL bReturn = FALSE; - - ByteString sDelimiter( - DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - - ByteString sFileName( rFileName ); - sFileName.ToLowerAscii(); - - ByteString sNegative( PositiveList[ nIndex ] ); - while( !sNegative.Equals( "NULL" ) && !bReturn ) { - sNegative.SearchAndReplaceAll( "\\", sDelimiter ); - sNegative.SearchAndReplaceAll( "/", sDelimiter ); - sNegative.ToLowerAscii(); - - if( sFileName.Search( sNegative ) == sFileName.Len() - sNegative.Len()) - bReturn = TRUE; - - nIndex++; - sNegative = PositiveList[ nIndex ]; - } - - return bReturn; -} - -/*****************************************************************************/ -void SourceTreeLocalizer::WorkOnFileType( - const ByteString &rDirectory, const ByteString &rExtension, - const ByteString &rExecutable, const ByteString &rParameter, - const ByteString &rCollectMode -) -/*****************************************************************************/ -{ - String sWild( rDirectory, RTL_TEXTENCODING_ASCII_US ); - sWild += DirEntry::GetAccessDelimiter(); - sWild += String::CreateFromAscii( "*." ); - sWild += String( rExtension, RTL_TEXTENCODING_ASCII_US ); - - DirEntry aEntry( sWild ); - Dir aDir( sWild, FSYS_KIND_FILE ); - - for ( USHORT i = 0; i < aDir.Count(); i++ ) { - DirEntry aFile( aDir[ i ] ); - ByteString sFile( aFile.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - BOOL bAllowed = TRUE; - - if ( rCollectMode.Equals( "negative" )) - bAllowed = CheckNegativeList( sFile ); - else if ( rCollectMode.Equals( "positive" )) - bAllowed = CheckPositiveList( sFile ); - - if ( bAllowed ) - WorkOnFile( sFile, rExecutable, rParameter ); - } -} - -/*****************************************************************************/ -void SourceTreeLocalizer::WorkOnDirectory( const ByteString &rDirectory ) -/*****************************************************************************/ -{ - //printf("Working on Directory %s\n",rDirectory.GetBuffer()); - ULONG nIndex = 0; - ByteString sExtension( ExeTable[ nIndex ][ 0 ] ); - ByteString sExecutable( ExeTable[ nIndex ][ 1 ] ); - ByteString sParameter( ExeTable[ nIndex ][ 2 ] ); - ByteString sCollectMode( ExeTable[ nIndex ][ 3 ] ); - - while( !sExtension.Equals( "NULL" )) { - WorkOnFileType( - rDirectory, - sExtension, - sExecutable, - sParameter, - sCollectMode - ); - - nIndex++; - - sExtension = ExeTable[ nIndex ][ 0 ]; - sExecutable = ExeTable[ nIndex ][ 1 ]; - sParameter = ExeTable[ nIndex ][ 2 ]; - sCollectMode = ExeTable[ nIndex ][ 3 ]; - } -} - -void SourceTreeLocalizer::OnExecuteDirectory( const rtl::OUString &aDirectory ) -{ - ByteString rDirectory( rtl::OUStringToOString( aDirectory , RTL_TEXTENCODING_UTF8 , aDirectory.getLength() ) ) ; - if ( nMode == LOCALIZE_NONE ){ - if( !bQuiet2 ) fprintf( stdout, "%s\n", rDirectory.GetBuffer()); - } - else - WorkOnDirectory( rDirectory ); -} - -/*****************************************************************************/ -BOOL SourceTreeLocalizer::Extract( const ByteString &rDestinationFile ) -/*****************************************************************************/ -{ - nMode = LOCALIZE_EXTRACT; - - aSDF.Open( String( rDestinationFile , RTL_TEXTENCODING_ASCII_US ) , STREAM_STD_WRITE ); - aSDF.SetLineDelimiter( LINEEND_CRLF ); - - BOOL bReturn = aSDF.IsOpen(); - if ( bReturn ) { - aSDF.Seek( STREAM_SEEK_TO_END ); - bReturn = StartExecute(); - aSDF.Close(); - } - else{ - printf("ERROR: Can't create file %s\n", rDestinationFile.GetBuffer() ); - } - nMode = LOCALIZE_NONE; - aSDF.Close(); - return bReturn; -} - -/*****************************************************************************/ -BOOL SourceTreeLocalizer::MergeSingleFile( - const ByteString &rPrj, - const ByteString &rFile, - const ByteString &rSDFFile -) -/*****************************************************************************/ -{ - //printf("MergeSingleFile(%s,%s,%s)",rPrj.GetBuffer(),rFile.GetBuffer(),rSDFFile.GetBuffer()); - if ( !rFile.Len()) - return TRUE; - - ByteString sRoot( Export::GetEnv( "SRC_ROOT" )); - DirEntry aEntry( String( sRoot, RTL_TEXTENCODING_ASCII_US )); - aEntry += DirEntry( String( rPrj, RTL_TEXTENCODING_ASCII_US )); - - ByteString sDelimiter( - DirEntry::GetAccessDelimiter(), RTL_TEXTENCODING_ASCII_US ); - - ByteString sCur( rFile ); - sCur.SearchAndReplaceAll( "\\", sDelimiter ); - sCur.SearchAndReplaceAll( "/", sDelimiter ); - - aEntry += DirEntry( String( sCur, RTL_TEXTENCODING_ASCII_US )); - ByteString sFile( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - - ByteString sBCur( aEntry.GetFull(), RTL_TEXTENCODING_ASCII_US ); - if( !bQuiet2 ) fprintf( stdout, "##### %s #####\n", sBCur.GetBuffer()); - - ULONG nIndex = 0; - ByteString sExtension( aEntry.GetExtension(), RTL_TEXTENCODING_ASCII_US ); - ByteString sCandidate( ExeTable[ nIndex ][ 0 ] ); - - while( !sCandidate.Equals ("NULL") && !sCandidate.Equals(sExtension) ) - sCandidate = ExeTable[ ++nIndex ][ 0 ]; - - if ( !sCandidate.Equals( "NULL" ) ) { - if( !aEntry.Exists()) { - DirEntryKind theDir=FSYS_KIND_FILE; - Dir myDir( aEntry.GetPath(), theDir); - DirEntry current; - BOOL found=FALSE; - for( USHORT x=0; x < myDir.Count() && !found;){ - current=myDir[x++]; - StringCompare result=current.GetName().CompareIgnoreCaseToAscii( aEntry.GetName() ); - if( result==COMPARE_EQUAL ){ - fprintf(stderr,"WARNING: %s not found\n", ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US).GetBuffer() ); - fprintf(stderr,"but use %s instead \n" , ByteString(current.GetFull(), RTL_TEXTENCODING_ASCII_US).GetBuffer() ); - aEntry=current; - found=TRUE; - } - } - if(!found) return TRUE; - - } - - DirEntry aOut( Export::GetTempFile() ); - ByteString sOutput; - if( sOutputFile.Len() == 0 ) - sOutput = ByteString ( aOut.GetFull(), RTL_TEXTENCODING_ASCII_US ); - else - sOutput = sOutputFile; - ByteString sCommand( ExeTable[ nIndex ][ 1 ] ); - sCommand += " -i "; - sCommand += ByteString( aEntry.GetName(), RTL_TEXTENCODING_ASCII_US ); - sCommand += " -m "; - sCommand += rSDFFile; - sCommand += " -o "; - sCommand += sOutput; - sCommand += " "; - sCommand += ByteString( ExeTable[ nIndex ][ 2 ] ); - if ( sLanguageRestriction.Len()) { - sCommand += " -l "; - sCommand += sLanguageRestriction; - } - if( bQuiet2 ){ - sCommand +=" -QQ "; - } - - DirEntry aPath( aEntry.GetPath()); - DirEntry aOldCWD; - aPath.SetCWD(); - - if (system(sCommand.GetBuffer()) == -1) - fprintf(stderr, "%s failed\n", sCommand.GetBuffer()); - nFileCnt++; - printf("."); - //if( bQuiet2 ){ printf("."); } - SvFileStream aInStream( aOut.GetFull(), STREAM_READ ); - if ( !aInStream.IsOpen()) { - fprintf( stderr, - "ERROR: Unable to open file %s for reading!\n", - sOutput.GetBuffer()); - } - else { - FileStat::SetReadOnlyFlag( aEntry, FALSE ); - String myStr2(aEntry.GetFull()); - String aTemp22 = String::CreateFromAscii("_tmp"); - myStr2.Append(aTemp22); - - ByteString test(myStr2,RTL_TEXTENCODING_ASCII_US); - SvFileStream aOutStream( myStr2, STREAM_STD_WRITE | STREAM_TRUNC ); - if ( !aOutStream.IsOpen()) { - ByteString test2(myStr2,RTL_TEXTENCODING_ASCII_US); - fprintf( stderr,"ERROR: Unable to open file %s for modification!\n", test2.GetBuffer()); - aInStream.Close(); - } - - else { - ByteString sLine; - aOutStream.SetLineDelimiter( LINEEND_LF ); - - aInStream.ReadLine( sLine ); - while ( !aInStream.IsEof()) { - aOutStream.WriteLine( sLine ); - aInStream.ReadLine( sLine ); - } - aInStream.Close(); - aOutStream.Close(); - - - DirEntry myTempFile(ByteString(myStr2,RTL_TEXTENCODING_ASCII_US)); // xxx_tmp -> - DirEntry myFile(ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US));// xxx - - DirEntry oldFile(ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US)); - - if(oldFile.Kill()==ERRCODE_NONE){ - if(myTempFile.MoveTo(myFile)!=ERRCODE_NONE){ - fprintf( stderr, "ERROR: Can't rename file %s\n",ByteString(myStr2,RTL_TEXTENCODING_ASCII_US).GetBuffer()); - } - } - else{ - fprintf( stderr, "ERROR: Can't remove file %s\n",ByteString(aEntry.GetFull(),RTL_TEXTENCODING_ASCII_US).GetBuffer()); - } - } // else - - aOldCWD.SetCWD(); - aOut.Kill(); - } // else - } - return TRUE; -} -/*****************************************************************************/ -BOOL SourceTreeLocalizer::ExecuteMerge( ) -/*****************************************************************************/ -{ - DirEntry aEntry( Export::GetTempFile()); - BOOL bReturn = TRUE; - bool bMerged = false; - - ByteString sFileName; - ByteString sCurFile; - ByteString sLine; - ByteString sFileKey; - - SvFileStream aFile; - - ByteString sOutputFileName = sOutputFile; - ByteString sInpath("."); - sInpath += Export::GetEnv("INPATH"); - ByteString sBlank(""); - - sOutputFileName.SearchAndReplaceAll( sInpath , sBlank ); - - String sDel = DirEntry::GetAccessDelimiter(); - ByteString sBDel( sDel.GetBuffer() , sDel.Len() , RTL_TEXTENCODING_UTF8 ); - if( bLocal ){ - xub_StrLen nPos = sOutputFileName.SearchBackward( sBDel.GetChar(0) ); - sOutputFileName = sOutputFileName.Copy( nPos+1 , sOutputFileName.Len()-nPos-1 ); - } - ByteStringBoolHashMap aFileHM; - // Read all possible files - while ( !aSDF.IsEof()) { - aSDF.ReadLine( sLine ); - sFileName = sLine.GetToken( 0, '\t' ); - sFileName += "#"; - sFileName += sLine.GetToken( 1, '\t' ); - aFileHM[sFileName]=true; - } - - for( ByteStringBoolHashMap::iterator iter = aFileHM.begin(); iter != aFileHM.end(); ++iter ){ - sFileKey = iter->first; - aSDF.Seek( 0 ); - aFile.Open( aEntry.GetFull(), STREAM_STD_WRITE |STREAM_TRUNC ); - - while ( !aSDF.IsEof()) { - aSDF.ReadLine( sLine ); - sFileName = sLine.GetToken( 0, '\t' ); - sFileName += "#"; - sFileName += sLine.GetToken( 1, '\t' ); - if( sFileName.Len() && ( sFileName.CompareTo(sFileKey) == COMPARE_EQUAL ) ){ - if ( aFile.IsOpen() && sLine.Len()) - aFile.WriteLine( sLine ); - } - } - if ( aFile.IsOpen()) - aFile.Close(); - - ByteString sPrj( sFileKey.GetToken( 0, '#' )); - ByteString sFile( sFileKey.GetToken( 1, '#' )); - ByteString sSDFFile( aFile.GetFileName(), RTL_TEXTENCODING_ASCII_US ); - - //printf("localize test sPrj = %s , sFile = %s , sSDFFile = %s sOutputFileName = %s\n",sPrj.GetBuffer(), sFile.GetBuffer() , sSDFFile.GetBuffer() , sOutputFileName.GetBuffer() ); - - // Test - bLocal = true; - // Test - - if( bLocal ){ - USHORT nPos = sFile.SearchBackward( '\\' ); - ByteString sTmp = sFile.Copy( nPos+1 , sFile.Len()-nPos-1 ); - //printf("'%s'='%s'\n",sTmp.GetBuffer(), sOutputFileName.GetBuffer()); - if( sTmp.CompareTo(sOutputFileName) == COMPARE_EQUAL ){ - bMerged = true; - if ( !MergeSingleFile( sPrj, sFile, sSDFFile )) - bReturn = FALSE; - }else{ - bMerged = true; - //printf("MergeSingleFile('%s','%s','%s')\n",sPrj.GetBuffer(),sFile.GetBuffer(),sSDFFile.GetBuffer()); - if ( !MergeSingleFile( sPrj, sFile, sSDFFile )) - bReturn = FALSE; - } - } - } - aEntry.Kill(); - // If Outputfile not included in the SDF file copy it without merge - - if( bLocal && !bMerged ){ - DirEntry aSourceFile( sOutputFileName.GetBuffer() ); - FSysError aErr = aSourceFile.CopyTo( DirEntry ( sOutputFile.GetBuffer() ) , FSYS_ACTION_COPYFILE ); - if( aErr != FSYS_ERR_OK ){ - printf("ERROR: Can't copy file '%s' to '%s' %d\n",sOutputFileName.GetBuffer(),sOutputFile.GetBuffer(),sal::static_int_cast(aErr)); - } - } - return bReturn; - -} - -/*****************************************************************************/ -BOOL SourceTreeLocalizer::Merge( const ByteString &rSourceFile , const ByteString &rOutput ) -/*****************************************************************************/ -{ - sOutputFile = rOutput; - nMode = LOCALIZE_MERGE; - aSDF.Open( String( rSourceFile, RTL_TEXTENCODING_ASCII_US ), - STREAM_STD_READ ); - - BOOL bReturn = aSDF.IsOpen(); - if ( bReturn ) { - bReturn = ExecuteMerge(); -// aSDF.Close(); - } - aSDF.Close(); - nMode = LOCALIZE_NONE; - return bReturn; -} - -} -using namespace transex3; - -#define STATE_NONE 0x0000 -#define STATE_EXPORT 0x0001 -#define STATE_MERGE 0x0002 -#define STATE_ISOCODE 0x0003 -#define STATE_LANGUAGES 0x0004 -#define STATE_FILENAME 0x0005 -#define STATE_OUTPUT 0x0006 - -/*****************************************************************************/ -void Help() -/*****************************************************************************/ -{ - fprintf( stdout, - "localize (c)2001 by Sun Microsystems\n" - "====================================\n" ); - fprintf( stdout, - "As part of the L10N framework, localize extracts and merges translations\n" - "out of and into the whole source tree.\n\n" - "Syntax: localize -e -l en-US -f FileName [-QQ]\n" - "Parameter:\n" - "\t-e: Extract mode\n" - "\tFileName: Output file when extract mode, input file when merge mode\n" - "\tl1...ln: supported languages (\"all\" for all languages).\n" - "\tQQ: quiet output)" - ); - - fprintf( stdout, - "Valid language codes for l1...ln and f1...fn are:\n" ); - fprintf( stdout, - "\nExample 1:\n" - "==========\n" - "localize -e -l en-US -f MyFile\n\n" - "All strings will be extracted for language de and language en-US.\n" - ); -} - -/*****************************************************************************/ -int Error() -/*****************************************************************************/ -{ - Help(); - return 1; -} - -/*****************************************************************************/ -BOOL CheckLanguages( ByteString &rLanguages ) -/*****************************************************************************/ -{ - ByteString sTmp( rLanguages ); - return true; -} - -/*****************************************************************************/ -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - String sTempBase( String::CreateFromAscii( "loc" )); - DirEntry::SetTempNameBase( sTempBase ); - USHORT nState = STATE_NONE; - - BOOL bExport = FALSE; - BOOL bMerge = FALSE; - bool bQuiet = false; - bool bQuiet2 = false; - bool bSkipLinks = false; - - ByteString sLanguages; - ByteString sFileName; - ByteString sOutput; - - bQuiet2 = true; - bExport = TRUE; - - for( int i = 1; i < argc; i++ ) { - ByteString sSwitch( argv[ i ] ); - sSwitch.ToUpperAscii(); - - if ( sSwitch.Equals( "-E" )) { - nState = STATE_EXPORT; - if ( bMerge ) - return Error(); - bExport = TRUE; - } - else if( sSwitch.Equals( "-Q" )) { - bQuiet = true; - } - else if ( sSwitch.Equals( "-I" ) ) - nState = STATE_ISOCODE; - else if ( sSwitch.Equals( "-L" ) ) - nState = STATE_LANGUAGES; - else if ( sSwitch.Equals( "-F" ) ) - nState = STATE_FILENAME; - else if ( sSwitch.Equals( "-QQ" )) - bQuiet2 = true; - else if ( ByteString( argv[ i ]).ToUpperAscii().Equals( "-O" ) ) - nState = STATE_OUTPUT; - else { - switch ( nState ) { - case STATE_NONE: - return Error(); - case STATE_OUTPUT: - if ( sOutput.Len()) - return Error(); - sOutput = ByteString( argv[ i ] ); - nState = STATE_NONE; - break; - case STATE_LANGUAGES: - if ( sLanguages.Len()) - return Error(); - sLanguages = ByteString( argv[ i ] ); - nState = STATE_NONE; - break; - case STATE_FILENAME: - if ( sFileName.Len()) - return Error(); - sFileName = ByteString( argv[ i ] ); - nState = STATE_NONE; - break; - default: - return Error(); - } - } - } - if ( !bMerge && !bExport ) { - Help(); - return 1; - } - - ByteString sSolarVer( Export::GetEnv( "WORK_STAMP" )); - ByteString sVersion( Export::GetEnv( "WORK_STAMP" )); - - if ( !sSolarVer.Len() || !sVersion.Len()) { - fprintf( stderr, "ERROR: No environment set!\n" ); - return 1; - } - - if ( !CheckLanguages( sLanguages )) - return 2; - - if ( !sFileName.Len()) { - fprintf( stderr, "ERROR: No filename given\n" ); - return 3; - } - - DirEntry aEntry( String( sFileName , RTL_TEXTENCODING_ASCII_US )); - aEntry.ToAbs(); - String sFullEntry = aEntry.GetFull(); - ByteString sFileABS( aEntry.GetFull(), gsl_getSystemTextEncoding()); - //printf("B %s\nA %s\n",rDestinationFile.GetBuffer(), sFile.GetBuffer()); - sFileName = sFileABS; - - Treeconfig treeconfig; - vector repos; - bool hasPwd = treeconfig.getActiveRepositories( repos ); - if( hasPwd ) cout << "Found special path!\n"; - - string minor_ext; - bool has_minor_ext; - - if( Export::GetEnv("UPDMINOREXT") != NULL ) - { - minor_ext = string( Export::GetEnv("UPDMINOREXT") ); - has_minor_ext = minor_ext.size(); - } - else - has_minor_ext = false; - - // localize through all repositories - for( vector::iterator iter = repos.begin(); iter != repos.end() ; ++iter ) - { - string curRepository; - if( has_minor_ext ) - curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter + minor_ext; - else - curRepository = string( Export::GetEnv("SOURCE_ROOT_DIR") ) + "/" + *iter; - cout << "Localizing repository " << curRepository << "\n"; - SourceTreeLocalizer aIter( ByteString( curRepository.c_str() ) , sVersion , (sOutput.Len() > 0) , bQuiet2 , bSkipLinks ); - aIter.SetLanguageRestriction( sLanguages ); - if ( bExport ){ - if( bQuiet2 ){ /*printf("");*/fflush( stdout );} - aIter.Extract( sFileName ); - if( bQuiet2 ){ printf("\n %d files found!\n",aIter.GetFileCnt());} - } - } - if( hasPwd ) - { - string pwd; - Export::getCurrentDir( pwd ); - cout << "Localizing repository " << pwd << "\n"; - SourceTreeLocalizer aIter( ByteString( pwd.c_str() ) , sVersion , (sOutput.Len() > 0) , bQuiet2 , bSkipLinks ); - aIter.SetLanguageRestriction( sLanguages ); - if ( bExport ){ - if( bQuiet2 ){ /*printf("");*/fflush( stdout );} - aIter.Extract( sFileName ); - if( bQuiet2 ){ printf("\n %d files found!\n",aIter.GetFileCnt());} - } - - } - - return 0; -} - diff --git a/transex3/source/makefile.mk b/transex3/source/makefile.mk deleted file mode 100644 index a557b210aad0..000000000000 --- a/transex3/source/makefile.mk +++ /dev/null @@ -1,210 +0,0 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: makefile.mk,v $ -# -# $Revision: 1.46 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -PRJ=.. - -INCPRE=$(MISC) - -PRJNAME=transex3 -TARGET=transex -TARGETTYPE=CUI -LIBTARGET=no -# --- Settings ----------------------------------------------------- -ENABLE_EXCEPTIONS=TRUE - -.INCLUDE : settings.mk -CDEFS+= -DYY_NEVER_INTERACTIVE=1 -#CDEFS+= -pg - -.IF "$(SYSTEM_EXPAT)" == "YES" -CFLAGS+=-DSYSTEM_EXPAT -.ENDIF - - -# --- Files -------------------------------------------------------- - -OBJFILES= \ - $(OBJ)$/export.obj \ - $(OBJ)$/export2.obj \ - $(OBJ)$/merge.obj \ - $(OBJ)$/srciter.obj \ - $(OBJ)$/utf8conv.obj \ - $(OBJ)$/xmlparse.obj \ - $(OBJ)$/helpmerge.obj \ - $(OBJ)$/helpex.obj \ - $(OBJ)$/file.obj \ - $(OBJ)$/directory.obj - - -LIB1TARGET= $(LB)$/$(TARGET).lib -LIB1ARCHIV= $(LB)$/libtransex.a -#LIB1FILES= $(LB)$/transex3.lib -LIB1OBJFILES= $(OBJ)$/export.obj \ - $(OBJ)$/export2.obj \ - $(OBJ)$/merge.obj \ - $(OBJ)$/srciter.obj \ - $(OBJ)$/file.obj \ - $(OBJ)$/directory.obj \ - $(OBJ)$/utf8conv.obj - - -APP1VERSIONMAP=exports.map - -# extractor and merger for *.src and *.hrc -APP1TARGET= transex3 -#APP1OBJS= $(OBJ)$/src_yy.obj -APP1OBJS= $(OBJ)$/src_yy_wrapper.obj - -APP1STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) - -.IF "$(OS)"=="MACOSX" -# static libs at end for OS X -.ENDIF - -APP1LIBS+= $(LB)$/$(TARGET).lib -APP1DEPN= $(OBJ)$/src_yy_wrapper.obj $(LB)$/$(TARGET).lib - -APP2TARGET= helpex -APP2OBJS= $(OBJ)$/helpmerge.obj $(OBJ)$/xmlparse.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj $(OBJ)$/merge.obj $(OBJ)$/helpex.obj -APP2RPATH= NONE - -.IF "$(OS)"!="MACOSX" -.ENDIF - -APP2STDLIBS+=$(SALLIB) $(EXPATASCII3RDLIB) $(TOOLSLIB) $(VOSLIB) - -.IF "$(OS)"=="MACOSX" -# static libs at end for OS X -.ENDIF - -# extractor and merger for *.lng and *.lng -APP3TARGET= ulfex -APP3OBJS= $(OBJ)$/lngmerge.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/lngex.obj $(OBJ)$/utf8conv.obj -APP3RPATH= NONE - -.IF "$(OS)"!="MACOSX" -#APP3STDLIBS+= $(BTSTRPLIB) -.ENDIF -APP3STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) -.IF "$(OS)"=="MACOSX" -# static libs at end for OS X -.ENDIF - -# encoding converter for *.gsi -APP4TARGET= gsiconv -APP4OBJS= $(OBJ)$/utf8conv.obj $(OBJ)$/gsiconv.obj -APP4STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) - -# tag checker for *.gsi -APP5TARGET= gsicheck -APP5OBJS= $(OBJ)$/gsicheck.obj $(OBJ)$/tagtest.obj -APP5STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) - -# extractor and merger for *.cfg -APP6TARGET= cfgex -APP6OBJS= $(OBJ)$/cfgmerge.obj $(OBJ)$/cfg_yy_wrapper.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj - -.IF "$(OS)"!="MACOSX" -#APP6STDLIBS+= $(BTSTRPLIB) -.ENDIF - -APP6STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) - -.IF "$(OS)"=="MACOSX" -# static libs at end for OS X -.ENDIF - -# extractor and merger for *.xrm -APP7TARGET= xrmex -APP7OBJS= $(OBJ)$/xrmmerge.obj $(OBJ)$/xrm_yy_wrapper.obj $(OBJ)$/merge.obj $(OBJ)$/export2.obj $(OBJ)$/utf8conv.obj -APP7RPATH= NONE - -.IF "$(OS)"!="MACOSX" -.ENDIF - -APP7STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(SALLIB) - -.IF "$(OS)"=="MACOSX" -# static libs at end for OS X -.ENDIF - -# -#APP8TARGET= treeconfig -#APP8OBJS= $(OBJ)$/treeconfig.obj $(OBJ)$/inireader.obj $(OBJ)$/export2.obj -#APP8STDLIBS=$(TOOLSLIB) $(SALLIB) $(VOSLIB) $(ICUINLIB) $(STLPORT) - -# localizer for l10n framework -APP9TARGET= localize_sl -EXCEPTIONSFILES= \ - $(OBJ)$/localize.obj -APP9OBJS= $(OBJ)$/localize.obj $(OBJ)$/utf8conv.obj $(OBJ)$/srciter.obj $(OBJ)$/export2.obj $(OBJ)$/file.obj $(OBJ)$/directory.obj $(OBJ)$/treeconfig.obj $(OBJ)$/inireader.obj - -APP9STDLIBS+= \ - $(TOOLSLIB) \ - $(VOSLIB) \ - $(ICUINLIB) \ - $(ICUUCLIB) \ - $(STLPORTLIB) \ - $(SALLIB) - -DEPOBJFILES=$(APP1OBJS) $(APP2OBJS) $(APP3OBJS) $(APP4OBJS) $(APP5OBJS) $(APP6OBJS) $(APP7OBJS) $(APP8OBJS) $(APP9OBJS) - -# --- Targets ------------------------------------------------------ - -.INCLUDE : target.mk - -$(MISC)$/%_yy.c : %lex.l - flex -l -w -8 -o$@ $< - -# Helper to suppress warnings in lex generated c code, see #i57362# - -$(OBJ)$/src_yy_wrapper.obj: $(MISC)$/src_yy.c -$(OBJ)$/cfg_yy_wrapper.obj: $(MISC)$/cfg_yy.c -$(OBJ)$/xrm_yy_wrapper.obj: $(MISC)$/xrm_yy.c - diff --git a/transex3/source/merge.cxx b/transex3/source/merge.cxx deleted file mode 100644 index ee0f6f459655..000000000000 --- a/transex3/source/merge.cxx +++ /dev/null @@ -1,445 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: merge.cxx,v $ - * $Revision: 1.27.36.3 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include -#include "export.hxx" -#include "utf8conv.hxx" -#include - -using namespace std; - -extern void ConvertHalfwitdhToFullwidth( String& rString ); - -// -// class PFormEntrys -// - -ByteString PFormEntrys::Dump(){ - ByteString sRet( "PFormEntrys\n" ); - //sRet.Append( Export::DumpMap( ByteString("sText") , sText ) ); - //sRet.Append("\n"); - ByteString a("sText"); - if ( sText.size() ) Export::DumpMap( a , sText ); - return sRet; -} - -/*****************************************************************************/ -BOOL PFormEntrys::GetText( ByteString &rReturn, - USHORT nTyp, const ByteString &nLangIndex, BOOL bDel ) -/*****************************************************************************/ -{ - - /*printf("DBG: PFormEntrys::GetText(nId=%s)\n",nLangIndex.GetBuffer() ); - - // DEBUG****************** - ByteStringHashMap::const_iterator idbg; - std::cout << "HASHKEYS : \n"; - for( idbg = sText.begin() ; idbg != sText.end(); ++idbg ) - std::cout << (idbg->first).GetBuffer() << "\n"; - std::cout << "\n\n"; - std::cout << "String sText[ nLangIndex ] = " << sText[ nLangIndex ].GetBuffer() << "\n"; - // DEBUG****************** -*/ - - BOOL bReturn=TRUE; - switch ( nTyp ) { - case STRING_TYP_TEXT : - rReturn = sText[ nLangIndex ]; - if ( bDel ) - sText[ nLangIndex ] = ""; - bReturn = bTextFirst[ nLangIndex ]; - bTextFirst[ nLangIndex ] = FALSE; - break; - case STRING_TYP_HELPTEXT : - rReturn = sHelpText; - break; - case STRING_TYP_QUICKHELPTEXT : - rReturn = sQuickHelpText[ nLangIndex ]; - if ( bDel ) - sQuickHelpText[ nLangIndex ] = ""; - bReturn = bQuickHelpTextFirst[ nLangIndex ]; - bQuickHelpTextFirst[ nLangIndex ] = FALSE; - break; - case STRING_TYP_TITLE : - rReturn = sTitle[ nLangIndex ]; - if ( bDel ) - sTitle[ nLangIndex ] = ""; - bReturn = bTitleFirst[ nLangIndex ]; - bTitleFirst[ nLangIndex ] = FALSE; - break; - } - //printf("Returning '%s'\n",rReturn.GetBuffer()); - return bReturn; -} - - -// -// class MergeData -// - -/*****************************************************************************/ -MergeData::~MergeData() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -PFormEntrys* MergeData::GetPFormEntrys( ResData *pResData ) -/*****************************************************************************/ -{ - - (void) pResData; // FIXME - if( aMap.find( ByteString("HACK") ) != aMap.end() ){ - return aMap[ ByteString("HACK") ]; - } - else{ - return 0; - } -} - -void MergeData::Insert( const ByteString& rPFO , PFormEntrys* pfEntrys ){ - (void) rPFO; // FIXME - aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) ); - -} -ByteString MergeData::Dump(){ - ByteString sRet( "MergeData\n" ); - - printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",sTyp.GetBuffer(),sGID.GetBuffer(),sLID.GetBuffer(), sFilename.GetBuffer() ); - - PFormEntrysHashMap::const_iterator idbg; - for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ - printf("aMap[ %s ] = " ,idbg->first.GetBuffer()); - ( (PFormEntrys*)(idbg->second) )->Dump(); - printf("\n") ; - } - printf("\n") ; - return sRet; -} - -PFormEntrys* MergeData::GetPFObject( const ByteString& rPFO ){ - if( aMap.find( ByteString("HACK") ) != aMap.end() ){ - return aMap[ rPFO ]; - } - else{ - return 0; - } -} - - -/*****************************************************************************/ -PFormEntrys *MergeData::InsertEntry( const ByteString &rPForm ) -/*****************************************************************************/ -{ - PFormEntrys* pFEntrys = new PFormEntrys( rPForm ); - aMap.insert( PFormEntrysHashMap::value_type( rPForm , pFEntrys ) ); - return pFEntrys; -} - -/*****************************************************************************/ -BOOL MergeData::operator==( ResData *pData ) -/*****************************************************************************/ -{ - ByteString sResTyp_upper( pData->sResTyp ); - sResTyp_upper.ToUpperAscii(); - ByteString sTyp_upper( sTyp ); - sTyp_upper.ToUpperAscii(); - - return (( pData->sId == sLID ) && - ( pData->sGId == sGID ) && - ( sResTyp_upper == sTyp_upper ) - ); -} - -// -// class MergeDataFile -// - -#define FFORMAT_UNKNOWN 0x0000 -#define FFORMAT_NEW 0x0001 -#define FFORMAT_OLD 0x0002 - -/*****************************************************************************/ -MergeDataFile::MergeDataFile( const ByteString &rFileName, const ByteString& sFile ,BOOL bErrLog, -// CharSet aCharSet, BOOL bUTF8 , bool bCaseSensitive ) - CharSet aCharSet, bool bCaseSensitive ) - -/*****************************************************************************/ - : bErrorLog( bErrLog ) -{ - - SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); - aInputStream.SetStreamCharSet( aCharSet ); - ByteString sLine; -// printf("\nReading localize.sdf ...\n"); - ByteString sTYP; - ByteString sGID; - ByteString sLID; - ByteString sPFO; - ByteString nLANG; - ByteString sTEXT; - ByteString sQHTEXT; - ByteString sTITLE; - ByteString sHACK("HACK"); - - const ByteString sEmpty(""); - - if( !aInputStream.IsOpen() ) { - printf("Warning : Can't open %s\n", rFileName.GetBuffer()); - //exit( -1 ); - return; - } - while ( !aInputStream.IsEof()) { - xub_StrLen nToks; - aInputStream.ReadLine( sLine ); - sLine = sLine.Convert( RTL_TEXTENCODING_MS_1252, aCharSet ); - - nToks = sLine.GetTokenCount( '\t' ); - if ( nToks == 15 ) { - // Skip all wrong filenames - ByteString filename = sLine.GetToken( 1 , '\t' ); - filename = filename.Copy( filename.SearchCharBackward( "\\" )+1 , filename.Len() ); - - if( sFile.Equals( sEmpty ) || ( !sFile.Equals( sEmpty ) && filename.Equals( sFile ) ) ) - { - xub_StrLen rIdx = 0; - sTYP = sLine.GetToken( 3, '\t', rIdx ); - sGID = sLine.GetToken( 0, '\t', rIdx ); // 4 - sLID = sLine.GetToken( 0, '\t', rIdx ); // 5 - sPFO = sLine.GetToken( 1, '\t', rIdx ); // 7 - sPFO = sHACK; - nLANG = sLine.GetToken( 1, '\t', rIdx ); // 9 - sTEXT = sLine.GetToken( 0, '\t', rIdx ); // 10 - - sQHTEXT = sLine.GetToken( 1, '\t', rIdx ); // 12 - sTITLE = sLine.GetToken( 0, '\t', rIdx ); // 13 - - nLANG.EraseLeadingAndTrailingChars(); - -#ifdef MERGE_SOURCE_LANGUAGES - if( true ){ -#else - if ( !nLANG.EqualsIgnoreCaseAscii("en-US") ){ -#endif - ByteStringHashMap::const_iterator lit; - lit = aLanguageMap.find (nLANG); - ByteString aLANG; - if (lit == aLanguageMap.end()) { - aLANG = nLANG; - aLanguageMap.insert( ByteStringHashMap::value_type( aLANG, aLANG ) ); - // Remember read languages for -l all switch - aLanguageList.push_back( nLANG ); - } else - aLANG = lit->first; - - InsertEntry( sTYP, sGID, sLID, sPFO, aLANG, sTEXT, sQHTEXT, sTITLE , filename , bCaseSensitive ); - } - } - } - else if ( nToks == 10 ) { - printf("ERROR: File format is obsolete and no longer supported!\n"); - } - } - aInputStream.Close(); -} -/*****************************************************************************/ -MergeDataFile::~MergeDataFile() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -//void MergeDataFile::WriteErrorLog( const ByteString &rFileName ) -/*****************************************************************************/ -//{ -// DEAD -//} - -ByteString MergeDataFile::Dump(){ - ByteString sRet( "MergeDataFile\n" ); - - //sRet.Append( Export::DumpMap( "aLanguageSet" , aLanguageSet ) ); - //sRet.Append( Export::DumpMap( "aLanguageList" , aLanguageList ) ); - printf("MergeDataFile\n"); - MergeDataHashMap::const_iterator idbg; - for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg ){ - /*sRet.Append( "aMap[" ); - sRet.Append( idbg->first ); - sRet.Append( "]= " ); - sRet.Append( ((MergeData*) (idbg->second))->Dump() ); - sRet.Append("\n");*/ - - printf("aMap[ %s ] = ",idbg->first.GetBuffer()); - ((MergeData*) (idbg->second))->Dump(); - printf("\n"); - } - printf("\n"); - //sRet.Append("\n"); - return sRet; -} - -/*****************************************************************************/ -void MergeDataFile::WriteError( const ByteString &rLine ) -/*****************************************************************************/ -{ - if ( bErrorLog ) { - if ( !aErrLog.IsOpen()) - aErrLog.Open( String( sErrorLog, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); - aErrLog.WriteLine( rLine ); - } - else - fprintf( stderr, "%s\n", rLine.GetBuffer()); -} -std::vector MergeDataFile::GetLanguages(){ - return aLanguageList; -} - -/*****************************************************************************/ -MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive ) -/*****************************************************************************/ -{ - ByteString sOldG = pResData->sGId; - ByteString sOldL = pResData->sId; - ByteString sGID = pResData->sGId; - ByteString sLID; - if ( !sGID.Len()) - sGID = pResData->sId; - else - sLID = pResData->sId; - pResData->sGId = sGID; - pResData->sId = sLID; - - ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive ); - - //printf("DBG: Searching [%s]\n",sKey.GetBuffer()); - if( aMap.find( sKey ) != aMap.end() ){ - pResData->sGId = sOldG; - pResData->sId = sOldL; - //printf("DBG: Found[%s]\n",sKey.GetBuffer()); - return aMap[ sKey ]; - } - pResData->sGId = sOldG; - pResData->sId = sOldL; - //printf("DBG: Found[%s]\n",sKey.GetBuffer()); - return NULL; -} - - -/*****************************************************************************/ -PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData ) -/*****************************************************************************/ -{ - // search for requested PFormEntrys - MergeData *pData = GetMergeData( pResData ); - if ( pData ) - return pData->GetPFormEntrys( pResData ); - return NULL; -} - -/*****************************************************************************/ -PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData ) -/*****************************************************************************/ -{ - // search for requested PFormEntrys - MergeData *pData = GetMergeData( pResData , true ); - if ( pData ) - return pData->GetPFormEntrys( pResData ); - return NULL; -} -/*****************************************************************************/ -void MergeDataFile::InsertEntry( - const ByteString &rTYP, const ByteString &rGID, - const ByteString &rLID, const ByteString &rPFO, - const ByteString &nLANG, const ByteString &rTEXT, - const ByteString &rQHTEXT, const ByteString &rTITLE , - const ByteString &rInFilename , bool bCaseSensitive - ) -/*****************************************************************************/ -{ - MergeData *pData; - BOOL bFound = FALSE; - - // uniquify the filename to save memory. - ByteStringHashMap::const_iterator fit = aFilenames.find (rInFilename); - ByteString aFilename; - if (fit == aFilenames.end()) { - aFilename = rInFilename; - aFilenames.insert (ByteStringHashMap::value_type (aFilename, aFilename)); - } else - aFilename = fit->first; - - // search for MergeData - - ByteString sKey = CreateKey( rTYP , rGID , rLID , aFilename , bCaseSensitive ); - MergeDataHashMap::const_iterator mit; - mit = aMap.find( sKey ); - if( mit != aMap.end() ){ - pData = mit->second; - }else{ - pData = new MergeData( rTYP, rGID, rLID, aFilename ); - aMap.insert( MergeDataHashMap::value_type( sKey, pData ) ); - } - - bFound = FALSE; - PFormEntrys *pFEntrys = 0; - - // search for PFormEntrys - - pFEntrys = pData->GetPFObject( rPFO ); - if( !pFEntrys ){ - // create new PFormEntrys, cause no one exists with current properties - pFEntrys = new PFormEntrys( rPFO ); - pData->Insert( rPFO , pFEntrys ); - } - - // finaly insert the cur string - - pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE ); - - //printf("DBG: MergeDataFile::Insert[]=( sKey=%s,nLang=%s,rTEXT=%s)\n",sKey2.GetBuffer(),nLANG.GetBuffer(),rTEXT.GetBuffer()); -} -ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive ){ - - ByteString sKey( rTYP ); - sKey.Append( '-' ); - sKey.Append( rGID ); - sKey.Append( '-' ); - sKey.Append( rLID ); - sKey.Append( '-' ); - sKey.Append( rFilename ); - - if( bCaseSensitive ) return sKey; // officecfg case sensitive identifier - else return sKey.ToUpperAscii(); -} - - diff --git a/transex3/source/src_yy_wrapper.c b/transex3/source/src_yy_wrapper.c deleted file mode 100644 index d326b9a94e86..000000000000 --- a/transex3/source/src_yy_wrapper.c +++ /dev/null @@ -1,2 +0,0 @@ -// Helper to suppress warnings in lex generated c code, see #i57362# -#include "src_yy.c" diff --git a/transex3/source/srciter.cxx b/transex3/source/srciter.cxx deleted file mode 100644 index d2cbb2352570..000000000000 --- a/transex3/source/srciter.cxx +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: srciter.cxx,v $ - * $Revision: 1.14 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" - -#include "srciter.hxx" -#include -#include - -// -// class SourceTreeIterator -// - -/*****************************************************************************/ -SourceTreeIterator::SourceTreeIterator( - const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in ) -/*****************************************************************************/ - : bInExecute( FALSE ) , bLocal( bLocal_in ) -{ - (void) rVersion ; - - if(!bLocal){ - rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 ); - aRootDirectory = transex::Directory( sRootDirectory ); - } -} - -/*****************************************************************************/ -SourceTreeIterator::~SourceTreeIterator() -/*****************************************************************************/ -{ -} - -/*****************************************************************************/ -void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory ) -/*****************************************************************************/ -{ - if ( bInExecute ) { - rtl::OUString sDirName = aDirectory.getDirectoryName(); - - static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) ); - static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) ); - static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) ); - static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) ); - static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) ); - static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) ); - static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) ); - - - if( sDirName.indexOf( WCARD1 , 0 ) > -1 || - sDirName.indexOf( WCARD2 , 0 ) > -1 || - sDirName.indexOf( WCARD3 , 0 ) > -1 || - sDirName.indexOf( WCARD4 , 0 ) > -1 || - sDirName.indexOf( WCARD5 , 0 ) > -1 || - sDirName.indexOf( WCARD6 , 0 ) > -1 || - sDirName.indexOf( WCARD7 , 0 ) > -1 - ) return; - //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); - - rtl::OUString sDirNameTmp = aDirectory.getFullName(); - ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); - -#ifdef WNT - sDirNameTmpB.Append( ByteString("\\no_localization") ); -#else - sDirNameTmpB.Append( ByteString("/no_localization") ); -#endif - //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); - - DirEntry aDE( sDirNameTmpB.GetBuffer() ); - if( aDE.Exists() ) - { - //printf("#### no_localization file found ... skipping"); - return; - } - - aDirectory.setSkipLinks( bSkipLinks ); - aDirectory.readDirectory(); - OnExecuteDirectory( aDirectory.getFullName() ); - if ( aDirectory.getSubDirectories().size() ) - for ( ULONG i=0;i < aDirectory.getSubDirectories().size();i++ ) - ExecuteDirectory( aDirectory.getSubDirectories()[ i ] ); - } -} - -/*****************************************************************************/ -BOOL SourceTreeIterator::StartExecute() -/*****************************************************************************/ -{ - - bInExecute = TRUE; // FIXME - ExecuteDirectory( aRootDirectory ); - - if ( bInExecute ) { // FIXME - bInExecute = FALSE; - return TRUE; - } - return FALSE; -} - -/*****************************************************************************/ -void SourceTreeIterator::EndExecute() -/*****************************************************************************/ -{ - bInExecute = FALSE; -} - -/*****************************************************************************/ -void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory ) -/*****************************************************************************/ -{ - fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() ); -} diff --git a/transex3/source/srclex.l b/transex3/source/srclex.l deleted file mode 100644 index fef251e47224..000000000000 --- a/transex3/source/srclex.l +++ /dev/null @@ -1,308 +0,0 @@ - -%{ -/* - * lexer for parsing ressource source files (*.src) - * - */ - - -/* enlarge token buffer to tokenize whole strings */ -#undef YYLMAX -#define YYLMAX 64000 - -/* to enable debug output define LEXDEBUG */ -#define LEXDEBUG 1 -#ifdef LEXDEBUG -#define OUTPUT fprintf -#else -#define OUTPUT(Par1,Par2); -#endif - -/* table of possible token ids */ -#include "tokens.h" -#include -#include - -#if defined __GNUC__ -#pragma GCC system_header -#elif defined __SINPRO_CC -#pragma disable_warn -#elif defined _MSC_VER -#pragma warning(push, 1) -#endif - -/* external functions (C++ code, declared as extren "C" */ -extern int WorkOnTokenSet( int, char* ); -extern int InitExport( char * , char * ); -extern int Parse( int nTyp, char *pTokenText ); -extern int EndExport(); -extern int SetError(); -extern int GetError(); -extern char *GetOutputFile( int argc, char* argv[]); -extern FILE *GetNextFile(); -extern int isQuiet(); -extern void Close(); -extern char* getFilename(); - -/* forwards */ -void YYWarning(); -%} - -%p 24000 -%e 1200 -%n 500 - -%% - -^[\t ]*"#pragma".* { - WorkOnTokenSet( PRAGMA, yytext ); -} - -^[ \t]*\n { - WorkOnTokenSet( EMPTYLINE, yytext ); -} - -[\t ]+ | -^[\t ]*"#include".* | -^[\t ]*"#undef".* | -"//".* | -";" | -"<" | -">" | -\n { - WorkOnTokenSet( IGNOREDTOKENS, yytext ); -} -"/*" { - char c1 = 0, c2 = input(); - char pChar[2]; - pChar[1] = 0x00; - pChar[0] = c2; - - WorkOnTokenSet( COMMEND, yytext ); - WorkOnTokenSet( COMMEND, pChar ); - for(;;) { - if ( c2 == EOF ) - break; - if ( c1 == '*' && c2 == '/' ) - break; - c1 = c2; - c2 = input(); - pChar[0] = c2; - WorkOnTokenSet( COMMEND, pChar ); - } -} - -^[\t ]*"#ifndef".+$ | -^[\t ]*"#ifdef".+$ | -^[\t ]*"#if".+$ | -^[\t ]*"#elif".*$ | -^[\t ]*"#else".*$ | -^[\t ]*"#endif".*$ { - WorkOnTokenSet( CONDITION, yytext ); -} - -[a-zA-Z]+[\t ]+[^={\n]+[\t ] { -/* defined Res */ - WorkOnTokenSet( DEFINEDRES, yytext ); -} - -[a-zA-Z]+[ \t]+[^={;\n]+\n[ \t]*"#".*\n[ \t]*"{" | -[a-zA-Z]+[ \t]+[^={;\n]+\n?([ \t]*"//".*\n)*[ \t]*"{" { -/* RESSOURCE // String TTT_XX ... */ - WorkOnTokenSet( RESSOURCE, yytext ); -} - -^[\t ]*[a-zA-Z_]+[\t ]*"\\"?[\t ]*\n?[ \t]*"{"[\t ]*"\\"? { -/* SMALRESSOURCE // String ... */ - WorkOnTokenSet( SMALRESSOURCE, yytext ); -} - -[\t ]*[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?=[ \t]*L?\".*\".*\n? { -/* TEXTLINE // TextTyp = "A Text" */ - WorkOnTokenSet( TEXTLINE, yytext ); -} - -[\t ]*[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?(\n[ \t]*)?=([ \t]*\n)?(([a-zA-Z0-9_]+)|(\".*\")|([ \t\n]*))*\".*\"(([a-zA-Z0-9_]+)|(\".*\")|([ \t\n]*))*; { -/* LONGTEXTLINE // TextTyp = "A Text" HHH_XXX "A Text" ZZZ_TTT ... */ - WorkOnTokenSet( LONGTEXTLINE, yytext ); -} - -\".*\" { -/* TEXT // "A Text" */ - WorkOnTokenSet( TEXT, yytext ); -} - -"{"[ \t]*\\? { -/* LEVELUP */ - WorkOnTokenSet( LEVELUP, yytext ); -} - -"}"[ \t]*;([ \t]*\\)? { -/* LEVELDOWN */ - WorkOnTokenSet( LEVELDOWN, yytext ); -} - -[a-zA-Z0-9_]+[ \t]*"="[ \t]*"MAP_APPFONT"[ \t]*"(".+")".* { -/* APPFONTMAPPING Typ = MAP_APPFONT( ... ) */ - WorkOnTokenSet( APPFONTMAPPING, yytext ); -} - -[ \t]*[a-zA-Z0-9_]+[ \t]*=[ \t]*[0123456789]{1,5}[ \t]*";"?\\? { -/* TEXTREFID // TextTyp = 12345 */ - WorkOnTokenSet( TEXTREFID, yytext ); -} - -[a-zA-Z0-9_]+[ \t]*"="[\t ]*([ \t]*"//".*\n)*.* | -[a-zA-Z0-9_]+[ \t]*"=".* { -/* ASSIGNMENT Typ = ... */ - WorkOnTokenSet( ASSIGNMENT, yytext ); -} - - - -[a-zA-Z0-9_]+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{"[ \t]*(\\[ \t]*)?\n?[ \t]*"<" { -/* LISTASSIGNMENT Typ [ ... ] = ... */ - WorkOnTokenSet( LISTASSIGNMENT, yytext ); -} - -"StringList"+[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{"[ \t]*(\\[ \t]*)?\n?[ \t]* { -/* LISTASSIGNMENT Typ [ ... ] = ... */ - WorkOnTokenSet( LISTASSIGNMENT, yytext ); -} - -"UIEntries"[ \t]*("["[ \t]*[a-zA-Z0-9_\-]+[ \t]*"]"[ \t]*)?"="[ \t]*(\\[ \t]*)?\n?[ \t]*"{" { -/* UIENTRIES */ - WorkOnTokenSet( UIENTRIES, yytext ); -} - -"<"?[ \t]*L?\".*\".*">" { -/* LISTTEXT */ - WorkOnTokenSet( LISTTEXT, yytext ); -} - -[ \t]*"#define"[ \t]+[a-zA-Z0-9_]+.*"\\" { -/* RSCDEFINE #define ... */ - WorkOnTokenSet( RSCDEFINE, yytext ); -} - -[ \t]*"#define"[ \t]+[a-zA-Z0-9_]+.+ { -/* #define ... */ - WorkOnTokenSet( NORMDEFINE, yytext ); -} - -"\\" { -/* RSCDEFINELEND */ - WorkOnTokenSet( RSCDEFINELEND, yytext ); -} - -[a-zA-Z0-9_]+[ \t]*; { -/* allowed other tokens like "49 ;" or "SFX_... ;" */ - WorkOnTokenSet( ANYTOKEN, yytext ); -} - -. { - WorkOnTokenSet( UNKNOWNCHAR, yytext ); -/* YYWarning( "Unknown Char" ); */ -} - -"{"?[ \t]*\".*\"[ \t]*";"[ \t]*"}" { -/* _LISTTEXT */ - WorkOnTokenSet( _LISTTEXT, yytext ); -} - -%% - -/*****************************************************************************/ -int yywrap(void) -/*****************************************************************************/ -{ - FILE *pFile; - pFile = GetNextFile(); - if ( pFile ) { - yyin = pFile; - yylineno = 0; - return 0; - } - - /* end of input reached */ - return 1; -} - -/*****************************************************************************/ -void YYWarning( char *s ) -/*****************************************************************************/ -{ - /* write warning to stderr */ - fprintf( stderr, "Warning: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); -} - -/*****************************************************************************/ -void yyerror( char *s ) -/*****************************************************************************/ -{ - /* write error to stderr */ - fprintf( stderr, "Error: \"%s\" in line %d: \"%s\"\n", s, yylineno, yytext ); - SetError(); -} - -/*****************************************************************************/ -int -#ifdef WNT -_cdecl -#endif -main( int argc, char* argv[]) -/*****************************************************************************/ -{ - /* error level */ - int nRetValue = 0; - char *pOutput; - FILE *pFile; - - pOutput = GetOutputFile( argc, argv ); - if( !isQuiet() ){ - fprintf( stdout, "\nTransEx 3.1 Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.\n" ); - fprintf( stdout, "========================================================================\n" ); - } - - if ( !pOutput ) { - fprintf( stdout, "Syntax:TRANSEX[-p Prj][-r PrjRoot]-i FileIn...[-o FileOut][-m DataBase][-e][-b][-u][-L l1,l2,...]\n" ); - fprintf( stdout, " Prj: Project\n" ); - fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" ); - fprintf( stdout, " FileIn: Source files (*.src)\n" ); - fprintf( stdout, " FileOut: Destination file (*.*)\n" ); - fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" ); - fprintf( stdout, " -QQ: quiet output\n" ); - fprintf( stdout, " -e: Disable writing errorlog\n" ); - fprintf( stdout, " -b: Break when Token \"HelpText\" found in source\n" ); - fprintf( stdout, " -u: [english] and [german] are allowed, Id is Taken from DataBase \n" ); - fprintf( stdout, " -NOUTF8: disable UTF8 as language independent encoding\n" ); - fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (de,en-US...)\n" ); - fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" ); - fprintf( stdout, " f1, f2,... are also elements of (de,en-US...)\n" ); - fprintf( stdout, " Example: -L de,es=en-US\n" ); - fprintf( stdout, " Restriction to de and es, en-US will be fallback for es\n" ); - return 1; - } - - InitExport( pOutput , getFilename() ); - pFile = GetNextFile(); - if ( !pFile ) - return 1; - - yyin = pFile; - - /* create global instance of class Export */ - - /* start parser */ - yylex(); - Close(); - - /* get error info. and end export */ - nRetValue = GetError(); - EndExport(); - - if( !isQuiet() ) fprintf( stdout, "\n===================================\n\n" ); - - /* return error level */ - return nRetValue; -} diff --git a/transex3/source/tagtest.cxx b/transex3/source/tagtest.cxx deleted file mode 100644 index 89c1ecf15488..000000000000 --- a/transex3/source/tagtest.cxx +++ /dev/null @@ -1,1577 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: tagtest.cxx,v $ - * $Revision: 1.20 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include -#include "tagtest.hxx" - -#if OSL_DEBUG_LEVEL > 1 -#include -#endif - -#include "gsicheck.hxx" - -#define HAS_FLAG( nFlags, nFlag ) ( ( nFlags & nFlag ) != 0 ) -#define SET_FLAG( nFlags, nFlag ) ( nFlags |= nFlag ) -#define RESET_FLAG( nFlags, nFlag ) ( nFlags &= ~nFlag ) // ~ = Bitweises NOT - - - -TokenInfo::TokenInfo( TokenId pnId, USHORT nP, String paStr, ParserMessageList &rErrorList ) -: bClosed(FALSE) -, bCloseTag(FALSE) -, bIsBroken(FALSE) -, bHasBeenFixed(FALSE) -, bDone(FALSE) -, aTokenString( paStr ) -, nId( pnId ) -, nPos(nP) -{ - if ( nId == TAG_COMMONSTART || nId == TAG_COMMONEND ) - SplitTag( rErrorList ); -} - -enum tagcheck { TC_START, TC_HAS_TAG_NAME, TC_HAS_PROP_NAME_EQ, TC_HAS_PROP_NAME_EQ_SP, TC_HAS_PROP_NAME_SP, TC_INSIDE_STRING, TC_PROP_FINISHED, TC_CLOSED, TC_CLOSED_SPACE, TC_CLOSETAG, TC_CLOSETAG_HAS_TAG_NAME, TC_FINISHED, TC_ERROR }; - -/* - \< link href = \"text\" name = \"C\" \> -START ' ' -> HAS_TAG_NAME -START '/' -> CLOSED -START '/' -> CLOSETAG - no Portion (starting with /) -START '>' -> FINISHED -HAS_TAG_NAME '=' -> HAS_PROP_NAME_EQ -HAS_TAG_NAME ' ' -> HAS_PROP_NAME_SP -HAS_TAG_NAME '/' -> CLOSED -HAS_TAG_NAME '>' -> FINISHED -HAS_PROP_NAME_SP '=' -> HAS_PROP_NAME_EQ -HAS_PROP_NAME_EQ ' ' -> HAS_PROP_NAME_EQ_SP -HAS_PROP_NAME_EQ '"' -> INSIDE_STRING -HAS_PROP_NAME_EQ_SP '"' -> INSIDE_STRING -INSIDE_STRING ' ' -> INSIDE_STRING -INSIDE_STRING '=' -> INSIDE_STRING -INSIDE_STRING '>' -> INSIDE_STRING -INSIDE_STRING '"' -> PROP_FINISHED -PROP_FINISHED ' ' -> HAS_TAG_NAME -PROP_FINISHED '/' -> CLOSED -PROP_FINISHED '>' -> FINISHED -CLOSED ' ' -> CLOSED_SPACE -CLOSED '>' -> FINISHED -CLOSED_SPACE '>' -> FINISHED - -CLOSETAG ' ' -> CLOSETAG_HAS_TAG_NAME -CLOSETAG '>' -> FINISHED -CLOSETAG_HAS_TAG_NAME '>' -> FINISHED - -*/ -void TokenInfo::SplitTag( ParserMessageList &rErrorList ) -{ - USHORT nLastPos = 2; // skip initial \< - USHORT nCheckPos = nLastPos; - String aDelims( String::CreateFromAscii( " \\=>/" ) ); - String aPortion; - String aValue; // store the value of a property - ByteString aName; // store the name of a property/tag - BOOL bCheckName = FALSE; - BOOL bCheckEmpty = FALSE; - sal_Unicode cDelim; - tagcheck aState = TC_START; - - // skip blanks - while ( nLastPos < aTokenString.Len() && aTokenString.GetChar( nLastPos ) == ' ') - nLastPos++; - - nCheckPos = aTokenString.SearchChar( aDelims.GetBuffer(), nLastPos ); - while ( nCheckPos != STRING_NOTFOUND && !( aState == TC_FINISHED || aState == TC_ERROR ) ) - { - aPortion = aTokenString.Copy( nLastPos, nCheckPos-nLastPos ); - - if ( aTokenString.GetChar( nCheckPos ) == '\\' ) - nCheckPos++; - - cDelim = aTokenString.GetChar( nCheckPos ); - nCheckPos++; - - switch ( aState ) - { -// START ' ' -> HAS_TAG_NAME -// START '/' -> CLOSED -// START '>' -> FINISHED - case TC_START: - aTagName = aPortion; - switch ( cDelim ) - { - case ' ': aState = TC_HAS_TAG_NAME; - bCheckName = TRUE; - break; - case '/': - { - if ( aPortion.Len() == 0 ) - { - aState = TC_CLOSETAG; - } - else - { - aState = TC_CLOSED; - bCheckName = TRUE; - } - } - break; - case '>': aState = TC_FINISHED; - bCheckName = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// HAS_TAG_NAME '=' -> HAS_PROP_NAME_EQ -// HAS_TAG_NAME ' ' -> HAS_PROP_NAME_SP -// HAS_TAG_NAME '/' -> CLOSED -// HAS_TAG_NAME '>' -> FINISHED - case TC_HAS_TAG_NAME: - switch ( cDelim ) - { - case '=': aState = TC_HAS_PROP_NAME_EQ; - bCheckName = TRUE; - break; - case ' ': aState = TC_HAS_PROP_NAME_SP; - bCheckName = TRUE; - break; - case '/': aState = TC_CLOSED; - bCheckEmpty = TRUE; - break; - case '>': aState = TC_FINISHED; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// HAS_PROP_NAME_SP '=' -> HAS_PROP_NAME_EQ - case TC_HAS_PROP_NAME_SP: - switch ( cDelim ) - { - case '=': aState = TC_HAS_PROP_NAME_EQ; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// HAS_PROP_NAME_EQ ' ' -> HAS_PROP_NAME_EQ_SP -// HAS_PROP_NAME_EQ '"' -> INSIDE_STRING - case TC_HAS_PROP_NAME_EQ: - switch ( cDelim ) - { - case ' ': aState = TC_HAS_PROP_NAME_EQ_SP; - bCheckEmpty = TRUE; - break; - case '\"': aState = TC_INSIDE_STRING; - bCheckEmpty = TRUE; - aValue.Erase(); - break; - default: aState = TC_ERROR; - } - break; - -// HAS_PROP_NAME_EQ_SP '"' -> INSIDE_STRING - case TC_HAS_PROP_NAME_EQ_SP: - switch ( cDelim ) - { - case '\"': aState = TC_INSIDE_STRING; - bCheckEmpty = TRUE; - aValue.Erase(); - break; - default: aState = TC_ERROR; - } - break; - -// INSIDE_STRING * -> INSIDE_STRING -// INSIDE_STRING '"' -> PROP_FINISHED - case TC_INSIDE_STRING: - switch ( cDelim ) - { - case '\"': - { - aState = TC_PROP_FINISHED; - aValue += aPortion; - if ( aProperties.find( aName ) == aProperties.end() ) - { - if ( !IsPropertyValueValid( aName, aValue ) ) - { - rErrorList.AddError( 25, ByteString("Property '").Append(aName).Append("' has invalid value '").Append(ByteString( aValue, RTL_TEXTENCODING_UTF8 )).Append("' "), *this ); - bIsBroken = TRUE; - } - aProperties[ aName ] = aValue; - } - else - { - rErrorList.AddError( 25, ByteString("Property '").Append(aName).Append("' defined twice "), *this ); - bIsBroken = TRUE; - } - } - break; - default: - { - aState = TC_INSIDE_STRING; - aValue += aPortion; - aValue += cDelim; - } - } - break; - -// PROP_FINISHED ' ' -> HAS_TAG_NAME -// PROP_FINISHED '/' -> CLOSED -// PROP_FINISHED '>' -> FINISHED - case TC_PROP_FINISHED: - switch ( cDelim ) - { - case ' ': aState = TC_HAS_TAG_NAME; - bCheckEmpty = TRUE; - break; - case '/': aState = TC_CLOSED; - bCheckEmpty = TRUE; - break; - case '>': aState = TC_FINISHED; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// CLOSED ' ' -> CLOSED_SPACE -// CLOSED '>' -> FINISHED - case TC_CLOSED: - switch ( cDelim ) - { - case ' ': aState = TC_CLOSED_SPACE; - bCheckEmpty = TRUE; - bClosed = TRUE; - break; - case '>': aState = TC_FINISHED; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// CLOSED_SPACE '>' -> FINISHED - case TC_CLOSED_SPACE: - switch ( cDelim ) - { - case '>': aState = TC_FINISHED; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// CLOSETAG ' ' -> CLOSETAG_HAS_TAG_NAME -// CLOSETAG '>' -> FINISHED - case TC_CLOSETAG: - bCloseTag = TRUE; - switch ( cDelim ) - { - case ' ': aState = TC_CLOSETAG_HAS_TAG_NAME; - aTagName = aPortion; - bCheckName = TRUE; - break; - case '>': aState = TC_FINISHED; - aTagName = aPortion; - bCheckName = TRUE; - break; - default: aState = TC_ERROR; - } - break; - -// CLOSETAG_HAS_TAG_NAME '>' -> FINISHED - case TC_CLOSETAG_HAS_TAG_NAME: - switch ( cDelim ) - { - case '>': aState = TC_FINISHED; - bCheckEmpty = TRUE; - break; - default: aState = TC_ERROR; - } - break; - - - default: rErrorList.AddError( 99, "Internal error Parsing Tag ", *this ); - bIsBroken = TRUE; - - } - - if ( bCheckName ) - { - if ( aPortion.Len() == 0 ) - { - rErrorList.AddError( 25, "Tag/Property name missing ", *this ); - bIsBroken = TRUE; - } - else - { - aName = ByteString( aPortion, RTL_TEXTENCODING_UTF8 ); - // "a-zA-Z_-.0-9" - xub_StrLen nCount; - BOOL bBroken = FALSE; - const sal_Char* aBuf = aName.GetBuffer(); - for ( nCount = 0 ; !bBroken && nCount < aName.Len() ; nCount++ ) - { - bBroken = ! ( ( aBuf[nCount] >= 'a' && aBuf[nCount] <= 'z' ) - ||( aBuf[nCount] >= 'A' && aBuf[nCount] <= 'Z' ) - ||( aBuf[nCount] >= '0' && aBuf[nCount] <= '9' ) - ||( aBuf[nCount] == '_' ) - ||( aBuf[nCount] == '-' ) - ||( aBuf[nCount] == '.' ) - ); - } - - if ( bBroken ) - { - rErrorList.AddError( 25, "Found illegal character in Tag/Property name ", *this ); - bIsBroken = TRUE; - } - } - - bCheckName = FALSE; - } - - if ( bCheckEmpty ) - { - if ( aPortion.Len() ) - { - rErrorList.AddError( 25, ByteString("Found displaced characters '").Append(ByteString( aPortion, RTL_TEXTENCODING_UTF8 )).Append("' in Tag "), *this ); - bIsBroken = TRUE; - } - bCheckEmpty = FALSE; - } - - - nLastPos = nCheckPos; - - // skip further blanks - if ( cDelim == ' ' && aState != TC_INSIDE_STRING ) - while ( nLastPos < aTokenString.Len() && aTokenString.GetChar( nLastPos ) == ' ') - nLastPos++; - - nCheckPos = aTokenString.SearchChar( aDelims.GetBuffer(), nLastPos ); - } - if ( aState != TC_FINISHED ) - { - rErrorList.AddError( 25, "Parsing error in Tag ", *this ); - bIsBroken = TRUE; - } -} - -BOOL TokenInfo::IsPropertyRelevant( const ByteString &aName, const String &aValue ) const -{ - if ( aTagName.EqualsAscii( "alt" ) && aName.Equals( "xml-lang" ) ) - return FALSE; - if ( aTagName.EqualsAscii( "ahelp" ) && aName.Equals( "visibility" ) && aValue.EqualsAscii("visible") ) - return FALSE; - if ( aTagName.EqualsAscii( "image" ) && (aName.Equals( "width" ) || aName.Equals( "height" )) ) - return FALSE; - - return TRUE; -} - -BOOL TokenInfo::IsPropertyValueValid( const ByteString &aName, const String &aValue ) const -{ -/* removed due to i56740 - if ( aTagName.EqualsAscii( "switchinline" ) && aName.Equals( "select" ) ) - { - return aValue.EqualsAscii("sys") || - aValue.EqualsAscii("appl") || - aValue.EqualsAscii("distrib"); - } */ - if ( aTagName.EqualsAscii( "caseinline" ) && aName.Equals( "select" ) ) - { - return /*!aValue.EqualsAscii("OS2") && removed due to i56740 */ - !aValue.EqualsAscii(""); - } - - // we don't know any better so we assume it to be OK - return TRUE; -} - -BOOL TokenInfo::IsPropertyInvariant( const ByteString &aName, const String &aValue ) const -{ - if ( aTagName.EqualsAscii( "link" ) && aName.Equals( "name" ) ) - return FALSE; - if ( aTagName.EqualsAscii( "link" ) && aName.Equals( "href" ) ) - { // check for external reference - if ( aValue.Copy( 0, 5 ).EqualsIgnoreCaseAscii( "http:" ) - || aValue.Copy( 0, 6 ).EqualsIgnoreCaseAscii( "https:" ) - || aValue.Copy( 0, 4 ).EqualsIgnoreCaseAscii( "ftp:" ) ) - return FALSE; - else - return TRUE; - } - return TRUE; -} - -BOOL TokenInfo::IsPropertyFixable( const ByteString &aName ) const -{ - // name everything that is allowed to be fixed automatically here - if ( (aTagName.EqualsAscii( "ahelp" ) && aName.Equals( "hid" )) - || (aTagName.EqualsAscii( "link" ) && aName.Equals( "href" )) - || (aTagName.EqualsAscii( "alt" ) && aName.Equals( "id" )) - || (aTagName.EqualsAscii( "variable" ) && aName.Equals( "id" )) - || (aTagName.EqualsAscii( "image" ) && aName.Equals( "src" )) - || (aTagName.EqualsAscii( "image" ) && aName.Equals( "id" ) )) - return TRUE; - return FALSE; -} - -BOOL TokenInfo::MatchesTranslation( TokenInfo& rInfo, BOOL bGenErrors, ParserMessageList &rErrorList, BOOL bFixTags ) const -{ - // check if tags are equal - // check if all existing properties are in the translation as well and - // wether they have a matching content (the same in most cases) - - if ( nId != rInfo.nId ) - return FALSE; - - if ( !aTagName.Equals( rInfo.aTagName ) ) - return FALSE; - - // If one of the tags has formating errors already it does make no sense to check here, so return right away - if ( bGenErrors && ( bIsBroken || rInfo.bIsBroken ) ) - return TRUE; - - StringHashMap::const_iterator iProp; - for( iProp = aProperties.begin() ; iProp != aProperties.end(); ++iProp ) - { - if ( rInfo.aProperties.find( iProp->first ) != rInfo.aProperties.end() ) - { - if ( IsPropertyRelevant( iProp->first, iProp->second ) || IsPropertyRelevant( iProp->first, rInfo.aProperties.find( iProp->first )->second ) ) - { - if ( IsPropertyInvariant( iProp->first, iProp->second ) ) - { - if ( !rInfo.aProperties.find( iProp->first )->second.Equals( iProp->second ) ) - { - if ( bGenErrors ) - { - if ( bFixTags && IsPropertyFixable( iProp->first ) ) - { - rInfo.aProperties.find( iProp->first )->second = iProp->second; - rInfo.SetHasBeenFixed(); - rErrorList.AddWarning( 25, ByteString("Property '").Append(iProp->first).Append("': FIXED different value in Translation "), *this ); - } - else - rErrorList.AddError( 25, ByteString("Property '").Append(iProp->first).Append("': value different in Translation "), *this ); - } - else return FALSE; - } - } - } - } - else - { - if ( IsPropertyRelevant( iProp->first, iProp->second ) ) - { - if ( bGenErrors ) - rErrorList.AddError( 25, ByteString("Property '").Append(iProp->first).Append("' missing in Translation "), *this ); - else return FALSE; - } - } - } - for( iProp = rInfo.aProperties.begin() ; iProp != rInfo.aProperties.end(); ++iProp ) - { - if ( aProperties.find( iProp->first ) == aProperties.end() ) - { - if ( IsPropertyRelevant( iProp->first, iProp->second ) ) - { - if ( bGenErrors ) - rErrorList.AddError( 25, ByteString("Extra Property '").Append(iProp->first).Append("' in Translation "), rInfo ); - else return FALSE; - } - } - } - - // if we reach here eather - // the tags match completely or - // the tags match but not the properties and we generated errors for that - return TRUE; -} - -String TokenInfo::GetTagName() const -{ - return aTagName; -} - -String TokenInfo::MakeTag() const -{ - String aRet; - aRet.AppendAscii("\\<"); - if ( bCloseTag ) - aRet.AppendAscii("/"); - aRet.Append( GetTagName() ); - StringHashMap::const_iterator iProp; - - for( iProp = aProperties.begin() ; iProp != aProperties.end(); ++iProp ) - { - aRet.AppendAscii(" "); - aRet.Append( String( iProp->first, RTL_TEXTENCODING_UTF8 ) ); - aRet.AppendAscii("=\\\""); - aRet.Append( iProp->second ); - aRet.AppendAscii("\\\""); - } - if ( bClosed ) - aRet.AppendAscii("/"); - aRet.AppendAscii("\\>"); - return aRet; -} - - -void ParserMessageList::AddError( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ) -{ - Insert( new ParserError( nErrorNr, aErrorText, rTag ), LIST_APPEND ); -} - -void ParserMessageList::AddWarning( USHORT nErrorNr, ByteString aErrorText, const TokenInfo &rTag ) -{ - Insert( new ParserWarning( nErrorNr, aErrorText, rTag ), LIST_APPEND ); -} - -BOOL ParserMessageList::HasErrors() -{ - USHORT i; - for ( i=0 ; i < Count() ; i++ ) - if ( GetObject( i )->IsError() ) - return TRUE; - return FALSE; -} - -struct Tag -{ - String GetName() const { return String::CreateFromAscii( pName ); }; - const char* pName; - TokenId nTag; -}; - - -static const Tag aKnownTags[] = -{ -/* commenting oldstyle tags -// { "<#GROUP_FORMAT>", TAG_GROUP_FORMAT }, - { "<#BOLD>", TAG_BOLDON }, - { "<#/BOLD>", TAG_BOLDOFF }, - { "<#ITALIC>", TAG_ITALICON }, - { "<#/ITALIC>", TAG_ITALICOFF }, - { "<#UNDER>", TAG_UNDERLINEON }, - { "<#/UNDER>", TAG_UNDERLINEOFF }, - -// { "<#GROUP_NOTALLOWED>", TAG_GROUP_NOTALLOWED }, - { "<#HELPID>", TAG_HELPID }, - { "<#MODIFY>", TAG_MODIFY }, - { "<#REFNR>", TAG_REFNR }, - -// { "<#GROUP_STRUCTURE>", TAG_GROUP_STRUCTURE }, - { "<#NAME>", TAG_NAME }, - { "<#HREF>", TAG_HREF }, - { "<#AVIS>", TAG_AVIS }, - { "<#AHID>", TAG_AHID }, - { "<#AEND>", TAG_AEND }, - - { "<#TITEL>", TAG_TITEL }, - { "<#KEY>", TAG_KEY }, - { "<#INDEX>", TAG_INDEX }, - - { "<#REFSTART>", TAG_REFSTART }, - - { "<#GRAPHIC>", TAG_GRAPHIC }, - { "<#NEXTVERSION>", TAG_NEXTVERSION }, - - // { "<#GROUP_SYSSWITCH>", TAG_GROUP_SYSSWITCH }, - { "<#WIN>", TAG_WIN }, - { "<#UNIX>", TAG_UNIX }, - { "<#MAC>", TAG_MAC }, - { "<#OS2>", TAG_OS2 }, - -// { "<#GROUP_PROGSWITCH>", TAG_GROUP_PROGSWITCH }, - { "<#WRITER>", TAG_WRITER }, - { "<#CALC>", TAG_CALC }, - { "<#DRAW>", TAG_DRAW }, - { "<#IMPRESS>", TAG_IMPRESS }, - { "<#SCHEDULE>", TAG_SCHEDULE }, - { "<#IMAGE>", TAG_IMAGE }, - { "<#MATH>", TAG_MATH }, - { "<#CHART>", TAG_CHART }, - { "<#OFFICE>", TAG_OFFICE }, - */ -// { "<#TAG_GROUP_META>", TAG_GROUP_META }, - { "$[officefullname]", TAG_OFFICEFULLNAME }, - { "$[officename]", TAG_OFFICENAME }, - { "$[officepath]", TAG_OFFICEPATH }, - { "$[officeversion]", TAG_OFFICEVERSION }, - { "$[portalname]", TAG_PORTALNAME }, - { "$[portalfullname]", TAG_PORTALFULLNAME }, - { "$[portalpath]", TAG_PORTALPATH }, - { "$[portalversion]", TAG_PORTALVERSION }, - { "$[portalshortname]", TAG_PORTALSHORTNAME }, -/* commenting oldstyle tags -// { "<#TAG_GROUP_SINGLE>", TAG_GROUP_SINGLE }, - { "<#REFINSERT>", TAG_REFINSERT }, - -// { "<#GROUP_MULTI>", TAG_GROUP_MULTI }, - { "<#END>", TAG_END }, - { "<#ELSE>", TAG_ELSE }, - { "<#VERSIONEND>", TAG_VERSIONEND }, - { "<#ENDGRAPHIC>", TAG_ENDGRAPHIC },*/ - { "", TAG_COMMONSTART }, - { "", TAG_COMMONEND }, - - { "", TAG_NOMORETAGS }, - { "", TAG_UNKNOWN_TAG }, -}; - - -SimpleParser::SimpleParser() -: nPos( 0 ) -, aNextTag( TAG_NOMORETAGS, TOK_INVALIDPOS ) -{ -} - -void SimpleParser::Parse( String PaSource ) -{ - aSource = PaSource; - nPos = 0; - aLastToken.Erase(); - aNextTag = TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); - aTokenList.Clear(); -}; - -TokenInfo SimpleParser::GetNextToken( ParserMessageList &rErrorList ) -{ - TokenInfo aResult; - USHORT nTokenStartPos = 0; - if ( aNextTag.nId != TAG_NOMORETAGS ) - { - aResult = aNextTag; - aNextTag = TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); - } - else - { - aLastToken = GetNextTokenString( rErrorList, nTokenStartPos ); - if ( aLastToken.Len() == 0 ) - return TokenInfo( TAG_NOMORETAGS, TOK_INVALIDPOS ); - - // do we have a \< ... \> style tag? - if ( aLastToken.Copy(0,2).EqualsAscii( "\\<" ) ) - { - // check for paired \" \" - bool bEven = true; - USHORT nQuotePos = 0; - USHORT nQuotedQuotesPos = aLastToken.SearchAscii( "\\\"" ); - USHORT nQuotedBackPos = aLastToken.SearchAscii( "\\\\" ); // this is only to kick out quoted backslashes - while ( nQuotedQuotesPos != STRING_NOTFOUND ) - { - if ( nQuotedBackPos <= nQuotedQuotesPos ) - nQuotePos = nQuotedBackPos+2; - else - { - nQuotePos = nQuotedQuotesPos+2; - bEven = !bEven; - } - nQuotedQuotesPos = aLastToken.SearchAscii( "\\\"", nQuotePos ); - nQuotedBackPos = aLastToken.SearchAscii( "\\\\", nQuotePos ); // this is only to kick out quoted backslashes - } - if ( !bEven ) - { - rErrorList.AddError( 24, "Missing quotes ( \\\" ) in Tag", TokenInfo( TAG_UNKNOWN_TAG, nTokenStartPos, aLastToken ) ); - } - - // check if we have an end-tag or a start-tag - USHORT nNonBlankStartPos,nNonBlankEndPos; - nNonBlankStartPos = 2; - while ( aLastToken.GetChar(nNonBlankStartPos) == ' ' ) - nNonBlankStartPos++; - if ( aLastToken.GetChar(nNonBlankStartPos) == '/' ) - aResult = TokenInfo( TAG_COMMONEND, nTokenStartPos, aLastToken, rErrorList ); - else - { - aResult = TokenInfo( TAG_COMMONSTART, nTokenStartPos, aLastToken, rErrorList ); - nNonBlankEndPos = aLastToken.Len() -3; - while ( aLastToken.GetChar(nNonBlankEndPos) == ' ' ) - nNonBlankEndPos--; - if ( aLastToken.GetChar( nNonBlankEndPos ) == '/' ) - aNextTag = TokenInfo( TAG_COMMONEND, nTokenStartPos, String::CreateFromAscii("\\"), rErrorList ); - } - } - else - { - USHORT i = 0; - while ( aKnownTags[i].nTag != TAG_UNKNOWN_TAG && - aLastToken != aKnownTags[i].GetName() ) - i++; - aResult = TokenInfo( aKnownTags[i].nTag, nTokenStartPos ); - } - } - - if ( aResult.nId == TAG_UNKNOWN_TAG ) - aResult = TokenInfo( TAG_UNKNOWN_TAG, nTokenStartPos, aLastToken ); - aTokenList.Insert( aResult, LIST_APPEND ); - return aResult; -} - -String SimpleParser::GetNextTokenString( ParserMessageList &rErrorList, USHORT &rTagStartPos ) -{ -// USHORT nStyle1StartPos = aSource.SearchAscii( "<#", nPos ); - USHORT nStyle2StartPos = aSource.SearchAscii( "$[", nPos ); - USHORT nStyle3StartPos = aSource.SearchAscii( "\\<", nPos ); - USHORT nStyle4StartPos = aSource.SearchAscii( "\\\\", nPos ); // this is only to kick out quoted backslashes - - rTagStartPos = 0; - -/* removing since a \<... is not likely - // check if the tag starts with a letter to avoid things like <> <= ... > - while ( STRING_NOTFOUND != nStyle3StartPos && !( aSource.Copy( nStyle3StartPos+2, 1 ).IsAlphaAscii() || aSource.GetChar( nStyle3StartPos+2 ) == '/' ) ) - nStyle3StartPos = aSource.SearchAscii( "\\<", nStyle3StartPos+1 ); -*/ - if ( STRING_NOTFOUND == nStyle2StartPos && STRING_NOTFOUND == nStyle3StartPos ) - return String(); // no more tokens - - if ( nStyle4StartPos < nStyle2StartPos && nStyle4StartPos <= nStyle3StartPos ) // <= to make sure \\ is always handled first - { // Skip quoted Backslash - nPos = nStyle4StartPos +2; - return GetNextTokenString( rErrorList, rTagStartPos ); - } - -/* if ( nStyle1StartPos < nStyle2StartPos && nStyle1StartPos <= nStyle3StartPos ) // <= to make sure our spechial tags are recognized before all others - { // test for <# ... > style tokens - USHORT nEndPos = aSource.SearchAscii( ">", nStyle1StartPos ); - if ( nEndPos == STRING_NOTFOUND ) - { // Token is incomplete. Skip start and search for better ones - nPos = nStyle1StartPos +2; - return GetNextTokenString( rErrorList, rTagStartPos ); - } - nPos = nEndPos; - rTagStartPos = nStyle1StartPos; - return aSource.Copy( nStyle1StartPos, nEndPos-nStyle1StartPos +1 ).ToUpperAscii(); - } - else*/ if ( nStyle2StartPos < nStyle3StartPos ) - { // test for $[ ... ] style tokens - USHORT nEndPos = aSource.SearchAscii( "]", nStyle2StartPos); - if ( nEndPos == STRING_NOTFOUND ) - { // Token is incomplete. Skip start and search for better ones - nPos = nStyle2StartPos +2; - return GetNextTokenString( rErrorList, rTagStartPos ); - } - nPos = nEndPos; - rTagStartPos = nStyle2StartPos; - return aSource.Copy( nStyle2StartPos, nEndPos-nStyle2StartPos +1 ); - } - else - { // test for \< ... \> style tokens - USHORT nEndPos = aSource.SearchAscii( "\\>", nStyle3StartPos); - USHORT nQuotedBackPos = aSource.SearchAscii( "\\\\", nStyle3StartPos ); // this is only to kick out quoted backslashes - while ( nQuotedBackPos <= nEndPos && nQuotedBackPos != STRING_NOTFOUND ) - { - nEndPos = aSource.SearchAscii( "\\>", nQuotedBackPos +2); - nQuotedBackPos = aSource.SearchAscii( "\\\\", nQuotedBackPos +2 ); // this is only to kick out quoted backslashes - } - if ( nEndPos == STRING_NOTFOUND ) - { // Token is incomplete. Skip start and search for better ones - nPos = nStyle3StartPos +2; - ByteString sTmp( "Tag Start '\\<' without Tag End '\\>': " ); - rErrorList.AddError( 24, "Tag Start '\\<' without Tag End '\\>'", TokenInfo( TAG_UNKNOWN_TAG, nStyle3StartPos, aSource.Copy( nStyle3StartPos-10, 20 ) ) ); - return GetNextTokenString( rErrorList, rTagStartPos ); - } - // check for paired quoted " --> \"sometext\" - - nPos = nEndPos; - rTagStartPos = nStyle3StartPos; - return aSource.Copy( nStyle3StartPos, nEndPos-nStyle3StartPos +2 ); - } -} - -String SimpleParser::GetLexem( TokenInfo const &aToken ) -{ - if ( aToken.aTokenString.Len() ) - return aToken.aTokenString; - else - { - USHORT i = 0; - while ( aKnownTags[i].nTag != TAG_UNKNOWN_TAG && - aKnownTags[i].nTag != aToken.nId ) - i++; - - return aKnownTags[i].GetName(); - } -} - -TokenParser::TokenParser() -: pErrorList( NULL ) -{} - -void TokenParser::Parse( const String &aCode, ParserMessageList* pList ) -{ - pErrorList = pList; - - //Scanner initialisieren - aParser.Parse( aCode ); - - //erstes Symbol holen - aTag = aParser.GetNextToken( *pErrorList ); - - nPfCaseOptions = 0; - nAppCaseOptions = 0; - bPfCaseActive = FALSE; - bAppCaseActive = FALSE; - - nActiveRefTypes = 0; - - //Ausfuehren der Start-Produktion - Paragraph(); - - //Es wurde nicht die ganze Kette abgearbeitet, bisher ist aber - //kein Fehler aufgetreten - //=> es wurde ein einleitendes Tag vergessen - if ( aTag.nId != TAG_NOMORETAGS ) - { - switch ( aTag.nId ) - { - case TAG_END: - { - ParseError( 3, "Extra Tag <#END>. Switch or <#HREF> expected.", aTag ); - } - break; - case TAG_BOLDOFF: - { - ParseError( 4, "<#BOLD> expected before <#/BOLD>.", aTag ); - } - break; - case TAG_ITALICOFF: - { - ParseError( 5, "<#ITALIC> expected before <#/ITALIC>.", aTag ); - } - break; - case TAG_UNDERLINEOFF: - { - ParseError( 17, "<#UNDER> expected before <#/UNDER>.", aTag ); - } - break; -/* case TAG_MISSPARENTHESIS: - { - ParseError( 14, "missing closing parenthesis '>'", aTag ); - } - break;*/ - case TAG_AEND: - { - ParseError( 5, "Extra Tag <#AEND>. <#AVIS> or <#AHID> expected.", aTag ); - } - break; - case TAG_ELSE: - { - ParseError( 16, "Application-tag or platform-tag expected before <#ELSE>.", aTag ); - } - break; - case TAG_UNKNOWN_TAG: - { - ParseError( 6, "unknown Tag", aTag ); - } - break; - default: - { - ParseError( 6, "unexpected Tag", aTag ); - } - } - } - pErrorList = NULL; -} - -void TokenParser::Paragraph() -{ - switch ( aTag.nId ) - { - case TAG_GRAPHIC: - case TAG_NEXTVERSION: - { - TagRef(); - Paragraph(); - } - break; - case TAG_AVIS: - case TAG_AHID: - { - TagRef(); - Paragraph(); - } - break; - case TAG_HELPID: - { - SimpleTag(); - Paragraph(); - } - break; - case TAG_OFFICEFULLNAME: - case TAG_OFFICENAME: - case TAG_OFFICEPATH: - case TAG_OFFICEVERSION: - case TAG_PORTALNAME: - case TAG_PORTALFULLNAME: - case TAG_PORTALPATH: - case TAG_PORTALVERSION: - case TAG_PORTALSHORTNAME: - { - SimpleTag(); - Paragraph(); - } - break; - case TAG_REFINSERT: - { - SimpleTag(); - Paragraph(); - } - break; - case TAG_BOLDON: - case TAG_ITALICON: - case TAG_UNDERLINEON: - case TAG_COMMONSTART: - { - TagPair(); - Paragraph(); - } - break; - case TAG_HREF: - case TAG_NAME: - case TAG_KEY: - case TAG_INDEX: - case TAG_TITEL: - case TAG_REFSTART: - { - TagRef(); - Paragraph(); - } - break; - case TAG_OS2: - case TAG_WIN: - case TAG_UNIX: - case TAG_MAC: //... - { - if ( ! bPfCaseActive ) - { - //PfCases duerfen nicht verschachtelt sein: - bPfCaseActive = TRUE; - PfCase(); - - //So jetzt kann wieder ein PfCase kommen: - bPfCaseActive = FALSE; - Paragraph(); - } - } - break; - case TAG_WRITER: - case TAG_CALC: - case TAG_DRAW: - case TAG_IMPRESS: - case TAG_SCHEDULE: - case TAG_IMAGE: - case TAG_MATH: - case TAG_CHART: - case TAG_OFFICE: - { - if ( !bAppCaseActive ) - { - //AppCases duerfen nicht verschachtelt sein: - bAppCaseActive = TRUE; - AppCase(); - - //jetzt koennen wieder AppCases kommen: - bAppCaseActive = FALSE; - Paragraph(); - } - } - break; - - //Case TAG_BOLDOFF, TAG_ITALICOFF, TAG_BUNDERLINE, TAG_END - //nichts tun wg. epsilon-Prod. - } -} - -void TokenParser::PfCase() -{ - - //Produktion: - //PfCase -> PfCaseBegin Paragraph (PfCase | PfCaseEnd) - - PfCaseBegin(); - - //Jetzt ist eine PfCase-Produktion aktiv: - Paragraph(); - switch ( aTag.nId ) - { - case TAG_ELSE: - case TAG_END: - { - CaseEnd(); - } - break; - case TAG_OS2: - case TAG_WIN: - case TAG_UNIX: - case TAG_MAC: //First (PfBegin) - { - PfCase(); - } - break; - default: - ParseError( 8, "<#ELSE> or <#END> or platform-tag expected.", aTag ); - } - //Die gemerkten Tags wieder loeschen fuer naechstes PfCase: - nPfCaseOptions = 0; -} - -void TokenParser::PfCaseBegin() -{ - switch ( aTag.nId ) - { - case TAG_OS2: - case TAG_WIN: - case TAG_UNIX: - case TAG_MAC: - { - //Token darf noch nicht vorgekommen sein im - //aktuellen Plattform-Case: - if ( !HAS_FLAG( nPfCaseOptions, TAG_NOGROUP( aTag.nId ) ) ) - { - SET_FLAG( nPfCaseOptions, TAG_NOGROUP( aTag.nId ) ); - match( aTag, aTag ); - } - else { - ParseError( 9, "Tag defined twice in the same platform-case", aTag ); - } - } - } -} - -void TokenParser::AppCase() -{ - - //Produktion: - //AppCase -> AppCaseBegin Paragraph (AppCase | AppCaseEnd) - - - AppCaseBegin(); - - Paragraph(); - - switch ( aTag.nId ) - { - case TAG_ELSE: - case TAG_END: - { - CaseEnd(); - } - break; - case TAG_WRITER: - case TAG_DRAW: - case TAG_CALC: - case TAG_IMAGE: - case TAG_MATH: - case TAG_CHART: - case TAG_OFFICE: - case TAG_IMPRESS: - case TAG_SCHEDULE: //First (AppBegin) - { - AppCase(); - } - break; - default: - ParseError( 1, "<#ELSE> or <#END> or application-case-tag expected.", aTag ); - } - - //Die gemerkten Tags wieder loeschen fuer naechstes AppCase: - nAppCaseOptions = 0; -} - -void TokenParser::AppCaseBegin() -{ - switch ( aTag.nId ) - { - case TAG_WRITER: - case TAG_DRAW: - case TAG_CALC: - case TAG_IMAGE: - case TAG_MATH: - case TAG_CHART: - case TAG_OFFICE: - case TAG_IMPRESS: - case TAG_SCHEDULE: - { - //Token darf noch nicht vorgekommen sein im - //aktuellen Plattform-Case: - if ( !HAS_FLAG( nAppCaseOptions, TAG_NOGROUP( aTag.nId ) ) ) - { - SET_FLAG( nAppCaseOptions, TAG_NOGROUP( aTag.nId ) ); - match( aTag, aTag ); - } - else { - ParseError( 13, "Tag defined twice in the same application-case.", aTag ); - } - } - } -} - -void TokenParser::CaseEnd() -{ - //Produktion: - //CaseEnd -> <#ELSE> Paragraph <#END> | <#END> - - switch ( aTag.nId ) - { - case TAG_ELSE: - { - match( aTag, TAG_ELSE ); - Paragraph(); - match( aTag, TAG_END ); - } - break; - case TAG_END: - { - match( aTag, TAG_END ); - } - break; - default: - ParseError( 2, "<#ELSE> or <#END> expected.", aTag ); - } -} - -void TokenParser::SimpleTag() -{ - - switch ( aTag.nId ) - { - case TAG_HELPID: - { - match( aTag, TAG_HELPID ); - } - break; - case TAG_OFFICEFULLNAME: - case TAG_OFFICENAME: - case TAG_OFFICEPATH: - case TAG_OFFICEVERSION: - case TAG_PORTALNAME: - case TAG_PORTALFULLNAME: - case TAG_PORTALPATH: - case TAG_PORTALVERSION: - case TAG_PORTALSHORTNAME: - - case TAG_REFINSERT: - { - match( aTag, aTag ); - } - break; - default: - ParseError( 15, "[<#SimpleTag>] expected.", aTag ); - } -} - -void TokenParser::TagPair() -{ - switch ( aTag.nId ) - { - case TAG_BOLDON: - { - match( aTag, TAG_BOLDON ); - Paragraph(); - match( aTag, TAG_BOLDOFF ); - } - break; - case TAG_ITALICON: - { - match( aTag, TAG_ITALICON ); - Paragraph(); - match( aTag, TAG_ITALICOFF ); - } - break; - case TAG_UNDERLINEON: - { - match( aTag, TAG_UNDERLINEON ); - Paragraph(); - match( aTag, TAG_UNDERLINEOFF ); - } - break; - case TAG_COMMONSTART: - { - //remember tag so we can give the original tag in case of an error - TokenInfo aEndTag( aTag ); - aEndTag.nId = TAG_COMMONEND; - match( aTag, TAG_COMMONSTART ); - Paragraph(); - match( aTag, aEndTag ); - } - break; - default: - ParseError( 10, "<#BOLD>, <#ITALIC>, <#UNDER> expected.", aTag ); - } -} - - -void TokenParser::TagRef() -{ - switch ( aTag.nId ) - { - case TAG_GRAPHIC: - case TAG_NEXTVERSION: - { - if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) - { - TokenId aThisToken = aTag.nId; - SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - match( aTag, aTag ); - Paragraph(); - if ( aThisToken == TAG_GRAPHIC ) - match( aTag, TAG_ENDGRAPHIC ); - else - match( aTag, TAG_VERSIONEND ); - // don't reset since alowed only once per paragraph - // RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - } - else - { - ParseError( 11, "Tags <#GRAPHIC>,<#NEXTVERSION> allowed only once per paragraph at", aTag ); - } - } - break; - case TAG_AVIS: - case TAG_AHID: - { - if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) - { - TokenId aThisToken = aTag.nId; - SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - match( aTag, aTag ); - Paragraph(); - match( aTag, TAG_AEND ); - RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - } - else - { - ParseError( 11, "Nested <#AHID>,<#AVIS> not allowed.", aTag ); - } - } - break; - case TAG_HREF: - case TAG_NAME: - { - - } - // NOBREAK - case TAG_KEY: - case TAG_INDEX: - case TAG_TITEL: - case TAG_REFSTART: - { - if ( !HAS_FLAG( nActiveRefTypes, TAG_NOGROUP( aTag.nId ) ) ) - { - TokenId aThisToken = aTag.nId; - match( aTag, aTag ); - if ( aThisToken != TAG_NAME ) - { // TAG_NAME has no TAG_END - SET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - Paragraph(); - match( aTag, TAG_END ); - RESET_FLAG( nActiveRefTypes, TAG_NOGROUP( aThisToken ) ); - } - } - else - { - ParseError( 11, "Nested <#HREF>,<#NAME> or <#KEY> not allowed.", aTag ); - } - } - break; - default: - ParseError( 12, "<#HREF>,<#NAME> or <#KEY> expected.", aTag ); - } -} - -BOOL TokenParser::match( const TokenInfo &aCurrentToken, const TokenId &aExpectedToken ) -{ - return match( aCurrentToken, TokenInfo( aExpectedToken, TOK_INVALIDPOS ) ); -} - -BOOL TokenParser::match( const TokenInfo &aCurrentToken, const TokenInfo &rExpectedToken ) -{ - TokenInfo aExpectedToken( rExpectedToken ); - if ( aCurrentToken.nId == aExpectedToken.nId ) - { - if ( ( aCurrentToken.nId == TAG_COMMONEND - && aCurrentToken.GetTagName().Equals( aExpectedToken.GetTagName() ) ) - || aCurrentToken.nId != TAG_COMMONEND ) - { - aTag = aParser.GetNextToken( *pErrorList ); - return TRUE; - } - } - - if ( aExpectedToken.nId == TAG_COMMONEND ) - { - aExpectedToken.aTokenString.Insert( String::CreateFromAscii( "Close tag for " ), 0 ); - } - - ByteString sTmp( "Expected Symbol" ); - if ( aCurrentToken.nId == TAG_NOMORETAGS ) - { - ParseError( 7, sTmp, aExpectedToken ); - } - else - { - sTmp += ": "; - sTmp += ByteString( aParser.GetLexem( aExpectedToken ), RTL_TEXTENCODING_UTF8 ); - sTmp += " near "; - ParseError( 7, sTmp, aCurrentToken ); - } - return FALSE; -} - -void TokenParser::ParseError( USHORT nErrNr, ByteString aErrMsg, const TokenInfo &rTag ) -{ - pErrorList->AddError( nErrNr, aErrMsg, rTag); - - // Das Fehlerhafte Tag ueberspringen - aTag = aParser.GetNextToken( *pErrorList ); -} - - -ParserMessage::ParserMessage( USHORT PnErrorNr, ByteString PaErrorText, const TokenInfo &rTag ) - : nErrorNr( PnErrorNr ) - , aErrorText( PaErrorText ) - , nTagBegin( 0 ) - , nTagLength( 0 ) -{ - String aLexem( SimpleParser::GetLexem( rTag ) ); - aErrorText.Append(": "); - aErrorText += ByteString( aLexem, RTL_TEXTENCODING_UTF8 ); - if ( rTag.nId == TAG_NOMORETAGS ) - aErrorText.Append(" at end of line "); - else if ( rTag.nPos != TOK_INVALIDPOS ) - { - aErrorText.Append(" at Position "); - aErrorText.Append( ByteString::CreateFromInt32( rTag.nPos ) ); - } - nTagBegin = rTag.nPos; - nTagLength = aLexem.Len(); -} - -ParserError::ParserError( USHORT ErrorNr, ByteString ErrorText, const TokenInfo &rTag ) -: ParserMessage( ErrorNr, ErrorText, rTag ) -{} - -ParserWarning::ParserWarning( USHORT ErrorNr, ByteString ErrorText, const TokenInfo &rTag ) -: ParserMessage( ErrorNr, ErrorText, rTag ) -{} - -BOOL LingTest::IsTagMandatory( TokenInfo const &aToken, TokenId &aMetaTokens ) -{ - TokenId aTokenId = aToken.nId; - TokenId aTokenGroup = TAG_GROUP( aTokenId ); - if ( TAG_GROUP_PROGSWITCH == aTokenGroup - || TAG_REFINSERT == aTokenId - || TAG_REFSTART == aTokenId - || TAG_NAME == aTokenId - || TAG_HREF == aTokenId - || TAG_AVIS == aTokenId - || TAG_AHID == aTokenId - || TAG_GRAPHIC == aTokenId - || TAG_NEXTVERSION == aTokenId - || ( TAG_GROUP_META == aTokenGroup && (aMetaTokens & aTokenId) == aTokenId ) ) - { - if ( TAG_GROUP_META == aTokenGroup ) - aMetaTokens |= aTokenId; - return TRUE; - } - else if ( TAG_COMMONSTART == aTokenId - || TAG_COMMONEND == aTokenId ) - { - String aTagName = aToken.GetTagName(); - return !(aTagName.EqualsIgnoreCaseAscii( "comment" ) - || aTagName.EqualsIgnoreCaseAscii( "bookmark_value" ) - || aTagName.EqualsIgnoreCaseAscii( "emph" ) - || aTagName.EqualsIgnoreCaseAscii( "item" ) - || aTagName.EqualsIgnoreCaseAscii( "br" ) ); - } - return FALSE; -} - -void LingTest::CheckTags( TokenList &aReference, TokenList &aTestee, BOOL bFixTags ) -{ - ULONG i=0,j=0; - // Clean old Warnings - while ( aCompareWarningList.Count() ) - { - delete aCompareWarningList.GetCurObject(); - aCompareWarningList.Remove(); - } - - /* in xml tags, do not require the following tags - comment - bookmark_value - emph - item - br - */ - - // filter uninteresting Tags - TokenId aMetaTokens = 0; - for ( i=0 ; i < aReference.Count() ; i++ ) - { - if ( !IsTagMandatory( aReference.GetObject( i ), aMetaTokens ) ) - aReference.GetObject( i ).SetDone(); - } - - aMetaTokens = 0; - for ( i=0 ; i < aTestee.Count() ; i++ ) - { - if ( !IsTagMandatory( aTestee.GetObject( i ), aMetaTokens ) ) - aTestee.GetObject( i ).SetDone(); - } - - // remove all matching tags - for ( i=0 ; i < aReference.Count() ; i++ ) - { - if ( aReference.GetObject( i ).IsDone() ) - continue; - - BOOL bTagFound = FALSE; - for ( j=0 ; j < aTestee.Count() && !bTagFound ; j++ ) - { - if ( aTestee.GetObject( j ).IsDone() ) - continue; - - if ( aReference.GetObject( i ).MatchesTranslation( aTestee.GetObject( j ), FALSE, aCompareWarningList ) ) - { - aReference.GetObject( i ).SetDone(); - aTestee.GetObject( j ).SetDone(); - bTagFound = TRUE; - } - } - } - - BOOL bCanFix = TRUE; - - if ( bFixTags ) - { - // we fix only if its a really simple case - USHORT nTagCount = 0; - for ( i=0 ; i < aReference.Count() ; i++ ) - if ( !aReference.GetObject( i ).IsDone() ) - nTagCount++; - if ( nTagCount > 1 ) - bCanFix = FALSE; - - nTagCount = 0; - for ( i=0 ; i < aTestee.Count() ; i++ ) - if ( !aTestee.GetObject( i ).IsDone() ) - nTagCount++; - if ( nTagCount > 1 ) - bCanFix = FALSE; - } - - // generate errors for tags that have differing attributes - for ( i=0 ; i < aReference.Count() ; i++ ) - { - if ( aReference.GetObject( i ).IsDone() ) - continue; - - BOOL bTagFound = FALSE; - for ( j=0 ; j < aTestee.Count() && !bTagFound ; j++ ) - { - if ( aTestee.GetObject( j ).IsDone() ) - continue; - - if ( aReference.GetObject( i ).MatchesTranslation( aTestee.GetObject( j ), TRUE, aCompareWarningList, bCanFix && bFixTags ) ) - { - aReference.GetObject( i ).SetDone(); - aTestee.GetObject( j ).SetDone(); - bTagFound = TRUE; - } - } - } - - // list remaining tags as errors - for ( i=0 ; i < aReference.Count() ; i++ ) - { - if ( aReference.GetObject( i ).IsDone() ) - continue; - - aCompareWarningList.AddError( 20, "Missing Tag in Translation", aReference.GetObject( i ) ); - } - for ( i=0 ; i < aTestee.Count() ; i++ ) - { - if ( aTestee.GetObject( i ).IsDone() ) - continue; - - aCompareWarningList.AddError( 21, "Extra Tag in Translation", aTestee.GetObject( i ) ); - } - - for ( i=0 ; i < aReference.Count() ; i++ ) - aReference.GetObject( i ).SetDone( FALSE ); - - for ( i=0 ; i < aTestee.Count() ; i++ ) - aTestee.GetObject( i ).SetDone( FALSE ); -} - -void LingTest::CheckReference( GSILine *aReference ) -{ - aReferenceParser.Parse( aReference->GetUText(), aReference->GetMessageList() ); -} - -void LingTest::CheckTestee( GSILine *aTestee, BOOL bHasSourceLine, BOOL bFixTags ) -{ - aFixedTestee = aTestee->GetUText(); - aTesteeParser.Parse( aFixedTestee, aTestee->GetMessageList() ); - - if ( bHasSourceLine ) - CheckTags( aReferenceParser.GetTokenList(), aTesteeParser.GetTokenList(), bFixTags ); - - if ( bFixTags ) - { - TokenList& aTesteeTokens = aTesteeParser.GetTokenList(); - BOOL bFixesDone = FALSE; - // count backwards to allow replacing from right to left - int i; - for ( i=aTesteeTokens.Count()-1 ; i>=0 ; i-- ) - { - if ( aTesteeTokens.GetObject( i ).HasBeenFixed() ) - { - bFixesDone = TRUE; - aFixedTestee.Replace( aTesteeTokens.GetObject( i ).nPos, aTesteeTokens.GetObject( i ).aTokenString.Len(), aTesteeTokens.GetObject( i ).MakeTag() ); - } - } - if ( bFixesDone ) - { - aTestee->SetUText( aFixedTestee ); - aTestee->SetFixed(); - } - } -} - diff --git a/transex3/source/treeconfig.cxx b/transex3/source/treeconfig.cxx deleted file mode 100644 index 137492c39a50..000000000000 --- a/transex3/source/treeconfig.cxx +++ /dev/null @@ -1,128 +0,0 @@ -#include -#include -#include -#include "treeconfig.hxx" -#include "export.hxx" -#ifdef WNT -#include -#include -#else -#include -#endif -#include -#include -#include -#include - -using namespace std; - -namespace transex3 -{ - -bool Treeconfig::parseConfig(){ - - string source_config_file = string( static_cast( Export::GetEnv("SOURCE_ROOT_DIR") ).GetBuffer() ); - if( source_config_file.empty() ) - { - cerr << "Error: no suitable environment set?!?"; - exit( -1 ); - } - source_config_file += string("/source_config"); - if( isConfigFilePresent() ) - { - inireader.read( map , source_config_file ); - return true; - } - else return false; -} - -// ALWAYS add all repositories from source_config file to the container active_repos -// if a config_file is present ALWAYS return false -// if you are in the root of a repository also add it to the container active_repos -// if you are far inside a repository /my/path/ooo/sw/source then don't add it to the container but return true -// if you are in some misc place like /tmp then return true -// => the application can decide what to do in case the function returns true thus how to handle pwd() path -bool Treeconfig::getActiveRepositories( vector& active_repos ){ - - bool isPresent = isConfigFilePresent(); - bool hasPath = false; - string pwd; - string guessedRepo; - Export::getCurrentDir( pwd ); - string source_root = Export::GetEnv( "SOURCE_ROOT_DIR" ); - string solarsrc = Export::GetEnv( "SOLARSRC" ); - string partial; - - // if we are inside of a repository root then active it otherwise let the app handle the return! - string::size_type pos = pwd.find_first_of( source_root ); - if( pos != string::npos && ( pos + source_root.length() +1 ) < pwd.length()){ // I am within SOURCE_ROOT_DIR - partial = pwd.substr( pos + source_root.length() +1 , pwd.length()); - string::size_type nextPart = partial.find_first_of( "/" ); - if( nextPart != string::npos ) - hasPath = true; - else - guessedRepo = partial; - } - else // I am NOT within SOURCE_ROOT_DIR - hasPath = true; - - if( isPresent ) - { - hasPath = false; // if config_file is present don't care about pwd - stringmap* repos = static_cast( map[ string("repositories") ] ); - if( repos != 0 ) - { - for( stringmap::iterator iter = repos->begin() ; iter != repos->end() ; ++iter ) - { - if( static_cast( iter->second ) == string( "active" ) ) - { - active_repos.push_back( iter->first ); - if( static_cast( iter->first ) == guessedRepo ) - { - guessedRepo.clear(); // don't add double in case it is present in config_file - } - } - } - } - else - { - cerr << "Error: source_config files doesn't contain a 'repositories' section ?!?"; - exit( -1 ); - } - } - if( !guessedRepo.empty() ){ - active_repos.push_back( guessedRepo ); // add myrepo - } - return hasPath; // are we deep inside of a source tree or outside of SOURCE_ROOT_DIR? -} - -void Treeconfig::getCurrentDir( string& dir ) -{ - char buffer[64000]; - if( getcwd( buffer , sizeof( buffer ) ) == 0 ){ - cerr << "Error: getcwd failed!\n"; - exit( -1 ); - } - dir = string( buffer ); -} - -bool Treeconfig::isConfigFilePresent() -{ - string config_file = Export::GetEnv( "SOURCE_ROOT_DIR" ); - config_file += "/source_config"; - - struct stat status; - if( stat( config_file.c_str() , &status ) < 0 ) - { - return false; - } -#ifdef WNT - return ( status.st_mode & _S_IFREG ) && ( _access( config_file.c_str() , 4 ) >= 0 ) ; -#else - return ( status.st_mode & S_IFREG ) && ( access( config_file.c_str() , R_OK ) >= 0 ) ; -#endif -} - - - -} diff --git a/transex3/source/utf8conv.cxx b/transex3/source/utf8conv.cxx deleted file mode 100644 index 8fc61f9bb5cc..000000000000 --- a/transex3/source/utf8conv.cxx +++ /dev/null @@ -1,77 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: utf8conv.cxx,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include "utf8conv.hxx" - -// -// class UTF8Converter -// - -#define MAX_CONV_BUFFER_SIZE 0xFF00 - -#define TO_CVTFLAGS (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_MAPTOPRIVATE |\ - RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |\ - RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT) - -#define FROM_CVTFLAGS (RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT |\ - RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT |\ - RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |\ - RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0) - -/*****************************************************************************/ -void UTF8Converter::Convert( ByteString &rBuffer, - rtl_TextEncoding nSourceENC, rtl_TextEncoding nDestENC ) -/*****************************************************************************/ -{ - String sTemp( rBuffer, nSourceENC ); - rBuffer = ByteString( sTemp, nDestENC ); -} - -/*****************************************************************************/ -ByteString UTF8Converter::ConvertToUTF8( - const ByteString &rASCII, rtl_TextEncoding nEncoding ) -/*****************************************************************************/ -{ - ByteString sReturn( rASCII ); - Convert( sReturn, nEncoding, RTL_TEXTENCODING_UTF8 ); - return sReturn; -} - -/*****************************************************************************/ -ByteString UTF8Converter::ConvertFromUTF8( - const ByteString &rUTF8, rtl_TextEncoding nEncoding ) -/*****************************************************************************/ -{ - ByteString sReturn( rUTF8 ); - Convert( sReturn, RTL_TEXTENCODING_UTF8, nEncoding ); - return sReturn; -} diff --git a/transex3/source/wrdtrans.cxx b/transex3/source/wrdtrans.cxx deleted file mode 100644 index 71866cd0e618..000000000000 --- a/transex3/source/wrdtrans.cxx +++ /dev/null @@ -1,248 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: wrdtrans.cxx,v $ - * $Revision: 1.7 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" - -/* -#include "wrdtrans.hxx" - - -// NOT FULLY DECLARED SERVICES -#include -#include - - -#include -#include "wtratree.hxx" - -#include -*/ -//************** Declaration WordTrans_ErrorList ******************// -/* -typedef NAMESPACE_STD(vector) Stl_ByteStringList; - -class WordTrans_ErrorList -{ - public: - // OPERATIONS - void AddError( - WordTransformer::E_Error - i_eType, - const char * i_sErrorDescription ); - void Clear(); /// Empties the list. - - // INQUIRY - USHORT NrOfErrors() const; - WordTransformer::E_Error - GetError( - USHORT i_nNr, /// [0 .. NrOfErrors()-1], other values return an empty error. - ByteString * o_pErrorText ) const; /// If o_pErrorText != 0, the String is filled with the description of the error. - private: - // DATA - Stl_ByteStringList aErrors; -}; - -*/ - -//************** Implementation WordTransformer ******************// - -/* -WordTransformer::WordTransformer() - : dpTransformer(0), - dpErrors(new WordTrans_ErrorList) -{ -} - -WordTransformer::~WordTransformer() -{ - if (dpTransformer != 0) - delete dpTransformer; - delete dpErrors; -} - -BOOL -WordTransformer::LoadWordlist( const ByteString & i_sWordlist_Filepath, - CharSet i_nWorkingCharSet, - CharSet i_nFileCharSet ) -{ - if (dpTransformer != 0) - return FALSE; - - SvFileStream aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ); - if (! aFile.IsOpen()) - return FALSE; - aFile.SetStreamCharSet( i_nFileCharSet ) ; -// aFile.SetTargetCharSet( i_nWorkingCharSet ); - - dpTransformer = new WordTransTree; - - ByteString sTrans; - while ( aFile.ReadLine(sTrans) ) - { - dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';')); - } - - aFile.Close(); - return TRUE; -} - -USHORT -WordTransformer::Transform(ByteString & io_sText) -{ - // Initialization and precondition testing: - dpErrors->Clear(); - if (dpTransformer == 0) - { - dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded."); - return dpErrors->NrOfErrors(); - } - else if (io_sText.Len() > 63 * 1024) - { - dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB)."); - return dpErrors->NrOfErrors(); - } - else if (io_sText.Len() == 0) - { - return 0; - } - - // Transform: - dpTransformer->InitTransformation( - io_sText.GetBuffer(), - io_sText.Len() ); - - for ( ; !dpTransformer->TextEndReached(); ) - { - if (dpTransformer->TransformNextToken() != WordTransTree::OK) - { - CreateError(); - } - } - io_sText = dpTransformer->Output(); - return dpErrors->NrOfErrors(); -} - -USHORT -WordTransformer::NrOfErrors() const -{ - return dpErrors->NrOfErrors(); -} - -WordTransformer::E_Error -WordTransformer::GetError( USHORT i_nNr, - ByteString * o_pErrorText) const -{ - return dpErrors->GetError(i_nNr,o_pErrorText); -} - -void -WordTransformer::CreateError() -{ - ByteString sErr; - - switch (dpTransformer->CurResult()) - { - case WordTransTree::OK: - break; - case WordTransTree::HOTKEY_LOST: - sErr = ByteString("Error: By replacement of string "); - sErr += dpTransformer->CurReplacedString(); - sErr += " by "; - sErr += dpTransformer->CurReplacingString(); - sErr += "the hotkey at char '"; - sErr += dpTransformer->CurHotkey(); - sErr += "' was lost."; - dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess()); - sErr.ReleaseBufferAccess(); - break; - case WordTransTree::OUTPUT_OVERFLOW: - dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow."); - break; - default: - dpErrors->AddError(OTHER_ERROR,"Error: Unknown error."); - } -} -*/ -//************** Implementation WordTrans_ErrorList ******************// -/* -void -WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType, - const char * i_sErrorDescription ) -{ - ByteString sErrorType = "xxx"; - char * pErrorChars = sErrorType.GetBufferAccess(); - pErrorChars[0] = char(i_eType / 100 + '0'); - pErrorChars[1] = char( (i_eType % 100) / 10 + '0'); - pErrorChars[2] = char(i_eType % 10 + '0'); - sErrorType += i_sErrorDescription; - - aErrors.push_back(sErrorType); - sErrorType.ReleaseBufferAccess(); -} - -void -WordTrans_ErrorList::Clear() -{ - aErrors.erase(aErrors.begin(),aErrors.end()); -} - -USHORT -WordTrans_ErrorList::NrOfErrors() const -{ - return aErrors.size(); -} - -WordTransformer::E_Error -WordTrans_ErrorList::GetError( USHORT i_nNr, - ByteString * o_pErrorText ) const -{ - if ( i_nNr < aErrors.size() ) - { - const ByteString & rError = aErrors[i_nNr]; - const char * pErrorChars = rError.GetBuffer(); - - USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100 - + (pErrorChars[1] - '0') * 10 - + pErrorChars[2] - '0'; - - if (o_pErrorText != 0) - *o_pErrorText = pErrorChars+3; - - return WordTransformer::E_Error(nError); - } - else - { - if (o_pErrorText != 0) - *o_pErrorText = ""; - return WordTransformer::OK; - } -} -*/ diff --git a/transex3/source/wtranode.cxx b/transex3/source/wtranode.cxx deleted file mode 100644 index 0383ffa7feac..000000000000 --- a/transex3/source/wtranode.cxx +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: wtranode.cxx,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" - - -#include "wtranode.hxx" - - -// NOT FULLY DECLARED SERVICES - - -const ByteString sEmptyString(""); - - -WTT_Node::WTT_Node( UINT8 i_nValue, - WTT_Node * i_pDefaultBranch, - WTT_Node * i_pDefaultBranchForAlphas ) - : nValue(i_nValue), - eType(token_to_keep), - sReplaceString(sEmptyString), - // aBranches, - bIsOnDeleting(char(0)) -{ - int i = 0; - for ( ; i < C_BR_ALPHABASE; i++ ) - { - aBranches[i] = i_pDefaultBranch; - } // end for - for ( ; i < C_NR_OF_BRANCHES; i++ ) - { - aBranches[i] = i_pDefaultBranchForAlphas; - } -} - -void -WTT_Node::SetBranch( UINT8 i_cBranch, - WTT_Node * i_pNode ) -{ - if (i_cBranch < C_NR_OF_BRANCHES) - { - aBranches[i_cBranch] = i_pNode; - } -} - -void -WTT_Node::SetAsTokenToReplace(const ByteString & i_sReplaceString) -{ - sReplaceString = i_sReplaceString; - eType = token_to_replace; -} - -WTT_Node::~WTT_Node() -{ - // Delete the tree hanging below this node: - - bIsOnDeleting = TRUE; // Avoid double deleting of multiple used nodes. - - for (int i = 0; i < C_NR_OF_BRANCHES; i++) - { - if (aBranches[i] != 0 ? ! aBranches[i]->IsOnDeleting() : FALSE) - { - delete aBranches[i]; - } - } // end for -} - - - - - - - - - - - - - - - - - diff --git a/transex3/source/wtratree.cxx b/transex3/source/wtratree.cxx deleted file mode 100644 index fea67215ba51..000000000000 --- a/transex3/source/wtratree.cxx +++ /dev/null @@ -1,421 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: wtratree.cxx,v $ - * $Revision: 1.5 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" - - -#include "wtratree.hxx" - - - -/** @ATTENTION - For reasons of speed, class WordTransTree works with two simple - char arrays, sOutput and sInput, instead of secure containers or - streams. So be extremely careful, when changing this code!!! -**/ - - - -// NOT FULLY DECLARED SERVICES -#include -#include -#include -#include "wtranode.hxx" - - -const BRANCH_T BR_END = 0; -const BRANCH_T BR_NONALPHA = 1; -const BRANCH_T BR_HOTKEY = 2; -const BRANCH_T BR_BACKSLASH = 3; -const BRANCH_T BR_ALPHABASE = 4; /// @ATTENTION All branches not valid for words must be smaller than this value! -const BRANCH_T BR_AE = 30; -const BRANCH_T BR_OE = 31; -const BRANCH_T BR_UE = 32; -const BRANCH_T BR_SZ = 33; -const BRANCH_T BR_MAX = 34; /// @ATTENTION Must be updated always! - -const BRANCH_T BR_START = 0; - - - - - -WordTransTree::WordTransTree(CharSet i_nWorkingCharSet) - : sInput(0), - nInputLength(0), - pInputEnd(0), - sOutput(0), - nOutputMaxLength(0), - dpParsingTreeTop(0), - pUnknownAlpha(0), - // cChar2Branch - c_AE(u_char('\xC4')), c_OE(u_char('\xD6')), c_UE(u_char('\xDC')), - c_ae(u_char('\xE4')), c_oe(u_char('\xF6')), c_ue(u_char('\xFC')), - pInputCurTokenStart(0), - pInputPosition(0), - pOutputPosition(0), - pCurParseNode(0), - eCurResult(OK), - cCurHotkey(0), - cCurHotkeySign(u_char('~')) -{ - // Initialize parsing tree: - pUnknownAlpha = new WTT_Node(BR_ALPHABASE,0,0); // This will be deleted as part of the parsing tree. - for ( UINT8 i = BR_ALPHABASE; i < C_NR_OF_BRANCHES; i++) - { - pUnknownAlpha->SetBranch(i,pUnknownAlpha); - } // end for - - dpParsingTreeTop = new WTT_Node(BR_START,0,pUnknownAlpha); - - WTT_Node * dpNonAlpha = new WTT_Node(BR_NONALPHA,0,0); - - dpNonAlpha->SetBranch(BR_NONALPHA,dpNonAlpha); - dpParsingTreeTop->SetBranch(BR_NONALPHA,dpNonAlpha); - - WTT_Node * dpBackslash = new WTT_Node(BR_BACKSLASH,dpNonAlpha,dpNonAlpha); - dpBackslash->SetBranch(BR_END,0); - - dpParsingTreeTop->SetBranch(BR_BACKSLASH,dpBackslash); - dpNonAlpha->SetBranch(BR_BACKSLASH,dpBackslash); - - - // Initialize character set: - SetCharSet(i_nWorkingCharSet); - - if (C_BR_ALPHABASE != BR_ALPHABASE || C_NR_OF_BRANCHES != BR_MAX) - { - fprintf(stderr, "Assertion failed: file %s line %d.", __FILE__, __LINE__); - exit(1); - } -} - -void -WordTransTree::SetCharSet(CharSet i_nWorkingCharSet) -{ - ByteString sConvert("\xC4\xD6\xDC\xE4\xF6\xFC\xDF"); - const u_char * pConvert = (const u_char * ) ( sConvert.Convert(RTL_TEXTENCODING_MS_1252, i_nWorkingCharSet).GetBuffer() ); - - INT16 i = 0; - for ( ; i < C_NR_OF_POSSIBLE_CHARS; ++i ) - { - cChar2Branch[i] = BR_NONALPHA; - } // end for - for ( i = 'a'; i <= 'z'; ++i ) - { - cChar2Branch[i] = BR_ALPHABASE + i - 'a'; - } // end for - for ( i = 'A'; i <= 'Z'; ++i ) - { - cChar2Branch[i] = BR_ALPHABASE + i - 'A'; - } // end for - cChar2Branch[pConvert[0]] = BR_AE; - cChar2Branch[pConvert[1]] = BR_OE; - cChar2Branch[pConvert[2]] = BR_UE; - cChar2Branch[pConvert[3]] = BR_AE; - cChar2Branch[pConvert[4]] = BR_OE; - cChar2Branch[pConvert[5]] = BR_UE; - cChar2Branch[pConvert[6]] = BR_SZ; - - cChar2Branch[u_char('~')] = BR_HOTKEY; - cChar2Branch[u_char('&')] = BR_HOTKEY; - - - c_AE = pConvert[0]; - c_OE = pConvert[1]; - c_UE = pConvert[2]; - c_ae = pConvert[3]; - c_oe = pConvert[4]; - c_ue = pConvert[5]; -} - -WordTransTree::~WordTransTree() -{ - delete dpParsingTreeTop; - if (sOutput != 0) - delete [] sOutput; -} - -void -WordTransTree::AddWordPair( const ByteString & i_sOldString, - const ByteString & i_sReplaceString ) -{ - if (i_sOldString.Len() == 0) - return; - - pCurParseNode = dpParsingTreeTop; - WTT_Node * pBranch = 0; - char cBranch = 0; - - for ( constr pOld = i_sOldString.GetBuffer(); - *pOld != 0; - pOld++ ) - { - cBranch = CalculateBranch(*pOld); - pBranch = pCurParseNode->GetNextNode(cBranch); - if (pBranch == 0 || pBranch == pUnknownAlpha) - { - pBranch = new WTT_Node(cBranch,0,pUnknownAlpha); - pCurParseNode->SetBranch(cBranch,pBranch); - } - pCurParseNode = pBranch; - } // end for - pCurParseNode->SetAsTokenToReplace(i_sReplaceString); -} - -void -WordTransTree::InitTransformation( const char * i_sInput, - UINT32 i_nInputLength, - UINT32 i_nOutputMaxLength ) -{ - sInput = (const u_char *)i_sInput; - nInputLength = i_nInputLength; - pInputEnd = &sInput[i_nInputLength]; - - pInputCurTokenStart = sInput; - pInputPosition = sInput; - - if (nOutputMaxLength < i_nOutputMaxLength) - { - if (sOutput != 0) - delete [] sOutput; - sOutput = new unsigned char[i_nOutputMaxLength]; - nOutputMaxLength = i_nOutputMaxLength; - } - pOutputPosition = sOutput; -} - -/** pInputCurTokenStart and CurParseNode are updated just when - starting this function. After its end they must not be changed - till this functon is called again. - Outside this function pInputPositon and pOutputPosition are both - on the first not transformed char in their respective array. -**/ -WordTransTree::E_Result -WordTransTree::TransformNextToken() -{ - pInputCurTokenStart = pInputPosition; - pCurParseNode = dpParsingTreeTop; - cCurHotkey = 0; - eCurResult = OK; - - WTT_Node * pBranch = 0; - UINT8 cBranch = 0; - - for ( pCurParseNode = dpParsingTreeTop; - pInputPosition != pInputEnd; - ++pInputPosition ) - { - cBranch = CalculateBranch(*pInputPosition); - pBranch = pCurParseNode->GetNextNode( cBranch ); - if (pBranch != 0) - { - pCurParseNode = pBranch; - } - else - { - if (cBranch == BR_HOTKEY) // current letter is '~' or '&'. - { - // Logic of the following. There are 9 possible cases - - // A = alphabetic letter, NA = non alphabetic, TB = token begin, - // Eot = end of text: - // 1. A~A set hotkey to following letter, continue - // 2. A~NA token end - // 3. A~Eot token end - // 4. NA~A token end - // 5. NA~NA continue - // 6. A~Eof continue - // 7. TB~A set hotkey to following letter, continue - // 8. TB~NA continue - // 9. TB~Eot continue - - // bNext and Prev are true, if there are alphabetic letters: - BOOL bNext = pInputPosition + 1 != pInputEnd - ? CalculateBranch(pInputPosition[1]) >= BR_ALPHABASE - : FALSE; - BOOL bPrev = pCurParseNode->Value() >= BR_ALPHABASE; - - if ( bNext && (bPrev || pCurParseNode == dpParsingTreeTop) ) - { // case 1. and 7. - Handle_Hotkey(); - continue; - } - else if (!bPrev && !bNext) - { // case 5.,6.,8.,9. - continue; - } - - // Case 2.,3.,4. : - // so this should be handled as an end of a token. - } - if (pCurParseNode->TokenType() == WTT_Node::token_to_keep) - { - Handle_TokenToKeep(); - return eCurResult; - } - else - { - Handle_TokenToTransform(); - return eCurResult; - } // endif (pCurParseNode->TokenType() == WTT_Node::token_to_keep) - } // endif (pBranch == 0) else - } // end for - - // If here, the text end is reached - if (pCurParseNode->TokenType() == WTT_Node::token_to_keep) - { - Handle_TokenToKeep(); - return eCurResult; - } - else - { - Handle_TokenToTransform(); - return eCurResult; - } -} - -ByteString -WordTransTree::CurReplacingString() const -{ - return pCurParseNode->ReplaceString(); -} - -void -WordTransTree::Handle_Hotkey() -{ - if (cCurHotkey == 0) // Avoid to replace the first found hotkey by - // a later one - though this shouldn't happen anyway. - { - cCurHotkey = (pInputPosition+1) != pInputEnd ? pInputPosition[1] : 0; - cCurHotkeySign = *pInputPosition; - } -} - -void -WordTransTree::Handle_TokenToKeep() -{ - UINT32 nTokenLength = pInputPosition-pInputCurTokenStart; - - memcpy(pOutputPosition,pInputCurTokenStart,nTokenLength); - - pOutputPosition += nTokenLength; - *pOutputPosition = '\0'; -} - -void -WordTransTree::Handle_TokenToTransform() -{ - BOOL bHaveHotkey = CalculateBranch(cCurHotkey) >= BR_ALPHABASE; - const ByteString & rReplace = pCurParseNode->ReplaceString(); - - // Find position of hotkey in replace-string: - USHORT nHotkeyPos = bHaveHotkey - ? rReplace.Search(char(cCurHotkey)) - : STRING_NOTFOUND; - if (nHotkeyPos == STRING_NOTFOUND && bHaveHotkey) - { - if (cCurHotkey < 128) - { - if (islower(cCurHotkey)) - nHotkeyPos = rReplace.Search(toupper(char(cCurHotkey))); - else - nHotkeyPos = rReplace.Search(tolower(char(cCurHotkey))); - } - else // cCurHotkey >= 128 - { - if (cCurHotkey == c_ae) - nHotkeyPos = rReplace.Search(char(c_AE)); - else if (cCurHotkey == c_oe) - nHotkeyPos = rReplace.Search(char(c_OE)); - else if (cCurHotkey == c_ue) - nHotkeyPos = rReplace.Search(char(c_UE)); - else if (cCurHotkey == c_AE) - nHotkeyPos = rReplace.Search(char(c_ae)); - else if (cCurHotkey == c_OE) - nHotkeyPos = rReplace.Search(char(c_oe)); - else if (cCurHotkey == c_UE) - nHotkeyPos = rReplace.Search(char(c_ue)); - } // endif (cCurHotkey < 128) else - - if (nHotkeyPos == STRING_NOTFOUND) - { - eCurResult = HOTKEY_LOST; - bHaveHotkey = FALSE; - } - } // endif (nHotkeyPos == STRING_NOT_FOUND && bHaveHotkey) - - - UINT32 nOutputTokenLength = rReplace.Len() + (bHaveHotkey ? 1 : 0); - - if (bHaveHotkey) - { - memcpy( pOutputPosition, - pCurParseNode->ReplaceString().GetBuffer(), - nHotkeyPos ); - *(pOutputPosition + nHotkeyPos) = cCurHotkeySign; - memcpy( pOutputPosition + nHotkeyPos + 1, - pCurParseNode->ReplaceString().GetBuffer() + nHotkeyPos, - nOutputTokenLength - nHotkeyPos - 1); - } - else - { - memcpy( pOutputPosition, - pCurParseNode->ReplaceString().GetBuffer(), - nOutputTokenLength ); - } - - // Convert first letter into upper if necessary: - u_char cInStart = CalculateBranch(*pInputCurTokenStart) == BR_HOTKEY - ? pInputCurTokenStart[1] - : pInputCurTokenStart[0] ; - u_char * pOutStart = nHotkeyPos == 0 - ? pOutputPosition + 1 - : pOutputPosition ; - if (isupper(cInStart) || cInStart > 127) - { // Possibly cInStart is upper character: - if (isupper(cInStart) || cInStart == c_AE || cInStart == c_OE || cInStart == c_UE) - { // Surely cInStart is upper character: - u_char cOutStart = *pOutStart; - if (cOutStart < 128) - *pOutStart = toupper(cOutStart); - else if (cOutStart == c_ae) - *pOutStart = c_AE; - else if (cOutStart == c_oe) - *pOutStart = c_OE; - else if (cOutStart == c_ue) - *pOutStart = c_UE; - } - } // endif (isupper(cInStart) || cInStart > 127) - - pOutputPosition += nOutputTokenLength; - *pOutputPosition = '\0'; -} - diff --git a/transex3/source/xgfconv.cxx b/transex3/source/xgfconv.cxx deleted file mode 100644 index 76ea1a2906a8..000000000000 --- a/transex3/source/xgfconv.cxx +++ /dev/null @@ -1,66 +0,0 @@ -#include - -#include "export.hxx" -#include "utf8conv.hxx" - -/*****************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#if defined(UNX) || defined(OS2) -int main( int argc, char *argv[] ) -#else -int _cdecl main( int argc, char *argv[] ) -#endif -/*****************************************************************************/ -{ - if ( argc != 3 ) { - fprintf( stderr, "xgfconv InputFile OutputFile\n" ); - return ( 5 ); - } - - ByteString sInput( argv[ 1 ] ); - ByteString sOutput( argv[ 2 ] ); - - SvFileStream aInput( String( sInput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); - if ( !aInput.IsOpen()) { - fprintf( stderr, "ERROR: Unable to open input file!\n" ); - return ( 5 ); - } - - SvFileStream aOutput( String( sOutput, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); - if ( !aOutput.IsOpen()) { - fprintf( stderr, "ERROR: Unable to open output file!\n" ); - aInput.Close(); - return ( 5 ); - } - - ByteString sLine; - BOOL bFirst = TRUE; - while ( !aInput.IsEof()) { - aInput.ReadLine( sLine ); - ByteString sLangId = sLine.GetToken( 0, '\t' ); - ByteString sFile = sLine.GetToken( 1, '\t' ); - ByteString sText = sLine.Copy( sLangId.Len() + sFile.Len() + 2 ); - - USHORT nLangId = sLangId.ToInt32(); - CharSet aCharSet = Export::GetCharSet( nLangId ); - if ( aCharSet != 0xFFFF && sText.Len()) { - sText = UTF8Converter::ConvertToUTF8( sText, aCharSet ); - ByteString sOutput = sFile; - sOutput += "\t"; - sOutput += sText; - if ( !bFirst ) { - ByteString sEmpty; - aOutput.WriteLine( sEmpty ); - } - else - bFirst = FALSE; - aOutput.Write( sOutput.GetBuffer(), sOutput.Len()); - } - } - aInput.Close(); - aOutput.Close(); - return ( 0 ); -} - diff --git a/transex3/source/xmlparse.cxx b/transex3/source/xmlparse.cxx deleted file mode 100644 index 921f1d329f67..000000000000 --- a/transex3/source/xmlparse.cxx +++ /dev/null @@ -1,1456 +0,0 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xmlparse.cxx,v $ - * $Revision: 1.24 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * - * for a copy of the LGPLv3 License. - * - ************************************************************************/ - -// MARKER(update_precomp.py): autogen include statement, do not remove -#include "precompiled_transex3.hxx" -#include /* std::iterator*/ - -#include -#include - -#include "xmlparse.hxx" -#include -#include -#include -#include -#ifdef __MINGW32__ -#include -#include -#endif -using namespace std; -using namespace osl; - -// -// class XMLChildNode -// - -/*****************************************************************************/ -XMLChildNode::XMLChildNode( XMLParentNode *pPar ) -/*****************************************************************************/ - : pParent( pPar ) -{ - if ( pParent ) - pParent->AddChild( this ); -} - - -/*****************************************************************************/ -XMLChildNode::XMLChildNode( const XMLChildNode& obj) -/*****************************************************************************/ -: XMLNode(obj), - pParent(obj.pParent){} - -/*****************************************************************************/ -XMLChildNode& XMLChildNode::operator=(const XMLChildNode& obj){ -/*****************************************************************************/ - if(this != &obj){ - pParent=obj.pParent; - } - return *this; -} -// -// class XMLParentNode -// - - -/*****************************************************************************/ -XMLParentNode::~XMLParentNode() -/*****************************************************************************/ -{ - if( pChildList ){ - RemoveAndDeleteAllChilds(); - delete pChildList; - pChildList = NULL; - } - pChildList = NULL; -} -/*****************************************************************************/ -XMLParentNode::XMLParentNode( const XMLParentNode& obj) -/*****************************************************************************/ -: XMLChildNode( obj ) -{ - if( obj.pChildList ){ - pChildList=new XMLChildNodeList(); - XMLChildNode* pNode = NULL; - for ( ULONG i = 0; i < obj.pChildList->Count(); i++ ){ - pNode = obj.pChildList->GetObject( i ); - if( pNode != NULL){ - switch(pNode->GetNodeType()){ - case XML_NODE_TYPE_ELEMENT: - AddChild( new XMLElement( *static_cast(pNode) ) ); break; - case XML_NODE_TYPE_DATA: - AddChild( new XMLData ( *static_cast (pNode) ) ); break; - case XML_NODE_TYPE_COMMENT: - AddChild( new XMLComment( *static_cast(pNode) ) ); break; - case XML_NODE_TYPE_DEFAULT: - AddChild( new XMLDefault( *static_cast(pNode) ) ); break; - default: fprintf(stdout,"XMLParentNode::XMLParentNode( const XMLParentNode& obj) strange obj"); - } - } - } - }else pChildList = NULL; -} -/*****************************************************************************/ -XMLParentNode& XMLParentNode::operator=(const XMLParentNode& obj){ -/*****************************************************************************/ - if(this!=&obj){ - XMLChildNode::operator=(obj); - if( pChildList ){ - RemoveAndDeleteAllChilds(); - delete pChildList; - pChildList = NULL; - } - if( obj.pChildList ){ - pChildList=new XMLChildNodeList(); - for ( ULONG i = 0; i < obj.pChildList->Count(); i++ ) - AddChild( obj.pChildList->GetObject( i ) ); - }else pChildList = NULL; - - } - return *this; -} -/*****************************************************************************/ -void XMLParentNode::AddChild( XMLChildNode *pChild ) -/*****************************************************************************/ -{ - if ( !pChildList ) - pChildList = new XMLChildNodeList(); - pChildList->Insert( pChild, LIST_APPEND ); -} - -/*****************************************************************************/ -void XMLParentNode::AddChild( XMLChildNode *pChild , int pos ) -/*****************************************************************************/ -{ - if ( !pChildList ) - pChildList = new XMLChildNodeList(); - pChildList->Insert( pChild, pos ); -} - -/*****************************************************************************/ -int XMLParentNode::GetPosition( ByteString id ){ -/*****************************************************************************/ - XMLElement* a; - - static const ByteString sEnusStr = ByteString(String::CreateFromAscii(ENGLISH_US_ISO).ToLowerAscii() , RTL_TEXTENCODING_ASCII_US ).ToLowerAscii(); - static const ByteString sDeStr = ByteString(String::CreateFromAscii(GERMAN_ISO2).ToLowerAscii() , RTL_TEXTENCODING_ASCII_US ).ToLowerAscii(); - - if ( pChildList ){ - for ( ULONG i = 0; i < pChildList->Count(); i++ ) { - XMLChildNode *pChild = pChildList->GetObject( i ); - if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ - a = static_cast(pChild); - ByteString elemid( a->GetId() ); - elemid.ToLowerAscii(); - if ( elemid.Equals( id.ToLowerAscii() ) ){ - ByteString elemLID( a->GetLanguageId() ); - elemLID.ToLowerAscii(); - if( elemLID.Equals( sEnusStr) ) { - return i; - } - else if( elemLID.Equals( sDeStr) ) { - return i; - } - } - } - } - } - return -1; -} - -/*****************************************************************************/ -int XMLParentNode::RemoveChild( XMLElement *pRefElement ) -/*****************************************************************************/ -{ - XMLElement* a; - if ( pChildList ){ - for ( ULONG i = 0; i < pChildList->Count(); i++ ) { - XMLChildNode *pChild = pChildList->GetObject( i ); - if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ - a = static_cast(pChild); - ByteString elemid( a->GetId() ); - elemid.ToLowerAscii(); - ByteString elemLID( a->GetLanguageId() ); - elemLID.ToLowerAscii(); - ByteString pRefLID( pRefElement->GetLanguageId() ); - pRefLID.ToLowerAscii(); - if ( elemid.Equals(pRefElement->GetId()) - && elemLID.Equals( pRefLID ) ) - { - if( pRefElement->ToOString().compareTo( a->ToOString() )==0 ){ - pChildList->Remove( i ); - delete a; // Test - return i; - } - } - } - - } - } - return -1; -} - -/*****************************************************************************/ -void XMLParentNode::RemoveAndDeleteAllChilds(){ -/*****************************************************************************/ - if ( pChildList ) { - for ( ULONG i = 0; i < pChildList->Count(); i++ ) - delete pChildList->GetObject( i ); - pChildList->Clear(); - } -} - -/*****************************************************************************/ -XMLElement *XMLParentNode::GetChildElement( XMLElement *pRefElement ) -/*****************************************************************************/ -{ - for ( ULONG i = 0; i < pChildList->Count(); i++ ) { - XMLChildNode *pChild = pChildList->GetObject( i ); - if ( pChild->GetNodeType() == XML_NODE_TYPE_ELEMENT ) - if ((( XMLElement * ) pChild )->GetName() == - pRefElement->GetName()) - { - XMLAttributeList *pList = pRefElement->GetAttributeList(); - if ( !pList ) - return ( XMLElement * ) pChild; - - BOOL bMatch = FALSE; - for ( ULONG j = 0; j < pList->Count() && bMatch; j++ ) { - XMLAttribute *pAttribute = pList->GetObject( j ); - XMLAttribute *pCandidate = - (( XMLElement * ) pChild )->GetAttribute( - *pAttribute ); - if ( !pCandidate || !pAttribute->IsEqual( *pCandidate )) - bMatch = FALSE; - } - if ( bMatch ) - return ( XMLElement * ) pChild; - } - } - return NULL; -} - -// -// class XMLFile -// - -/*****************************************************************************/ -USHORT XMLFile::GetNodeType() -/*****************************************************************************/ -{ - return XML_NODE_TYPE_FILE; -} - -/*****************************************************************************/ -BOOL XMLFile::Write( ByteString &aFilename ) -/*****************************************************************************/ -{ - - if ( aFilename.Len()) { - // retry harder if there is a NFS problem, - for( int x = 1 ; x < 3 ; x++ ){ // this looks strange...yes! - ofstream aFStream( aFilename.GetBuffer() , ios::out | ios::trunc ); - - if( !aFStream ) // From time to time the stream can not be opened the first time on NFS volumes, - { // I wasn't able to track this down. I think this is an NFS issue ..... - //cerr << "ERROR: - helpex - Can't write to tempfile " << aFilename.GetBuffer() << " No#" << x << "\n"; - TimeValue aTime; - aTime.Seconds = 3; - aTime.Nanosec = 0; - - osl::Thread::wait( aTime ); - } - else - { - // write out - Write( aFStream ); - aFStream.close(); - - // check! - DirEntry aTarget( aFilename ); - FileStat aFileStat( aTarget ); - - if( aFileStat.GetSize() < 1 ) - { - //retry - //cerr << "WARNING: - helpex - Can't create file " << aFilename.GetBuffer() << " No#" << x << "\n"; - aTarget.Kill(); - } - else - { - //everything ok! - return true; - } - } - } - cerr << "ERROR: - helpex - Can't create file " << aFilename.GetBuffer() << "\nPossible reason: Disk full ? Mounted NFS volume broken ? Wrong permissions ?\n"; - exit( -1 ); - } - cerr << "ERROR: - helpex - Empty file name\n"; - exit( -1 ); -} - - - -void XMLFile::WriteString( ofstream &rStream, const String &sString ) -{ - ByteString sText( sString, RTL_TEXTENCODING_UTF8 ); - rStream << sText.GetBuffer(); -} - - -BOOL XMLFile::Write( ofstream &rStream , XMLNode *pCur ) -{ - XMLUtil& xmlutil = XMLUtil::Instance(); - (void) xmlutil; - - if ( !pCur ) - Write( rStream, this ); - else { - switch( pCur->GetNodeType()) { - case XML_NODE_TYPE_FILE: { - if( GetChildList()) - for ( ULONG i = 0; i < GetChildList()->Count(); i++ ) - Write( rStream, GetChildList()->GetObject( i )); - } - break; - case XML_NODE_TYPE_ELEMENT: { - XMLElement *pElement = ( XMLElement * ) pCur; - rStream << "<"; - WriteString( rStream, pElement->GetName()); - if ( pElement->GetAttributeList()) - for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ) { - rStream << " "; - String sData(*pElement->GetAttributeList()->GetObject( j )); - xmlutil.QuotHTML( sData ); - WriteString( rStream , sData ); - rStream << "=\""; - sData=pElement->GetAttributeList()->GetObject( j )->GetValue(); - xmlutil.QuotHTML( sData ); - WriteString( rStream , sData ); - rStream << "\""; - } - if ( !pElement->GetChildList()) - rStream << "/>"; - else { - rStream << ">"; - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) - Write( rStream, pElement->GetChildList()->GetObject( k )); - rStream << "GetName()); - rStream << ">"; - } - } - break; - case XML_NODE_TYPE_DATA: { - XMLData *pData = ( XMLData * ) pCur; - String sData( pData->GetData()); - xmlutil.QuotHTML( sData ); - WriteString( rStream, sData ); - } - break; - case XML_NODE_TYPE_COMMENT: { - XMLComment *pComment = ( XMLComment * ) pCur; - rStream << ""; - } - break; - case XML_NODE_TYPE_DEFAULT: { - XMLDefault *pDefault = ( XMLDefault * ) pCur; - WriteString( rStream, pDefault->GetDefault()); - } - break; - } - } - return TRUE; -} - - -void XMLFile::Print( XMLNode *pCur, USHORT nLevel ) -{ - - if ( !pCur ) - Print( this ); - else { - switch( pCur->GetNodeType()) { - case XML_NODE_TYPE_FILE: { - if( GetChildList()) - for ( ULONG i = 0; i < GetChildList()->Count(); i++ ) - Print( GetChildList()->GetObject( i )); - } - break; - case XML_NODE_TYPE_ELEMENT: { - XMLElement *pElement = ( XMLElement * ) pCur; - - fprintf( stdout, "<%s", ByteString( pElement->GetName(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); - if ( pElement->GetAttributeList()) - for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ - ByteString aAttrName( *pElement->GetAttributeList()->GetObject( j ), RTL_TEXTENCODING_UTF8 ); - if( !aAttrName.EqualsIgnoreCaseAscii( XML_LANG ) ) { - fprintf( stdout, " %s=\"%s\"", - aAttrName.GetBuffer(), - ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(), - RTL_TEXTENCODING_UTF8 ).GetBuffer()); - } - } - if ( !pElement->GetChildList()) - fprintf( stdout, "/>" ); - else { - fprintf( stdout, ">" ); - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) - Print( pElement->GetChildList()->GetObject( k ), nLevel + 1 ); - fprintf( stdout, "", ByteString( pElement->GetName(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); - } - } - break; - case XML_NODE_TYPE_DATA: { - XMLData *pData = ( XMLData * ) pCur; - String sData = pData->GetData(); - fprintf( stdout, "%s", ByteString( sData, RTL_TEXTENCODING_UTF8 ).GetBuffer()); - } - break; - case XML_NODE_TYPE_COMMENT: { - XMLComment *pComment = ( XMLComment * ) pCur; - fprintf( stdout, "", ByteString( pComment->GetComment(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); - } - break; - case XML_NODE_TYPE_DEFAULT: { - XMLDefault *pDefault = ( XMLDefault * ) pCur; - fprintf( stdout, "%s", ByteString( pDefault->GetDefault(), RTL_TEXTENCODING_UTF8 ).GetBuffer()); - } - break; - } - } -} -XMLFile::~XMLFile() -{ - if( XMLStrings != NULL ){ - XMLHashMap::iterator pos = XMLStrings->begin(); - for( ; pos != XMLStrings->end() ; ++pos ){ - delete pos->second; // Check and delete content also ? - } - delete XMLStrings; - XMLStrings = NULL; - } -} -/*****************************************************************************/ -XMLFile::XMLFile( const String &rFileName ) // the file name, empty if created from memory stream -/*****************************************************************************/ - : XMLParentNode( NULL ), - sFileName ( rFileName ), - ID ( "id" ), - OLDREF ( "oldref" ), - XML_LANG ( "xml-lang" ), - XMLStrings ( NULL ) - -{ -// nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("bookmark_value"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("bookmark"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("variable"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("paragraph"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("alt"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("caption"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("title"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); - nodes_localize.insert( TagMap::value_type(ByteString(String::CreateFromAscii("link"),RTL_TEXTENCODING_ASCII_US) , TRUE) ); -} -/*****************************************************************************/ -void XMLFile::Extract( XMLFile *pCur ) -/*****************************************************************************/ -{ - if( XMLStrings != NULL ) delete XMLStrings; // Elements ? - - XMLStrings = new XMLHashMap(); - if ( !pCur ) - SearchL10NElements( this ); - else { - if( pCur->GetNodeType()==XML_NODE_TYPE_FILE) { - SearchL10NElements(pCur); - } - } -} - -/*****************************************************************************/ -void XMLFile::View(){ -/*****************************************************************************/ - XMLElement* cur; - for(XMLHashMap::iterator pos=XMLStrings->begin(); pos!=XMLStrings->end();++pos){ - fprintf(stdout,"\nid=%s\n",(pos->first).GetBuffer()); - LangHashMap* elem=pos->second; - for(LangHashMap::iterator pos2=elem->begin(); pos2!=elem->end();++pos2){ - fprintf( stdout,"\nlanguage=%s\n",(pos2->first).GetBuffer() ); - cur=pos2->second; - fprintf(stdout,"\n%s\n",((XMLElement*)cur)->ToOString().getStr()); - - } - } -} - -/*****************************************************************************/ -void XMLFile::InsertL10NElement( XMLElement* pElement ){ -/*****************************************************************************/ - ByteString tmpStr,id,oldref,language(""); - LangHashMap* elem; - - if( pElement->GetAttributeList() != NULL ){ - for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ - tmpStr=ByteString( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); - if( tmpStr.CompareTo(ID)==COMPARE_EQUAL ){ // Get the "id" Attribute - id = ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - } - if( tmpStr.CompareTo( XML_LANG ) == COMPARE_EQUAL ){ // Get the "xml-lang" Attribute - language = ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - } - - } - }else{ - fprintf(stdout,"XMLFile::InsertL10NElement: No AttributeList found"); - fprintf(stdout,"++++++++++++++++++++++++++++++++++++++++++++++++++"); - Print( pElement , 0 ); - fprintf(stdout,"++++++++++++++++++++++++++++++++++++++++++++++++++"); - } - - XMLHashMap::iterator pos = XMLStrings->find( id ); - if( pos == XMLStrings->end() ){ // No instanze , create new one - elem = new LangHashMap(); - (*elem)[ language ]=pElement; - XMLStrings->insert( XMLHashMap::value_type( id , elem ) ); - order.push_back( id ); - }else{ // Already there - elem=pos->second; - if ( (*elem)[ language ] ) - { - fprintf(stdout,"Error: Duplicated entry. ID = %s LANG = %s in File %s\n", id.GetBuffer(), language.GetBuffer(), ByteString( sFullName,RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); - exit( -1 ); - } - (*elem)[ language ]=pElement; - } -} -/*****************************************************************************/ -void XMLFile::showType(XMLParentNode* node){ -/*****************************************************************************/ - switch (node->GetNodeType()){ - case XML_NODE_TYPE_ELEMENT: fprintf(stdout,"ELEMENT\n") ;break; - case XML_NODE_TYPE_FILE: fprintf(stdout,"FILE\n") ;break; - case XML_NODE_TYPE_COMMENT: fprintf(stdout,"COMMENT\n") ;break; - case XML_NODE_TYPE_DATA: fprintf(stdout,"DATA\n") ;break; - case XML_NODE_TYPE_DEFAULT: fprintf(stdout,"DEFAULT\n") ;break; - default: break; - } -} -XMLFile::XMLFile() -/*****************************************************************************/ - : XMLParentNode( NULL ), - ID ( "id" ), - OLDREF ( "oldref" ), - XML_LANG ( "xml-lang" ), - XMLStrings ( NULL ){}; - - -XMLFile::XMLFile( const XMLFile& obj ) -/*****************************************************************************/ - : XMLParentNode( obj ), - sFileName ( obj.sFileName ), - ID ( "id" ), - OLDREF ( "oldref" ), - XML_LANG ( "xml-lang" ), - XMLStrings ( NULL ) -{ - if( this!=&obj ) - { - nodes_localize =obj.nodes_localize; - order =obj.order; - - } -} -/*****************************************************************************/ -XMLFile& XMLFile::operator=(const XMLFile& obj){ -/*****************************************************************************/ - if( this!=&obj ){ - - XMLParentNode::operator=(obj); - - nodes_localize =obj.nodes_localize; - order =obj.order; - - if( XMLStrings ) delete XMLStrings; - - if( obj.XMLStrings ) - { - XMLStrings = new XMLHashMap(); - for( XMLHashMap::iterator pos = obj.XMLStrings->begin() ; pos != obj.XMLStrings->end() ; ++pos ) - { - LangHashMap* elem=pos->second; - LangHashMap* newelem = new LangHashMap(); - for(LangHashMap::iterator pos2=elem->begin(); pos2!=elem->end();++pos2){ - (*newelem)[ pos2->first ] = new XMLElement( *pos2->second ); - printf("*"); - } - (*XMLStrings)[ pos->first ] = newelem; - } - } - } - printf("done!\n"); - return *this; -} - - -/*****************************************************************************/ -void XMLFile::SearchL10NElements( XMLParentNode *pCur , int pos) -/*****************************************************************************/ -{ - static const ByteString LOCALIZE("localize"); - static const ByteString THEID("id"); - bool bInsert = true; - if ( !pCur ) - SearchL10NElements( this ); - else { - switch( pCur->GetNodeType()) { - case XML_NODE_TYPE_FILE: { - XMLParentNode* pElement; - if( GetChildList()){ - for ( ULONG i = 0; i < GetChildList()->Count(); i++ ){ - pElement = (XMLParentNode*) GetChildList()->GetObject( i ); - if( pElement->GetNodeType() == XML_NODE_TYPE_ELEMENT ) SearchL10NElements( pElement , i); - } - } - } - break; - case XML_NODE_TYPE_ELEMENT: { - XMLElement *pElement = ( XMLElement * ) pCur; - ByteString sName(pElement->GetName(),RTL_TEXTENCODING_ASCII_US); - ByteString language,tmpStrVal,oldref; - if ( pElement->GetAttributeList()){ - for ( ULONG j = 0 , cnt = pElement->GetAttributeList()->Count(); j < cnt && bInsert; j++ ){ - const ByteString tmpStr( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); - if( tmpStr.CompareTo(THEID)==COMPARE_EQUAL ){ // Get the "id" Attribute - tmpStrVal=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - //printf("Checking id = %s\n",tmpStrVal.GetBuffer() ); - } - if( tmpStr.CompareTo(LOCALIZE)==COMPARE_EQUAL ){ // Get the "localize" Attribute - bInsert=false; - } - if( tmpStr.CompareTo(XML_LANG)==COMPARE_EQUAL ){ // Get the "xml-lang" Attribute - language=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - } - if( tmpStr.CompareTo(OLDREF)==COMPARE_EQUAL ){ // Get the "oldref" Attribute - oldref=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - } - } - pElement->SetLanguageId ( language ); - pElement->SetId ( tmpStrVal.GetBuffer() ); - pElement->SetOldRef ( oldref ); - pElement->SetPos( pos ); - } - - if ( bInsert && ( nodes_localize.find( sName.ToLowerAscii() ) != nodes_localize.end() ) ) - InsertL10NElement(pElement); - else if ( bInsert && pElement->GetChildList() ){ - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) - SearchL10NElements( (XMLParentNode*) pElement->GetChildList()->GetObject( k ) , k); - } - } - break; - case XML_NODE_TYPE_DATA: { - } - break; - case XML_NODE_TYPE_COMMENT: { - } - break; - case XML_NODE_TYPE_DEFAULT: { - } - break; - } - } -} - -/*****************************************************************************/ -bool XMLFile::CheckExportStatus( XMLParentNode *pCur ) -/*****************************************************************************/ -{ - static bool bStatusExport = true; - const ByteString LOCALIZE("localize"); - const ByteString STATUS("status"); - const ByteString PUBLISH("PUBLISH"); - const ByteString DEPRECATED("DEPRECATED"); - - const ByteString TOPIC("topic"); - bool bInsert = true; - if ( !pCur ) - CheckExportStatus( this ); - else { - switch( pCur->GetNodeType()) { - case XML_NODE_TYPE_FILE: { - XMLParentNode* pElement; - if( GetChildList()){ - for ( ULONG i = 0; i < GetChildList()->Count(); i++ ){ - pElement = (XMLParentNode*) GetChildList()->GetObject( i ); - if( pElement->GetNodeType() == XML_NODE_TYPE_ELEMENT ) CheckExportStatus( pElement );//, i); - } - } - } - break; - case XML_NODE_TYPE_ELEMENT: { - XMLElement *pElement = ( XMLElement * ) pCur; - ByteString sName(pElement->GetName(),RTL_TEXTENCODING_ASCII_US); - if( sName.EqualsIgnoreCaseAscii( TOPIC ) ){ - if ( pElement->GetAttributeList()){ - for ( ULONG j = 0 , cnt = pElement->GetAttributeList()->Count(); j < cnt && bInsert; j++ ){ - const ByteString tmpStr( *pElement->GetAttributeList()->GetObject( j ),RTL_TEXTENCODING_UTF8 ); - if( tmpStr.EqualsIgnoreCaseAscii( STATUS ) ){ - ByteString tmpStrVal=ByteString( pElement->GetAttributeList()->GetObject( j )->GetValue(),RTL_TEXTENCODING_UTF8 ); - if( !tmpStrVal.EqualsIgnoreCaseAscii( PUBLISH ) && - !tmpStrVal.EqualsIgnoreCaseAscii( DEPRECATED )){ - bStatusExport = false; - } - } - - } - } - } - else if ( pElement->GetChildList() ){ - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ) - CheckExportStatus( (XMLParentNode*) pElement->GetChildList()->GetObject( k ) );//, k); - } - } - break; - } - } - return bStatusExport; -} - -/*****************************************************************************/ -USHORT XMLElement::GetNodeType() -/*****************************************************************************/ -{ - return XML_NODE_TYPE_ELEMENT; -} - -/*****************************************************************************/ -XMLElement::XMLElement(const XMLElement& obj) -/*****************************************************************************/ - : - XMLParentNode ( obj ), - sElementName ( obj.sElementName ), - pAttributes ( NULL ), - project ( obj.project ), - filename ( obj.filename ), - id ( obj.id ), - sOldRef ( obj.sOldRef ), - resourceType ( obj.resourceType ), - languageId ( obj.languageId ), - nPos ( obj.nPos ) - -{ - if ( obj.pAttributes ){ - pAttributes = new XMLAttributeList(); - for ( ULONG i = 0; i < obj.pAttributes->Count(); i++ ) - AddAttribute( *obj.pAttributes->GetObject( i ) , obj.pAttributes->GetObject( i )->GetValue() ); - } -} - -/*****************************************************************************/ -XMLElement& XMLElement::operator=(const XMLElement& obj){ -/*****************************************************************************/ - if( this!=&obj ){ - XMLParentNode::operator=(obj); - sElementName =obj.sElementName; - project =obj.project; - filename =obj.filename; - id =obj.id; - sOldRef =obj.sOldRef; - resourceType =obj.resourceType; - languageId =obj.languageId; - nPos =obj.nPos; - - if ( pAttributes ){ - for ( ULONG i = 0; i < pAttributes->Count(); i++ ) - delete pAttributes->GetObject( i ); - delete pAttributes; - } - if ( obj.pAttributes ){ - pAttributes =new XMLAttributeList(); - for ( ULONG i = 0; i < obj.pAttributes->Count(); i++ ) - AddAttribute( *obj.pAttributes->GetObject( i ) , obj.pAttributes->GetObject( i )->GetValue() ); - } - } - return *this; -} - -/*****************************************************************************/ -void XMLElement::AddAttribute( const String &rAttribute, const String &rValue ) -/*****************************************************************************/ -{ - if ( !pAttributes ) - pAttributes = new XMLAttributeList(); - pAttributes->Insert( new XMLAttribute( rAttribute, rValue ), LIST_APPEND ); -} - -/*****************************************************************************/ -void XMLElement::ChangeLanguageTag( const String &rValue ){ -/*****************************************************************************/ - static const String rName = String::CreateFromAscii("xml-lang"); - SetLanguageId( ByteString(rValue,RTL_TEXTENCODING_UTF8) ); - if ( pAttributes ){ - for ( ULONG i = 0; i < pAttributes->Count(); i++ ){ - if ( *pAttributes->GetObject( i ) == rName ){ - pAttributes->GetObject( i )->setValue(rValue); - } - } - } - XMLChildNode* pNode = NULL; - XMLElement* pElem = NULL; - XMLChildNodeList* pCList = GetChildList(); - - if( pCList != NULL ){ - for ( ULONG i = 0; i < pCList->Count(); i++ ){ - pNode = pCList->GetObject( i ); - if( pNode != NULL && pNode->GetNodeType() == XML_NODE_TYPE_ELEMENT ){ - pElem = static_cast< XMLElement* >(pNode); - pElem->ChangeLanguageTag( rValue ); - pElem->SetLanguageId( ByteString(rValue,RTL_TEXTENCODING_UTF8) ); - pElem = NULL; - pNode = NULL; - } - } - pCList = NULL; - } -} -/*****************************************************************************/ -XMLAttribute *XMLElement::GetAttribute( const String &rName ) -/*****************************************************************************/ -{ - if ( pAttributes ) - for ( ULONG i = 0; i < pAttributes->Count(); i++ ) - if ( *pAttributes->GetObject( i ) == rName ) - return pAttributes->GetObject( i ); - - return NULL; -} - -/*****************************************************************************/ -XMLElement::~XMLElement() -/*****************************************************************************/ -{ - if ( pAttributes ) { - for ( ULONG i = 0; i < pAttributes->Count(); i++ ) - delete pAttributes->GetObject( i ); - - delete pAttributes; - pAttributes = NULL; - } -} -/*****************************************************************************/ -bool XMLElement::Equals(OUString refStr){ -/*****************************************************************************/ - return refStr.equals( ToOUString() ); -} - -/*****************************************************************************/ -OString XMLElement::ToOString(){ -/*****************************************************************************/ - OUString ouEmpty; - - OUStringBuffer* buffer = new OUStringBuffer(); - Print( this, *buffer , true ); - - OString result( (sal_Unicode* )buffer->getStr(), buffer->getLength() , RTL_TEXTENCODING_UTF8 ); - delete buffer; - return result; -} -/*****************************************************************************/ -OUString XMLElement::ToOUString(){ -/*****************************************************************************/ - OUStringBuffer* buffer = new OUStringBuffer(); - Print(this,*buffer,true); - OUString result=buffer->makeStringAndClear(); - String xy(result.getStr()); - result=OUString(xy); - delete buffer; - return result; -} -/*****************************************************************************/ -void XMLElement::Print(XMLNode *pCur, OUStringBuffer& buffer , bool rootelement ){ -/*****************************************************************************/ - //YD FIXME somewhere COMMENT is defined as 4! - static const String _COMMENT = String::CreateFromAscii("comment"); - static const OUString XML_LANG ( OUString::createFromAscii("xml-lang") ); - - if(pCur!=NULL){ - if(rootelement){ - XMLElement *pElement = ( XMLElement * ) pCur; - if ( pElement->GetAttributeList()){ - if ( pElement->GetChildList()){ - XMLChildNode* tmp=NULL; - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ){ - tmp=pElement->GetChildList()->GetObject( k ); - Print( tmp, buffer , false); - } - } - } - } - else{ - - switch( pCur->GetNodeType()) { - case XML_NODE_TYPE_ELEMENT: { - XMLElement *pElement = ( XMLElement * ) pCur; - - if( !pElement->GetName().EqualsIgnoreCaseAscii( _COMMENT ) ){ - buffer.append( OUString::createFromAscii("\\<") ); - buffer.append( pElement->GetName() ); - if ( pElement->GetAttributeList()){ - for ( ULONG j = 0; j < pElement->GetAttributeList()->Count(); j++ ){ - - OUString aAttrName( *pElement->GetAttributeList()->GetObject( j ) ); - if( !aAttrName.equalsIgnoreAsciiCase( XML_LANG ) ) { - buffer.append( OUString::createFromAscii(" ") ); - buffer.append( aAttrName ); - buffer.append( OUString::createFromAscii("=") ); - buffer.append( OUString::createFromAscii("\\\"") ); - buffer.append( pElement->GetAttributeList()->GetObject( j )->GetValue() ); - buffer.append( OUString::createFromAscii("\\\"") ); - } - } - } - if ( !pElement->GetChildList()) - buffer.append( OUString::createFromAscii("/\\>") ); - else { - buffer.append( OUString::createFromAscii("\\>") ); - XMLChildNode* tmp=NULL; - for ( ULONG k = 0; k < pElement->GetChildList()->Count(); k++ ){ - tmp=pElement->GetChildList()->GetObject( k ); - Print( tmp, buffer , false); - } - buffer.append( OUString::createFromAscii("\\GetName() ); - buffer.append( OUString::createFromAscii("\\>") ); - } - } - } - break; - case XML_NODE_TYPE_DATA: { - XMLData *pData = ( XMLData * ) pCur; - String sData = pData->GetData(); - buffer.append( sData ); - } - break; - case XML_NODE_TYPE_COMMENT: { - XMLComment *pComment = ( XMLComment * ) pCur; - buffer.append( OUString::createFromAscii("") ); - } - break; - case XML_NODE_TYPE_DEFAULT: { - XMLDefault *pDefault = ( XMLDefault * ) pCur; - buffer.append( pDefault->GetDefault() ); - } - break; - } - } - }else { - fprintf(stdout,"\n#+------Error: NULL Pointer in XMLELement::Print------+#\n"); - return; - } -} - - -// -// class XMLData -// -/*****************************************************************************/ -XMLData::XMLData(const XMLData& obj) -/*****************************************************************************/ - : XMLChildNode( obj ), - sData( obj.sData ) , - isNewCreated ( obj.isNewCreated ){} - -/*****************************************************************************/ -XMLData& XMLData::operator=(const XMLData& obj){ -/*****************************************************************************/ - if( this!=&obj ){ - XMLChildNode::operator=( obj ); - sData = obj.sData; - isNewCreated = obj.isNewCreated; - } - return *this; -} -/*****************************************************************************/ -void XMLData::AddData( const String &rData) { -/*****************************************************************************/ - sData += rData; -} - -/*****************************************************************************/ -USHORT XMLData::GetNodeType() -/*****************************************************************************/ -{ - return XML_NODE_TYPE_DATA; -} - -// -// class XMLComment -// - -/*****************************************************************************/ -USHORT XMLComment::GetNodeType() -/*****************************************************************************/ -{ - return XML_NODE_TYPE_COMMENT; -} -/*****************************************************************************/ -XMLComment::XMLComment(const XMLComment& obj) -/*****************************************************************************/ - : XMLChildNode( obj ), - sComment( obj.sComment ){} - -/*****************************************************************************/ -XMLComment& XMLComment::operator=(const XMLComment& obj){ -/*****************************************************************************/ - if( this!=&obj ){ - XMLChildNode::operator=( obj ); - sComment = obj.sComment; - } - return *this; -} - -// -// class XMLDefault -// - -/*****************************************************************************/ -USHORT XMLDefault::GetNodeType() -/*****************************************************************************/ -{ - return XML_NODE_TYPE_DEFAULT; -} -/*****************************************************************************/ -XMLDefault::XMLDefault(const XMLDefault& obj) -/*****************************************************************************/ - : XMLChildNode( obj ), - sDefault( obj.sDefault){} - -/*****************************************************************************/ -XMLDefault& XMLDefault::operator=(const XMLDefault& obj){ -/*****************************************************************************/ - if( this!=&obj ){ - XMLChildNode::operator=( obj ); - sDefault = obj.sDefault; - } - return *this; -} - - -// -// class SimpleXMLParser -// - -#define XML_CHAR_TO_OUSTRING(x) OStringToOUString(OString(x), RTL_TEXTENCODING_UTF8) -#define XML_CHAR_N_TO_OUSTRING(x,n) OStringToOUString(OString(x,n), RTL_TEXTENCODING_UTF8 ) - - -/*****************************************************************************/ -SimpleXMLParser::SimpleXMLParser() -/*****************************************************************************/ - : pXMLFile( NULL ) -{ - aParser = XML_ParserCreate( NULL ); - XML_SetUserData( aParser, this ); - XML_SetElementHandler( aParser, (XML_StartElementHandler) StartElementHandler, (XML_EndElementHandler) EndElementHandler ); - XML_SetCharacterDataHandler( aParser, (XML_CharacterDataHandler) CharacterDataHandler ); - XML_SetCommentHandler( aParser, (XML_CommentHandler) CommentHandler ); - XML_SetDefaultHandler( aParser, (XML_DefaultHandler) DefaultHandler ); -} - -/*****************************************************************************/ -SimpleXMLParser::~SimpleXMLParser() -/*****************************************************************************/ -{ - XML_ParserFree( aParser ); -} - -/*****************************************************************************/ -void SimpleXMLParser::StartElementHandler( - void *userData, const XML_Char *name, const XML_Char **atts ) -/*****************************************************************************/ -{ - (( SimpleXMLParser * ) userData )->StartElement( name, atts ); -} - - -/*****************************************************************************/ -void SimpleXMLParser::EndElementHandler( - void *userData, const XML_Char *name ) -/*****************************************************************************/ -{ - (( SimpleXMLParser * ) userData )->EndElement( name ); -} - -/*****************************************************************************/ -void SimpleXMLParser::CharacterDataHandler( - void *userData, const XML_Char *s, int len ) -/*****************************************************************************/ -{ - (( SimpleXMLParser * ) userData )->CharacterData( s, len ); -} - -/*****************************************************************************/ -void SimpleXMLParser::CommentHandler( - void *userData, const XML_Char *data ) -/*****************************************************************************/ -{ - (( SimpleXMLParser * ) userData )->Comment( data ); -} - -/*****************************************************************************/ -void SimpleXMLParser::DefaultHandler( - void *userData, const XML_Char *s, int len ) -/*****************************************************************************/ -{ - (( SimpleXMLParser * ) userData )->Default( s, len ); -} - -/*****************************************************************************/ -void SimpleXMLParser::StartElement( - const XML_Char *name, const XML_Char **atts ) -/*****************************************************************************/ -{ - String sElementName = String( XML_CHAR_TO_OUSTRING( name )); - XMLElement *pElement = new XMLElement( sElementName, ( XMLParentNode * ) pCurNode ); - pCurNode = pElement; - pCurData = NULL; - - int i = 0; - while( atts[i] ) { - pElement->AddAttribute( - String( XML_CHAR_TO_OUSTRING( atts[ i ] )), - String( XML_CHAR_TO_OUSTRING( atts[ i + 1 ] ))); - i += 2; - } -} - -/*****************************************************************************/ -void SimpleXMLParser::EndElement( const XML_Char *name ) -/*****************************************************************************/ -{ - // This variable is not used at all, but the the sax C interface can't be changed - // To prevent warnings this dummy assignment is used - // +++ - (void) name; - - pCurNode = pCurNode->GetParent(); - pCurData = NULL; -} - -/*****************************************************************************/ -void SimpleXMLParser::CharacterData( - const XML_Char *s, int len ) -/*****************************************************************************/ -{ - if ( !pCurData ){ - String x=String( XML_CHAR_N_TO_OUSTRING( s, len )); - XMLUtil::UnQuotHTML(x); - pCurData = new XMLData( x , pCurNode ); - }else{ - String x=String( XML_CHAR_N_TO_OUSTRING( s, len )); - XMLUtil::UnQuotHTML(x); - pCurData->AddData( x ); - - } -} - -/*****************************************************************************/ -void SimpleXMLParser::Comment( - const XML_Char *data ) -/*****************************************************************************/ -{ - pCurData = NULL; - new XMLComment( String( XML_CHAR_TO_OUSTRING( data )), pCurNode ); -} - -/*****************************************************************************/ -void SimpleXMLParser::Default( - const XML_Char *s, int len ) -/*****************************************************************************/ -{ - pCurData = NULL; - new XMLDefault( - String( XML_CHAR_N_TO_OUSTRING( s, len )), pCurNode ); -} - -/*****************************************************************************/ -XMLFile *SimpleXMLParser::Execute( const String &rFullFileName , const String &rFileName, XMLFile* pXMLFileIn ) -/*****************************************************************************/ -{ -// printf("DBG: SimpleXMLParser::Execute( %s )", ByteString( rFileName , RTL_TEXTENCODING_ASCII_US ).GetBuffer() ); - aErrorInformation.eCode = XML_ERROR_NONE; - aErrorInformation.nLine = 0; - aErrorInformation.nColumn = 0; - aErrorInformation.sMessage = String::CreateFromAscii( "ERROR: Unable to open file " ); - aErrorInformation.sMessage += rFileName; - - SvFileStream aStream( rFileName, STREAM_STD_READ ); - - if ( !aStream.IsOpen()) - return NULL; - - SvMemoryStream aMemStream; - aStream >> aMemStream; - aMemStream.Seek( 0 ); - - aStream.Close(); - - pXMLFile = pXMLFileIn; - pXMLFile->SetName( rFileName ); - pXMLFile->SetFullName( rFullFileName ); - - return Execute( &aMemStream ); -} - -/*****************************************************************************/ -XMLFile *SimpleXMLParser::Execute( SvMemoryStream *pStream ) -/*****************************************************************************/ -{ - if ( !pXMLFile ) - pXMLFile = new XMLFile( String()); - - pCurNode = pXMLFile; - pCurData = NULL; - - ULONG nPos = pStream->Tell(); - pStream->Seek( STREAM_SEEK_TO_END ); - - aErrorInformation.eCode = XML_ERROR_NONE; - aErrorInformation.nLine = 0; - aErrorInformation.nColumn = 0; - if ( pXMLFile->GetName().Len()) { - aErrorInformation.sMessage = String::CreateFromAscii( "File " ); - aErrorInformation.sMessage += pXMLFile->GetName(); - aErrorInformation.sMessage += String::CreateFromAscii( " parsed succesfully" ); - } - else - aErrorInformation.sMessage = String::CreateFromAscii( "XML-File parsed successfully" ); - - if ( !XML_Parse( - aParser, ( char * ) pStream->GetData() + nPos, pStream->Tell() - nPos, TRUE )) - { - aErrorInformation.eCode = XML_GetErrorCode( aParser ); - aErrorInformation.nLine = XML_GetErrorLineNumber( aParser ); - aErrorInformation.nColumn = XML_GetErrorColumnNumber( aParser ); - - aErrorInformation.sMessage = String::CreateFromAscii( "ERROR: " ); - if ( pXMLFile->GetName().Len()) - aErrorInformation.sMessage += pXMLFile->GetName(); - else - aErrorInformation.sMessage += String::CreateFromAscii( "XML-File" ); - aErrorInformation.sMessage += String::CreateFromAscii( " (" ); - aErrorInformation.sMessage += String::CreateFromInt64( aErrorInformation.nLine ); - aErrorInformation.sMessage += String::CreateFromAscii( "," ); - aErrorInformation.sMessage += String::CreateFromInt64( aErrorInformation.nColumn ); - aErrorInformation.sMessage += String::CreateFromAscii( "): " ); - - switch( aErrorInformation.eCode ) { - case XML_ERROR_NO_MEMORY: aErrorInformation.sMessage += String::CreateFromAscii( "No memory" ); break; - case XML_ERROR_SYNTAX: aErrorInformation.sMessage += String::CreateFromAscii( "Syntax" ); break; - case XML_ERROR_NO_ELEMENTS: aErrorInformation.sMessage += String::CreateFromAscii( "No elements" ); break; - case XML_ERROR_INVALID_TOKEN: aErrorInformation.sMessage += String::CreateFromAscii( "Invalid token" ); break; - case XML_ERROR_UNCLOSED_TOKEN: aErrorInformation.sMessage += String::CreateFromAscii( "Unclosed token" ); break; - case XML_ERROR_PARTIAL_CHAR: aErrorInformation.sMessage += String::CreateFromAscii( "Partial char" ); break; - case XML_ERROR_TAG_MISMATCH: aErrorInformation.sMessage += String::CreateFromAscii( "Tag mismatch" ); break; - case XML_ERROR_DUPLICATE_ATTRIBUTE: aErrorInformation.sMessage += String::CreateFromAscii( "Dublicat attribute" ); break; - case XML_ERROR_JUNK_AFTER_DOC_ELEMENT: aErrorInformation.sMessage += String::CreateFromAscii( "Junk after doc element" ); break; - case XML_ERROR_PARAM_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Param entity ref" ); break; - case XML_ERROR_UNDEFINED_ENTITY: aErrorInformation.sMessage += String::CreateFromAscii( "Undefined entity" ); break; - case XML_ERROR_RECURSIVE_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Recursive entity ref" ); break; - case XML_ERROR_ASYNC_ENTITY: aErrorInformation.sMessage += String::CreateFromAscii( "Async_entity" ); break; - case XML_ERROR_BAD_CHAR_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Bad char ref" ); break; - case XML_ERROR_BINARY_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Binary entity" ); break; - case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: aErrorInformation.sMessage += String::CreateFromAscii( "Attribute external entity ref" ); break; - case XML_ERROR_MISPLACED_XML_PI: aErrorInformation.sMessage += String::CreateFromAscii( "Misplaced xml pi" ); break; - case XML_ERROR_UNKNOWN_ENCODING: aErrorInformation.sMessage += String::CreateFromAscii( "Unknown encoding" ); break; - case XML_ERROR_INCORRECT_ENCODING: aErrorInformation.sMessage += String::CreateFromAscii( "Incorrect encoding" ); break; - case XML_ERROR_UNCLOSED_CDATA_SECTION: aErrorInformation.sMessage += String::CreateFromAscii( "Unclosed cdata section" ); break; - case XML_ERROR_EXTERNAL_ENTITY_HANDLING: aErrorInformation.sMessage += String::CreateFromAscii( "External entity handling" ); break; - case XML_ERROR_NOT_STANDALONE: aErrorInformation.sMessage += String::CreateFromAscii( "Not standalone" ); break; - case XML_ERROR_NONE: break; - default: - break; - - } - delete pXMLFile; - pXMLFile = NULL; - } - pStream->Seek( nPos ); - - return pXMLFile; -} - -/*****************************************************************************/ -void XMLUtil::QuotHTML( String &rString ) -/*****************************************************************************/ -{ - OUStringBuffer sReturn; - static const String LT(String::CreateFromAscii("<")); - static const String QLT(String::CreateFromAscii("<")); - static const String GT(String::CreateFromAscii(">")); - static const String QGT(String::CreateFromAscii(">")); - static const String QUOT(String::CreateFromAscii("\\")); - static const String QQUOT(String::CreateFromAscii(""")); - static const String APOS(String::CreateFromAscii("\"")); - static const String QAPOS(String::CreateFromAscii("'")); - static const String AMP(String::CreateFromAscii("&")); - static const String QAMP(String::CreateFromAscii("&")); - static const String SLASH(String::CreateFromAscii("\\")); - - for ( USHORT i = 0; i < rString.Len(); i++) { - if ( i < rString.Len()) { - switch ( rString.GetChar( i )) { - case '\\': if( i+1 <= rString.Len() ){ - switch( rString.GetChar( i+1 ) ){ - case '<': sReturn.append( LT );i++;break; - case '>': sReturn.append( GT );i++;break; - case '\\': sReturn.append( QUOT );i++;break; - case '\"': sReturn.append( APOS );i++;break; - //case '\'': sReturn += "\'";i++;break; - //case '&' : sRetrun += "&";i++;break; - default: sReturn.append( SLASH );break; - - } - } - break; - - case '<': - sReturn.append( QLT ); - break; - - case '>': - sReturn.append( QGT ); - break; - - case '\"': - sReturn.append( QQUOT ); - break; - -/* case '\'': - sReturn += "'"; - break; -*/ - case '&': - if ( - ( ( i + 4 ) < rString.Len()) && - ( String( rString.Copy( i, 5 ) ).Equals( QAMP ) ) - ) - sReturn.append( rString.GetChar( i ) ); - else - sReturn.append( QAMP ); - break; - - default: - sReturn.append( rString.GetChar( i ) ); - break; - } - } - } - rString = String( sReturn.makeStringAndClear() ); -} - -void XMLUtil::UnQuotHTML( String &rString ){ - UnQuotData( rString ); -} - -void XMLUtil::UnQuotData( String &rString_in ){ - ByteString sReturn; - ByteString sString( rString_in , RTL_TEXTENCODING_UTF8 ); - while ( sString.Len()) { - if ( sString.Copy( 0, 1 ) == "\\" ) { - sReturn += "\\\\"; - sString.Erase( 0, 1 ); - } - else if ( sString.Copy( 0, 5 ) == "&" ) { - sReturn += "&"; - sString.Erase( 0, 5 ); - } - else if ( sString.Copy( 0, 4 ) == "<" ) { - sReturn += "<"; - sString.Erase( 0, 4 ); - } - else if ( sString.Copy( 0, 4 ) == ">" ) { - sReturn += ">"; - sString.Erase( 0, 4 ); - } - else if ( sString.Copy( 0, 6 ) == """ ) { - sReturn += "\""; - sString.Erase( 0, 6 ); - } - else if ( sString.Copy( 0, 6 ) == "'" ) { - sReturn += "\'"; - sString.Erase( 0, 6 ); - } - else { - sReturn += sString.GetChar( 0 ); - sString.Erase( 0, 1 ); - } - } - rString_in = String(sReturn , RTL_TEXTENCODING_UTF8 ); - - -} - -XMLUtil::XMLUtil(){ -} - - -/*****************************************************************************/ -void XMLUtil::dump(){ -/*****************************************************************************/ - int cnt=1; - printf("size=%lu\n",static_cast(lMap.size())); - for(HashMap::iterator pos = lMap.begin(); pos != lMap.end() ; ++pos){ - fprintf(stdout,"key=%s , value=%d , no=%d\n",pos->first.GetBuffer(),pos->second,cnt++); - } -} -/*****************************************************************************/ -XMLUtil& XMLUtil::Instance(){ -/*****************************************************************************/ - static XMLUtil instance; - return instance; -} -/*****************************************************************************/ -XMLUtil::~XMLUtil(){} -/*****************************************************************************/ -/*****************************************************************************/ -ByteString XMLUtil::GetIsoLangByIndex( USHORT nIndex ) -/*****************************************************************************/ -{ - if(nIndex > 0 && MAX_LANGUAGES >= nIndex ) - return isoArray[nIndex]; - return ""; -} - diff --git a/transex3/source/xrm_yy_wrapper.c b/transex3/source/xrm_yy_wrapper.c deleted file mode 100644 index 6a304d0d09dc..000000000000 --- a/transex3/source/xrm_yy_wrapper.c +++ /dev/null @@ -1,2 +0,0 @@ -// Helper to suppress warnings in lex generated c code, see #i57362# -#include "xrm_yy.c" diff --git a/transex3/source/xrmlex.l b/transex3/source/xrmlex.l deleted file mode 100644 index efc8bf1f7d91..000000000000 --- a/transex3/source/xrmlex.l +++ /dev/null @@ -1,228 +0,0 @@ -%{ -/* - * lexer for parsing xml-property source files (*.xml) - * - */ - - -/* enlarge token buffer to tokenize whole strings */ -#undef YYLMAX -#define YYLMAX 64000 - -/* to enable debug output define LEXDEBUG */ -#define LEXDEBUG 1 -#ifdef LEXDEBUG -#define OUTPUT fprintf -#else -#define OUTPUT(Par1,Par2); -#endif - -/* table of possible token ids */ -#include "tokens.h" -#include -#include - -#if defined __GNUC__ -#pragma GCC system_header -#elif defined __SINPRO_CC -#pragma disable_warn -#elif defined _MSC_VER -#pragma warning(push, 1) -#endif - -/* external functions (C++ code, declared as extren "C" */ -extern int WorkOnTokenSet( int, char* ); -extern int Argument( char * ); -extern int InitXrmExport( char * , char * ); -extern int EndXrmExport(); -extern int GetError(); -extern int SetError(); -extern char *GetOutputFile( int argc, char* argv[]); -extern FILE *GetXrmFile(); -extern int isQuiet(); -extern void removeTempFile(); -extern char* getFilename(); - -/* forwards */ -void YYWarning(); - -int bText=0; -%} - -%p 24000 -%e 1200 -%n 500 - -%% - -"]*\> { - WorkOnTokenSet( XRM_README_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_README_END, yytext ); -} - -"]*\> { - WorkOnTokenSet( XRM_README_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_README_END, yytext ); -} - -"]*\> { - WorkOnTokenSet( XRM_SECTION_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_SECTION_END, yytext ); -} - -"]*\> { - WorkOnTokenSet( XRM_PARAGRAPH_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_PARAGRAPH_END, yytext ); -} - -"]*\> { - WorkOnTokenSet( XRM_TEXT_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_TEXT_END, yytext ); -} - -"]*\> { - WorkOnTokenSet( XRM_LIST_START, yytext ); -} - -"" { - WorkOnTokenSet( XRM_LIST_END, yytext ); -} - -"